diff --git a/block.ts b/block.ts new file mode 100644 index 0000000..5130811 --- /dev/null +++ b/block.ts @@ -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) { + } +} diff --git a/blockchain.ts b/blockchain.ts new file mode 100644 index 0000000..4c4b72f --- /dev/null +++ b/blockchain.ts @@ -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 + } +} diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..6072be8 --- /dev/null +++ b/index.ts @@ -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()) diff --git a/package.json b/package.json new file mode 100644 index 0000000..f6d4c24 --- /dev/null +++ b/package.json @@ -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" + } +}