v6 initial commit, maybe more to follow
This commit is contained in:
parent
7f91be86c0
commit
d6a32870bc
34 changed files with 16875 additions and 0 deletions
45
blockchain/index.js
Normal file
45
blockchain/index.js
Normal file
|
@ -0,0 +1,45 @@
|
|||
const Block = require('./block');
|
||||
|
||||
class Blockchain {
|
||||
constructor() {
|
||||
this.chain = [Block.genesis()];
|
||||
}
|
||||
|
||||
addBlock(data) {
|
||||
const block = Block.mineBlock(this.chain[this.chain.length-1], data);
|
||||
this.chain.push(block);
|
||||
|
||||
return block;
|
||||
}
|
||||
|
||||
isValidChain(chain) {
|
||||
if(JSON.stringify(chain[0]) !== JSON.stringify(Block.genesis())) return false;
|
||||
|
||||
for (let i=1; i<chain.length; i++) {
|
||||
const block = chain[i];
|
||||
const lastBlock = chain[i-1];
|
||||
|
||||
if (block.lastHash !== lastBlock.hash ||
|
||||
block.hash !== Block.blockHash(block)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
replaceChain(newChain) {
|
||||
if (newChain.length <= this.chain.length) {
|
||||
console.log('Received chain is not longer than the current chain.');
|
||||
return;
|
||||
} else if (!this.isValidChain(newChain)) {
|
||||
console.log('The received chain is not valid.');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Replacing blockchain with the new chain.');
|
||||
this.chain = newChain;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Blockchain;
|
Loading…
Add table
Add a link
Reference in a new issue