-
Notifications
You must be signed in to change notification settings - Fork 0
/
proof.js
75 lines (62 loc) · 1.79 KB
/
proof.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const SHA256 = require('crypto-js/sha256');
class Coin{
constructor(index,time,data,preHash = ''){
this.index = index;
this.time = time;
this.data = data;
this.preHash = preHash;
this.Hash = this.calculateHash();
this.nonce = 0;
}
calculateHash(){
return SHA256(this.index + this.prevHash+ this.time +JSON.stringify(this.data)+this.nonce).toString();
}
mineBlock(difficulty){
while(this.Hash.substring(0,difficulty) !== Array(difficulty+1).join("0") ){
this.nonce++;
this.Hash = this.calculateHash();
}
console.log('Block Mined:' + this.Hash);
}
}
class Blockchain{
constructor(){
this.chain = [this.createGenesisBlock()];
this.difficulty = 2;
}
createGenesisBlock(){
return new Coin(0,"04/02/2018","Genesis block",0);
}
getCoin(){
return this.chain[this.chain.length-1];
}
addCoin(newCoin){
newCoin.preHash = this.getCoin().Hash;
//newCoin.Hash = newCoin.calculateHash();
newCoin.mineBlock(this.difficulty);
this.chain.push(newCoin);
}
checkValidchain(){
for(var i=1; i<this.chain.length; i++){
var currentCoin = this.chain[i];
var preCoin = this.chain[i-1];
if(currentCoin.Hash !== currentCoin.calculateHash()){
return false;
}
if(preCoin.Hash !== preCoin.calculateHash()){
return false;
}
}
return true;
}
}
let mayCoin = new Blockchain();
console.log("mining Block-1: ");
mayCoin.addCoin(new Coin(1,"03/02/2018",{amount:4}));
console.log("mining Block-2: ");
mayCoin.addCoin(new Coin(2,"04/02/2018",{amount:11}));
// console.log('is this Blockchain is valid '+ mayCoin.checkValidchain());
//
// mayCoin.chain[1].data = {amount:100};
// console.log('is this Blockchain is valid '+ mayCoin.checkValidchain());
// console.log(JSON.stringify(mayCoin,null,4));