-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleChain.js
304 lines (251 loc) · 10.3 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
293
294
295
296
297
298
299
300
301
302
303
304
/* ===== SHA256 with Crypto-js ===============================
| Learn more: Crypto-js: https://github.com/brix/crypto-js |
| =========================================================*/
const SHA256 = require('crypto-js/sha256');
const level = require('level');
const chainDB = './chaindata';
const bm = require('./blockModel');
const ListStream = require('list-stream');
const boom = require('boom');
const db = level(chainDB);
const DB_HEIGHT = "CHAIN_HEIGHT";
const INIT_CHAIN_HEIGHT = parseInt(0);
class CheckRetValue {
constructor(height, check) {
this.height = height;
this.check = check;
}
}
function getBlock(key) {
return new Promise(function (resolve, reject) {
db.get(key, function (err, value) {
if (err) {
const notFoundErr = 'Block ' + key + ' not found!';
console.log(notFoundErr, err);
reject(boom.notFound(notFoundErr));
} else {
// console.log("getLevelDB DataValue: " + value);
resolve(value);
}
});
});
}
function saveToDB(block) {
const jsonBlock = JSON.stringify(block).toString();
console.log(jsonBlock);
const ops = [
// save Block with BlockHeight
{type: 'put', key: block.height, value: jsonBlock},
// reference (Index) HASH to BlockHeight, every hash in the chain must be unqiue.
// The unique blockHeight ist part oft the Hash!
{type: 'put', key: block.hash, value: block.height},
// save last BLOCKHEIGHT
{type: 'put', key: DB_HEIGHT, value: block.height}
];
// add (Index) for wallet Address
db.batch(ops, function (err) {
if (err) {
const message = "Error adding Block " + block.height + " to chain DB";
console.log(message, err);
throw boom.conflict(message);
} else {
console.log("Block " + block.height + " sucessfull added to chainDB!");
}
})
}
function getBlockObj(key) {
return new Promise(function (resolve, reject) {
getBlock(key).then((jsonBlock) => {
const blockObj = bm.decodeStoryAddToBlock(jsonBlock);
resolve(blockObj);
}).catch((err) => {
reject(err);
});
});
}
/* ===== Blockchain Class ==========================
| Class with a constructor for new blockchain |
| ================================================*/
class Blockchain {
constructor() {
this.getBlockHeight().then(height => {
if (height == INIT_CHAIN_HEIGHT) {
console.log("INIT GENESIS BLOCK");
let genesis = bm.genesisFactory();
saveToDB(genesis);
}
});
}
// Add new block()
addBlock(newBlock) {
return new Promise((resolve, reject) => {
this.getBlockHeight().then(height => {
newBlock.height = height;
const previousHeight = newBlock.height - 1;
if (newBlock.height > 0) {
getBlockObj(previousHeight).then(previousBlock => {
newBlock = bm.setBlockTimestamp(newBlock);
newBlock = bm.setBlockHashes(newBlock, previousBlock.hash);
newBlock = bm.setEndoeStory(newBlock);
saveToDB(newBlock);
resolve(newBlock);
}).catch((error) => {
console.log(error);
reject(error);
});
} else {
reject(boom.notFound("No Genesis Block set !"));
}
});
});
}
// New Version suggestion of Coach
getBlockHeight() {
return new Promise(function (resolve) {
db.get(DB_HEIGHT, function (err, value) {
if (err) {
db.put(DB_HEIGHT, INIT_CHAIN_HEIGHT, function (err) {
if (err) return console.log('DB_HEIGHT ' + key + ' failed. NOT increased', err);
});
resolve(INIT_CHAIN_HEIGHT);
} else {
const retValue = parseInt(value) + 1;
resolve(retValue);
}
});
});
}
getBlockByHash(hashValue) {
return new Promise(function (resolve, reject) {
getBlock(hashValue).then((blockHeight) => {
getBlockObj(blockHeight).then((block) => {
resolve(block);
}).catch((err) => {
const message = "Block for Hash " + hashValue + " block height "
+ blockHeight + " not found!";
reject(boom.notFound(message));
});
}).catch((err) => {
const message = "Block height for Hash " + hashValue + " not found!";
reject(boom.notFound(message));
});
});
}
getBlocksByAddress(address) {
console.log("search for address " + address);
return new Promise(function (resolve, reject) {
let addressBlocks = [];
db.createValueStream().pipe(
ListStream.obj(function (err, data) {
if (err) {
reject(boom.boomify(err));
} else {
data.forEach(function (value, i) {;
let block = bm.decodeStoryAddToBlock(value);
if (bm.compareBodyAddress(address, block.body)) {
console.log("push block " + block.height + " into result.");
addressBlocks.push(block);
}
});
if (addressBlocks.length > 0) {
resolve(addressBlocks);
} else {
const emptyERR = "No entries found for address " + address;
reject(boom.notFound(emptyERR));
}
}
})
);
});
}
// validate block
validateBlock(blockHeight) {
return new Promise((resolve, reject) => {
this.getBlock(blockHeight).then((block) => {
let blockObj = JSON.parse(block);
const blockHash = blockObj.hash;
blockObj.hash = '';
const validBlockHash = SHA256(JSON.stringify(blockObj)).toString();
if (blockHash === validBlockHash) {
console.log('Block # ' + blockHeight + ' valid hash:\n' + blockHash);
resolve(new CheckRetValue(blockHeight, true));
} else {
console.log('Block #' + blockHeight + ' invalid hash:\n' + blockHash + '<>' + validBlockHash);
resolve(new CheckRetValue(blockHeight, false));
}
}).catch((err) => {
console.log('Error in getBlock at ValidateBlock() with Block ' + err);
reject(new CheckRetValue(blockHeight, false));
});
});
}
validatePreviousBlockHash(blockHeight, chainHeight) {
return new Promise((resolve, reject) => {
this.getBlock(blockHeight).then((block) => {
let blockObj = JSON.parse(block);
const blockHash = blockObj.hash;
const nextHeight = blockHeight + 1;
if (nextHeight < chainHeight) {
this.getBlock(nextHeight).then(nextBlock => {
let nextBlockObj = JSON.parse(nextBlock);
const previousBlockHash = nextBlockObj.previousBlockHash;
if (blockHash === previousBlockHash) {
console.log('Block # ' + blockHeight + ' valid previous hash:\n' + blockHash)
resolve(new CheckRetValue(blockHeight, true));
} else {
console.log('Block #' + blockHeight + ' invalid previous hash:\n' + blockHash + '<>'
+ previousBlockHash);
resolve(new CheckRetValue(blockHeight, false));
}
}).catch((err) => {
console.log('Error in getBlock at validatePreviousBlockHash() with next Block ' + err);
reject(new CheckRetValue(blockHeight, false));
});
} else {
console.log('Last Block, no check for previousBlockHash possible!');
resolve(new CheckRetValue(blockHeight, true));
}
}).catch((err) => {
console.log('Error in getBlock at validatePreviousBlockHash() with Block ' + err);
reject(new CheckRetValue(blockHeight, false));
});
});
}
// Validate blockchain
validateChain() {
this.getBlockHeight().then(height => {
let chainPromises = [];
let errorLog = [];
for (let i = 0; i < height; i++) {
chainPromises.push(this.validateBlock(i));
chainPromises.push(this.validatePreviousBlockHash(i, height));
}
Promise.all(chainPromises).then((results) => {
for (let i in results) {
const result = results[i];
if (!Boolean(result.check)) {
const errorHeight = parseInt(result.height);
console.log("push error " + errorHeight);
errorLog.push(errorHeight);
}
}
// remove duplicate errors Block
// e.g. validate Block false and validatePreviousBlockHash is false
const uniqueErrorLogs = [...new Set(errorLog)];
if (uniqueErrorLogs.length > 0) {
console.log('Block errors = ' + uniqueErrorLogs.length);
console.log('Blocks: ' + uniqueErrorLogs);
} else {
console.log('No errors detected');
}
});
});
}
}
function blockchainFactory() {
return new Blockchain();
}
module.exports = {
blockchainFactory: blockchainFactory,
getBlockObj: getBlockObj
}