├── README.md └── main.js /README.md: -------------------------------------------------------------------------------- 1 | # js-blockchain-pt1 -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | const SHA256 = require('crypto-js/sha256') 2 | 3 | class Block { 4 | constructor(index, timestamp, data, previousHash) { 5 | this.index = index; 6 | this.timestamp = timestamp; 7 | this.data = data; 8 | this.previousHash = previousHash; 9 | this.hash = this.calculateHash(); 10 | this.nonce = 0; 11 | } 12 | 13 | calculateHash() { 14 | return SHA256(this.index + this.previousHash + this.timestamp + this.data + this.nonce).toString(); 15 | } 16 | 17 | mineBlock(difficulty) { 18 | 19 | } 20 | } 21 | 22 | class Blockchain{ 23 | constructor() { 24 | this.chain = [this.createGenesis()]; 25 | } 26 | 27 | createGenesis() { 28 | return new Block(0, "01/01/2017", "Genesis block", "0") 29 | } 30 | 31 | latestBlock() { 32 | return this.chain[this.chain.length - 1] 33 | } 34 | 35 | addBlock(newBlock){ 36 | newBlock.previousHash = this.latestBlock().hash; 37 | newBlock.hash = newBlock.calculateHash(); 38 | this.chain.push(newBlock); 39 | } 40 | 41 | checkValid() { 42 | for(let i = 1; i < this.chain.length; i++) { 43 | const currentBlock = this.chain[i]; 44 | const previousBlock = this.chain[i - 1]; 45 | 46 | if (currentBlock.hash !== currentBlock.calculateHash()) { 47 | return false; 48 | } 49 | 50 | if (currentBlock.previousHash !== previousBlock.hash) { 51 | return false; 52 | } 53 | } 54 | 55 | return true; 56 | } 57 | } 58 | 59 | let jsChain = new Blockchain(); 60 | jsChain.addBlock(new Block("12/25/2017", {amount: 5})); 61 | jsChain.addBlock(new Block("12/26/2017", {amount: 10})); 62 | 63 | 64 | console.log(JSON.stringify(jsChain, null, 4)); 65 | console.log("Is blockchain valid? " + jsChain.checkValid()); --------------------------------------------------------------------------------