-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleChain.js
292 lines (255 loc) · 8.04 KB
/
simpleChain.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
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/* ===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
| =========================================================*/
const SHA256 = require('crypto-js/sha256');
//Importing levelSandbox class
const LevelSandboxClass = require('./levelSandbox.js');
// Creating the levelSandbox class object
const db = new LevelSandboxClass.LevelSandbox();
/* ===== Block Class ==============================
| Class with a constructor for block |
| ===============================================*/
class Block{
constructor(data){
this.hash = "",
this.height = 0,
this.body = data,
this.time = 0,
this.previousBlockHash = ""
}
}
/* ===== Blockchain Class ==========================
| Class with a constructor for new blockchain |
| ================================================*/
class Blockchain{
constructor(){
}
// Add new block
addBlock(newBlock){
let self = this;
// UTC timestamp
newBlock.time = new Date().getTime().toString().slice(0,-3);
return new Promise( function(resolve){
// get the chain length by counting all the blocks
db.getBlocksCount().then ( function(chainLength)
{
console.log("chainLength :" + chainLength);
return chainLength;
})
.then( function(chainLength){
console.log("in second then " +chainLength);
if (chainLength == 0 ){
// create Genesis block if it is the first block of the chain
let gBlock = new Block("First block in the chain - Genesis block");
gBlock.hash = SHA256(JSON.stringify(gBlock)).toString();
//add to levelDB
db.addLevelDBData(0, JSON.stringify(gBlock).toString())
.then((result) => {
if(!result) {
console.log("Error Adding gdata");
}else {
console.log(result);
// // newblock ht increased by 1
newBlock.height = 1;
return result;
}
})
.then(function(result){
let ggBlock = JSON.parse(result);
newBlock.previousBlockHash = ggBlock.hash;
// Block hash with SHA256 using newBlock and converting to a string
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
console.log("Block :" + JSON.stringify(newBlock));
newBlock.height =chainLength+1;
db.addLevelDBData(newBlock.height, JSON.stringify(newBlock).toString())
.then((result) => {
if(!result) {
console.log("Error Adding data");
}else {
console.log("after add: " + result);
resolve(true);
}
})
.catch((err) => { console.log(err); resolve(false)});
});
}
else{
// get previous block
self.getBlock(chainLength-1)
.then((result) => {
if(!result) {
console.log("Error getting pblock");
}else {
console.log(result);
newBlock.previousBlockHash = JSON.parse(result).hash;
// Block hash with SHA256 using newBlock and converting to a string
//newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
return result;
}
})
//.catch((err) => { console.log(err); }
.then(function(result){
let pBlock = JSON.parse(result);
newBlock.previousBlockHash = pBlock.hash;
//block height
newBlock.height =chainLength;
// Block hash with SHA256 using newBlock and converting to a string
newBlock.hash = SHA256(JSON.stringify(newBlock)).toString();
console.log("Block :" + JSON.stringify(newBlock));
db.addLevelDBData(newBlock.height, JSON.stringify(newBlock).toString())
.then((result) => {
if(!result) {
console.log("Error Adding data");
}else {
console.log("after add chainlength gt 0: " + result);
resolve(true);
}
})
.catch((err) => { console.log(err); resolve(false)});
});
}
});
});
}
// Get block height
getBlockHeight(){
let blockHeight = 0;
return new Promise((resolve) => {
db.getBlocksCount().then(function(value){
// blockHeight is the # of blocks before the block;
blockHeight = value-1;
console.log("blockHeight :" + blockHeight);
resolve(blockHeight);
});
})
}
// get block
getBlock(blockHeight){
return new Promise((resolve) => {
db.getLevelDBData(blockHeight).then(function(value){
console.log("blockHeight sent to getBlock :" + blockHeight);
console.log("block val: " + value);
resolve(value);
});
})
}
// validate block
validateBlock(blockHeight){
let self = this;
return new Promise(function(resolve){
self.getBlock(blockHeight)
.then((result) => {
if(!result) {
console.log("Error getting block in validateBlock");
resolve(false);
}else {
console.log(result);
let block = JSON.parse(result);
// get block hash
console.log(JSON.stringify(block)); // "Stuff worked!"
let blockHash = block.hash;
// remove block hash to test block integrity
block.hash = '';
// generate block hash
let validBlockHash = SHA256(JSON.stringify(block)).toString();
console.log("validBHash :" + validBlockHash);
// Compare
if(validBlockHash === blockHash) {
resolve(true);
} else {
resolve(false);
}
}
})
})
}
validateBlockGivenBlock(givenBlock){
let block = JSON.parse(givenBlock);
console.log("In validateBlockGivenBlock : " + givenBlock);
let blockHash = block.hash;
// remove block hash to test block integrity
block.hash = '';
// generate block hash
let validBlockHash = SHA256(JSON.stringify(block)).toString();
console.log("validBHash :" + validBlockHash);
// Compare
if(validBlockHash === blockHash)
{
return true;
} else {
return false;
}
}
// Validate blockchain
validateChain(){
let self = this;
let errorLog = [];
let chainLength = 0;
let block1 = null;
return new Promise(function(resolve){
db.getBlocksCount().then ( function(chainLength)
{
console.log("chainLength :" + chainLength);
var promises = [];
//get all blocks to be used for Promize.all
for(var i = 0; i < chainLength; i++){
promises.push(self.getBlock(i));
}
//Using Promise.all to execute all promises at the same time
Promise.all(promises)
.then((blocks) => {
for(var i = 0; i < chainLength; i++){
// console.log("blocks");
// console.log(JSON.stringify(blocks[i]));
// console.log(JSON.stringify(blocks[i+1]));
//validate the block
if (!self.validateBlockGivenBlock(blocks[i]))
{errorLog.push(i);}
if(i < chainLength-1){
let blockHash = JSON.parse(blocks[i]).hash;
// get the previousblock hash of the next block
let previousHash = JSON.parse(blocks[i+1]).previousBlockHash;
//compare with the hash of this blcok
if (blockHash!==previousHash) {
errorLog.push(i);
}
}
else {
if (errorLog.length>0) {
//at the end send the errorlog if there are errors
// console.log('Block errors = ' + errorLog.length);
// console.log('Blocks: '+errorLog);
resolve(errorLog);
} else {
console.log('No errors detected');
resolve(true);
}
}
}
})
.catch((e) => {
console.log("Exception **: " + e);
resolve(e);
});
})
});
}
}
(async function theTestLoop (i) {
let blockchain = new Blockchain();
// for (var i = 1; i <= 4; i++) {
// await blockchain.addBlock(new Block("test data chk chk" + i))
// .then(function(res){
// console.log("added block" + res);
// });
// }
// await blockchain.getBlockHeight().then(function(result){
// console.log("bcheight :" + result);
// });
await blockchain.validateChain().then(function(value){
console.log("block chain validation + " + value);
});
//await blockchain.validateBlock(1).then(function(value){
// console.log("b 1 validation + " + value);
// });
})(0);