-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockChain.js
More file actions
239 lines (219 loc) · 8.87 KB
/
BlockChain.js
File metadata and controls
239 lines (219 loc) · 8.87 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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
/* ===== Blockchain Class ==========================
| Class with a constructor for new blockchain |
| ================================================*/
const SHA256 = require('crypto-js/sha256');
const LevelSandbox = require('./LevelSandbox.js');
const Block = require('./Block.js');
const CryptoJS = require('crypto-js');
const async = require('async');
class Blockchain {
constructor() {
this.bd = new LevelSandbox.LevelSandbox();
this.generateGenesisBlock();
this.difficulty = 4;
}
// Helper method to create a Genesis Block (always with height= 0)
// You have to options, because the method will always execute when you create your blockchain
// you will need to set this up statically or instead you can verify if the height !== 0 then you
// will not create the genesis block
generateGenesisBlock() {
// Add your code here
let self = this;
return new Promise(function (resolve, reject) {
self.getBlockHeight()
.then(height => {
if (height === 0) {
self.addBlock(new Block.Block("This is the genesis block"));
resolve(true);
} else
console.log("The genesis block is already existed")
})
.catch(err => {
console.log(err);
reject(err);
})
})
}
// Get block height, it is a helper method that return the height of the blockchain
getBlockHeight() {
// Add your code here
let self = this;
return new Promise(function (resolve, reject) {
self.bd.getBlocksCount()
.then(value => {
console.log("blockCount =" + value);
resolve(value);
})
.catch(err => {
console.log("Not found");
reject(err);
})
})
}
// Add new block
addBlock(block) {
// Add your code here
let self = this;
return new Promise(function (resolve, reject) {
self.getBlockHeight()
.then(height => {
block.height = height;
block.time = new Date().getTime().toString().slice(0, -3);
if (height > 0) {
self.getBlock(height - 1)
.then(preBlock => {
block.previousBlockHash = preBlock.hash;
let nonce = 0;
let nextHash = '';
while (!self.isValidHashDifficulty(nextHash)) {
nonce = nonce + 1;
nextHash = self.calculateHash(block.height, block.previousBlockHash, block.time, block.body, nonce);
}
block.hash = nextHash;
block.nonce = nonce;
console.log("block.hash is : ", block.hash);
self.bd.addLevelDBData(height, JSON.stringify(block));
resolve(true);
})
.catch(error => {
console.log(error);
reject(error);
});
} else {
console.log("block SHA256 is :", SHA256(JSON.stringify(block)).toString());
// block.nonce = 0;
block.hash = self.calculateHashForBlock(block);
console.log("block.hash is :", block.hash);
self.bd.addLevelDBData(height, JSON.stringify(block));
resolve(true);
}
})
.catch(error => {
console.log(error)
reject(error);
});
});
}
// Get Block By Height
getBlock(height) {
// Add your code here
let self = this;
return new Promise(function (resolve, reject) {
self.bd.getLevelDBData(height)
.then(block => {
resolve(JSON.parse(block));
})
.catch(err => {
console.log("Not found");
reject(err);
})
})
}
// 根据区块的索引确认区块是否有效,法一:
validateBlock(height) {
// Add your code here
return this.getBlock(height)
.then(block => {
let blockHash = block.hash;
block.hash = "";
let validBlockHash = this.calculateHashForBlock(block);
block.hash = blockHash;
if (validBlockHash === blockHash) {
return Promise.resolve({isValidBlock: true, block: block});
} else {
console.log('Block #' + height + ' invalid hash:\n' + blockHash + '<>' + validBlockHash);
return Promise.resolve({isValidBlock: false, block: block});
}
})
}
// 根据区块的索引确认区块是否有效,法二:
validateBlock_2(height) {
return this.getBlock(height).then(
block => {
let preheight = block.height - 1;
this.getBlock(preheight).then(
previousBlock => {
if (this.isValidNewBlock(block, previousBlock)) {
console.log("YES");
return Promise.resolve({isValidBlock: true, block: block})
} else {
console.log("NO");
return Promise.reject({isValidBlock: false, block: block})
}
}
)
}
)
}
//返回区块的哈希
calculateHashForBlock(block) {
return this.calculateHash(block.height, block.previousBlockHash, block.time, block.body, block.nonce)
}
// 拼接一串字符,返回其哈希
calculateHash(index, previousHash, timestamp, data, nonce) {
return CryptoJS.SHA256(index + previousHash + timestamp + data + nonce).toString()
}
//根据区块的前后对比确认新的区块是否有效
isValidNewBlock(newBlock, previousBlock) {
const blockHash = this.calculateHashForBlock(newBlock);
if (previousBlock.height + 1 !== newBlock.height) {
console.log('❌ new block has invalid index ', newBlock.height)
return false
} else if (previousBlock.hash !== newBlock.previousBlockHash) {
console.log('❌ new block has invalid previous hash ', newBlock.height)
return false
} else if (blockHash !== newBlock.hash) {
console.log(`❌ invalid hash `, newBlock.height)
return false
} else if (!this.isValidHashDifficulty(this.calculateHashForBlock(newBlock))) {
console.log(`❌ invalid hash does not meet difficulty requirements: ${this.calculateHashForBlock(newBlock)}`);
return false;
}
return true
}
// 确认这条链是否有效
validateChain() {
// Add your code here
let errorlog = [];
let self = this;
return new Promise(function (resolve, reject) {
self.getBlockHeight()
.then(height => {
for (let i = 1; i < height; i++) {
self.getBlock(i)
.then(now_block => {
self.getBlock(now_block.height - 1).then(previousBlock => {
if(!self.isValidNewBlock(now_block, previousBlock)) errorlog.push(i)
})
});
}
setTimeout(function () {
resolve(errorlog)
}, 1 * 1000);
})
})
}
//判断是否是有效的哈希困难值
isValidHashDifficulty(hash) {
for (var i = 0, b = hash.length; i < b; i++) {
if (hash[i] !== '0') {
break;
}
}
return i === this.difficulty;
}
// Utility Method to Tamper a Block for Test Validation
// This method is for testing purpose
_modifyBlock(height, block) {
let self = this;
return new Promise((resolve, reject) => {
self.bd.addLevelDBData(height, JSON.stringify(block).toString()).then((blockModified) => {
resolve(blockModified);
}).catch((err) => {
console.log(err);
reject(err)
});
});
}
}
module.exports.Blockchain = Blockchain;