Skip to content

Commit

Permalink
Initial blockchain commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pkakelas committed Dec 8, 2018
0 parents commit 56c49b1
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 0 deletions.
39 changes: 39 additions & 0 deletions block.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const sha256 = require('sha256')

type Data = any

type BlockArguments = {
id: number,
timestamp: number,
data: any,
nonce: string
previousHash: string
}

export default class Block {
public index = 0
public timestamp: number
public data: any
public previousHash: string
public hash: string
public nonce: string

constructor (args: BlockArguments) {
this.index = args.id
this.timestamp = args.timestamp
this.data = args.data
this.nonce = args.nonce
this.previousHash = args.previousHash

this.hash = this.calculateHash()
}

calculateHash (): string {
const toBeHashed = this.previousHash + (this.index + this.timestamp + this.data + this.nonce)

return sha256(toBeHashed)
}

mineBlock (difficulty) {
}
}
51 changes: 51 additions & 0 deletions blockchain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Block from './block'

export default class Blockchain {
private chain: Block[] = []
constructor() {
this.chain.push(this.createGenesisBlock())
}

public createGenesisBlock(): Block {
return new Block({
id: 0,
timestamp: Date.now(),
data: "Initial Block",
previousHash: "",
nonce: "0"
})
}

public getLatestBlock (): Block {
return this.chain[this.getChainLength() - 1]
}

public getChainLength(): number {
return this.chain.length
}

public addBlock (data): void {
const block = new Block({
id: this.getChainLength(),
timestamp: Date.now(),
data: data,
previousHash: this.getLatestBlock().hash,
nonce: "0"
})

this.chain.push(block)
}

public checkValid (): boolean {
for (let i = this.getChainLength() - 1; i > 0; --i) {
const currentBlock = this.chain[i]
const previousBlock = this.chain[i - 1]

if (currentBlock.previousHash != previousBlock.hash) {
return false
}
}

return true
}
}
9 changes: 9 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Blockchain from './blockchain'
import Block from './block'

let chain = new Blockchain();
chain.addBlock({amount: 5})
chain.addBlock({amount: 10})

console.log(JSON.stringify(chain, null, 4))
console.log("Is blockchain valid? " + chain.checkValid())
16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "blockchain",
"version": "1.0.0",
"description": "",
"main": "block.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/node": "^10.12.12",
"sha256": "^0.2.0",
"sjcl": "^1.0.8"
}
}

0 comments on commit 56c49b1

Please sign in to comment.