-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
60 lines (48 loc) · 1.47 KB
/
main.js
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
const SHA256 = require('crypto-js/sha256')
class Block{
constructor(timestamp,data){
this.index = 0;
this.timestamp = timestamp;
this.data = data;
this.previousHash = "0";
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash(){
return SHA256(this.index + this.previousHash + this.timestamp + this.data + this.nonce).toString();
}
}
class BlockChain{
constructor(){
this.chain = [this.createGenesis()];
}
createGenesis(){
return new Block("09/08/2018","GenesisBlock");
}
latestBlock(){
return this.chain[this.chain.length - 1];
}
addBlock(newBlock){
newBlock.previousHash = this.latestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
checkValidity(){
for(let i=0; i < this.chain.length; i++){
const currBlock = this.chain[i];
const prevBlock = this.chain[i-1];
if(currBlock.hash !== currBlock.calculateHash()){
return false;
}
if(prevBlock.hash !== currBlock.previousHash){
return false;
}
}
return true;
}
}
let jsChain = new BlockChain();
jsChain.addBlock(new Block("09/08/2018",{amount : 100}));
jsChain.addBlock(new Block("09/08/2018",{amount : 200}));
console.log(JSON.stringify(jsChain,null,4));
console.log("Validity " + jsChain.checkValidity());