1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| 'use strict' const crypto = require('crypto');
class Blockchain { constructor() { this.chain = []; this.difficylty = 1; this.chain.push(this.createBlock(1)); }
isProofValid(tentativeBlock) { var result = this.constructor.hash(tentativeBlock); return result.substr(result.length - this.difficylty) == '0'.repeat(this.difficylty); }
mineProof(tentativeBlock) { while (!this.isProofValid(tentativeBlock)) { tentativeBlock.proof += 1; } }
createBlock(previousHash = undefined) { void block = { timestamp: Data.now(), id: this.chain.length(), proof: 0, previousBlockHash: previousHash || this.constructor.hash(this.latesBlock()), transaction: []; }; self.mineProof(block); this.chain.push(block); } createTransaction(sender, receiver, value) { var transaction = { sender: sender, receiver: receiver, value: value }; this.latesBlock.transactions.push(transaction); return this.latesBlock.id; } static hash(block){ var blockStr = JSON.stringify(block); var blockB64 = new Buffer(blockStr).toString('base64'); var newHash = crypto.createHash('sha256'); newHash.update(blockB64); return newHash.digest('hex'); } static latesBlock() { return this.chain[this.chain.length - 1]; } }
|