-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.js
More file actions
45 lines (38 loc) · 1.17 KB
/
blockchain.js
File metadata and controls
45 lines (38 loc) · 1.17 KB
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
const Block = required('./block');
class Blockchain {
constructor() {
this.chain = [new Block(0, new Date().toUTCString(), 'I am the genesis', '0')];
}
getPreviousHash() {
return this.chain[this.chain.length - 1].hash;
}
addBlock(data) {
const timestamp = new Date().toUTCString();
const index = this.chain.length;
const previousHash = this.getPreviousHash();
const newBlock = new Block(index, timestamp, data, previousHash);
if(this.isValid(newBlock)){
this.chain.push(newBlock);
}
else{
console.log('Invalid block');
}
}
isValid(newBlock){
const currentBlock = this.chain[this.chain.length - 1];
if(currentBlock.index + 1 !== newBlock.index){
return false;
}
else if(newBlock.previousHash !== currentBlock.hash){
return false;
}
else if(newBlock.hash !== newBlock.calculateHash()){
return false;
}
return true;
}
printChain(){
console.log(this.chain);
}
}
module.export = Blockchain;