-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.js
701 lines (530 loc) · 15.6 KB
/
blockchain.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
const { Block } = require("./block");
const { Proof } = require("./proof");
const { createDB, LH_KEY, returnPath, closeDBRes } = require("./db");
const {
coinbaseTx,
isCoinBaseTx,
sign,
verify,
usesKey,
isLockedWithKey,
} = require("./transaction");
const { sha256 } = require("bitcoinjs-lib/src/crypto");
class Blockchain {
constructor(address, node) {
this.Node = node;
this.Miner = address;
}
async continueBlockchain(needToWrite) {
await this.openDB(needToWrite);
try {
let res = await this.DB.get(LH_KEY);
this.LastHash = res;
} catch (e) {
console.log("eeeeeeeeeeeeeeeeeee", e);
if (e.code == "LEVEL_NOT_FOUND") {
this.LastHash = "";
}
}
}
async addBlock(blocks) {
try {
for (let i = 0; i < blocks.length; i++) {
const txn = await this.DB.batch();
const block = blocks[i];
const blockExists = await this.DB.get(block.Header.Hash).catch(
() => ""
);
if (blockExists) {
return;
}
const blockData = block;
let lastHash = await this.DB.get("lh").catch(() => "");
const lastBlockData = await this.DB.get(lastHash).catch(() => "");
const lastBlock = lastBlockData ? this.deserialize(lastBlockData) : "";
console.log("lastBlock", lastBlock);
console.log("blockData", blockData);
if (
(!lastBlock && blockData.Header.Height == 1) ||
(lastBlock &&
blockData.Header.Height == lastBlock.Header.Height + 1 &&
blockData.Header.PrevHash == lastBlock.Hash)
) {
await txn.put("lh", blockData.Hash);
await txn.put(`block_${blockData.Header.Height}`, blockData.Hash);
await txn.put(blockData.Hash, this.serialize(blockData));
this.LastHash = blockData.Hash;
} else {
return "fork";
}
await txn.write();
}
} catch (e) {
console.log("e", e);
}
}
async getBestHeight() {
try {
const lastHash = await this.DB.get("lh");
const lastBlockData = await this.DB.get(lastHash);
const lastBlock = this.deserialize(lastBlockData);
return lastBlock.Header.Height;
} catch (error) {
if (error.code == "LEVEL_NOT_FOUND") {
return 0;
}
console.error("Error while getting best height:", error);
throw new Error("Error fetching best height");
}
}
async getBlockHashes() {
const blocks = [];
let currentHash = await this.DB.get("lh").catch(() => null);
while (currentHash) {
blocks.push(currentHash);
const blockData = await this.DB.get(currentHash).catch(() => null);
if (blockData) {
const block = this.deserialize(blockData);
currentHash = block.Header.PrevHash;
} else {
break;
}
}
return blocks;
}
async getBlockHeaders(fromHeaderHash, stopHeaderHash, number = 100) {
let count = 0;
let height = 1;
let nowHash = fromHeaderHash;
let headers = [];
if (fromHeaderHash) {
try {
let block = this.deserialize(await this.DB.get(fromHeaderHash));
height = block.Header.Height + 1;
} catch (e) {}
}
try {
let lastHash = await this.DB.get("lh");
const lastBlockData = this.deserialize(await this.DB.get(lastHash));
number =
lastBlockData.Header.Height - height < 100
? lastBlockData.Header.Height - height
: 100;
} catch (e) {
console.log("e", e);
}
console.log("fromHeaderHash", fromHeaderHash);
console.log("number", number);
while (true) {
if ((stopHeaderHash && nowHash == stopHeaderHash) || count == number) {
break;
}
try {
let hash = await this.DB.get(`block_${height}`);
let block = this.deserialize(await this.DB.get(hash));
count += 1;
height += 1;
nowHash = block.Header.Hash;
headers.push({ Hash: block.Hash, Header: block.Header });
} catch {}
}
return headers;
}
async getBlockWithHeight(height) {
return await this.DB.get(`block_${height}`).catch(() => "");
}
async findCommonPointWithSyncNode(headers) {
let height = 1;
for (let i = 0; i < headers.length; i++) {
let hash = await this.DB.get(`block_${height}`).catch(() => "");
if (hash != headers[i].Hash) {
return height;
}
height += 1;
}
return height;
}
async getHeadersHashFromHeaders(headers) {
let headerHashs = [];
for (let i = 0; i < headers.length; i++) {
headerHashs.push(headers[i].Hash);
}
return headerHashs;
}
async backwardChain(height) {
console.log(
"---------------------------backward chain run----------------------------------"
);
try {
while (true) {
let lastHash = await this.DB.get("lh");
if (lastHash == "") {
break;
}
const lastBlockData = await this.DB.get(lastHash);
const lastBlock = this.deserialize(lastBlockData);
let lastHeight = lastBlock.Header.Height;
if (lastHeight < height) {
break;
}
await this.DB.put("lh", lastBlock.Header.PrevHash);
await this.DB.put(lastHash, "");
await this.DB.put(`block_${lastHeight}`, "");
}
} catch (error) {
console.error("error occure in backwardChain function", error);
}
}
async checkSyncNodeHeaders(headers) {
let hash = "";
console.log("headers", headers);
for (let i = 0; i < headers.length; i++) {
let block = new Block(
headers[i].Header.Timestamp,
headers[i].Hash,
[],
headers[i].Header.PrevHash,
headers[i].Header.Nonce,
headers[i].Header.Height,
headers[i].Header.MerkleRoot
);
let proof = new Proof(block);
if (
(hash && headers[i].Header.PrevHash != hash) ||
!proof.validateProof() ||
!proof.validate()
) {
throw new Error("Error checking sync node headers");
}
hash = block.Hash;
}
}
async getBlock(headerHashes) {
let blocks = [];
for (let i = 0; i < headerHashes.length; i++) {
try {
const blockData = await this.DB.get(headerHashes[i]);
const block = this.deserialize(blockData);
blocks.push(block);
} catch (error) {
if (error.code == "LEVEL_NOT_FOUND") {
return null;
}
console.log("Error fetching block", headerHashes);
throw new Error("Error fetching block");
}
}
return blocks;
}
async checkAfterMint(result) {
let newBlock = result.block;
let lastHeight = result.lastHeight;
let newlastHeight = 0;
let newlastHash;
try {
newlastHash = await this.DB.get("lh");
const newlastBlockData = await this.DB.get(newlastHash);
const newlastBlock = this.deserialize(newlastBlockData);
newlastHeight = newlastBlock.Header.Height;
} catch (error) {
console.error("error", error);
}
if (newlastHeight == lastHeight) {
this.LastHash = newBlock.Hash;
await this.DB.put(LH_KEY, newBlock.Hash);
await this.DB.put(newBlock.Hash, this.serialize(newBlock));
await this.DB.put(`block_${newBlock.Header.Height}`, newBlock.Hash);
return newBlock;
} else {
if (Math.abs(newlastHeight - lastHeight) > 1) {
return "fork";
}
}
}
async mineBlock(txs, miningProcess) {
let lastHash;
let lastHeight = 0;
for (let i = 0; i < txs.length; i++) {
if ((await this.verifyTransaction(txs[i])) != true) {
console.error("Error in verify transaction");
throw "Error in verify transaction";
}
}
try {
lastHash = await this.DB.get("lh");
const lastBlockData = await this.DB.get(lastHash);
const lastBlock = this.deserialize(lastBlockData);
lastHeight = lastBlock.Header.Height;
} catch (error) {
console.error("error", error);
}
miningProcess.send({
txs,
prevHash: this.LastHash,
height: lastHeight,
});
}
serialize(block) {
return JSON.stringify(block);
}
deserialize(data) {
return JSON.parse(data);
}
async findUTXO(pubKeyHash) {
let UTXOs = [];
let unspentTxs = await this.findUnspentTransactions(pubKeyHash);
for (let i = 0; i < unspentTxs.length; i++) {
unspentTxs[i].TxOutputs.map((item) => {
if (isLockedWithKey(item, pubKeyHash)) {
UTXOs.push(item);
}
});
}
return UTXOs;
}
async findUTXODB(returnSpend = false, height) {
let currentHash = await this.DB.get("lh").catch(() => "");
let UTXOs = {};
let spentTXOs = {};
if (currentHash) {
while (true) {
console.log("currentHash", currentHash);
let block = this.deserialize(await this.DB.get(currentHash));
console.log("blockblockblockblock", block);
block.Transactions.map((tx) => {
for (let i = 0; i < tx.TxOutputs.length; i++) {
let fail = false;
if (spentTXOs[tx.ID]) {
for (let j = 0; j < spentTXOs[tx.ID].length; j++) {
if (spentTXOs[tx.ID][j] == i) {
const index = spentTXOs[tx.ID].indexOf(spentTXOs[tx.ID][j]);
if (index > -1) {
spentTXOs[tx.ID].splice(index, 1);
}
if (spentTXOs[tx.ID] && spentTXOs[tx.ID].length == 0) {
delete spentTXOs[tx.ID];
}
fail = true;
break;
}
}
}
if (fail) {
continue;
}
if (!UTXOs[tx.ID]) {
UTXOs[tx.ID] = [];
}
UTXOs[tx.ID].push(tx.TxOutputs[i]);
}
if (!isCoinBaseTx(tx)) {
for (let j = 0; j < tx.TxInputs.length; j++) {
let intxId = tx.TxInputs[j].ID;
if (!spentTXOs[intxId]) {
spentTXOs[intxId] = [];
}
if (!spentTXOs[intxId].includes(tx.TxInputs[j].Out)) {
spentTXOs[intxId].push(tx.TxInputs[j].Out);
}
}
}
});
currentHash = block.Header.PrevHash;
if (
block.Header.PrevHash == "" ||
(height && block.Header.Height == height)
) {
break;
}
}
}
return returnSpend ? { UTXOs, spentTXOs } : UTXOs;
}
async findSpendableOutputs(pubKeyHash, amount) {
let unspentOuts = {};
let unspentTxs = await this.findUnspentTransactions(pubKeyHash);
let accumulated = 0;
unspentTxs.map((tx) => {
for (let i = 0; i < tx.TxOutputs.length; i++) {
if (
isLockedWithKey(tx.TxOutputs[i], pubKeyHash) &&
accumulated < Number(amount)
) {
accumulated += Number(tx.TxOutputs[i].Value);
if (unspentOuts[tx.ID]) {
unspentOuts[tx.ID].push(i);
} else {
unspentOuts[tx.ID] = [i];
}
if (accumulated > Number(amount)) {
break;
}
}
}
});
return {
accumulated,
unspentOuts,
};
}
async findUnspentTransactions(pubKeyHash) {
let currentHash = this.LastHash;
let unspentTxs = [];
let spentTXOs = {};
while (true) {
let block = this.deserialize(await this.DB.get(currentHash));
block.Transactions.map((tx) => {
for (let i = 0; i < tx.TxOutputs.length; i++) {
if (spentTXOs[tx.ID]) {
let spendOuts = spentTXOs[tx.ID] ? spentTXOs[tx.ID] : [];
for (let j = 0; j < spendOuts.length; j++) {
if (spendOuts[j] == i) {
continue;
}
}
}
if (isLockedWithKey(tx.TxOutputs[i], pubKeyHash)) {
unspentTxs.push(tx);
}
}
if (!isCoinBaseTx(tx)) {
for (let j = 0; j < tx.TxInputs.length; j++) {
let intxId = tx.TxInputs[j].ID;
if (usesKey(tx.TxInputs[j], pubKeyHash)) {
spentTXOs[intxId].push(intxId);
} else {
spentTXOs[intxId] = [intxId];
}
}
}
});
currentHash = block.Header.PrevHash;
if (block.Header.PrevHash == "") {
break;
}
}
return unspentTxs;
}
async signTransaction(tx, privKey) {
let prevTXs = {};
let spentTXOs = {};
for (let i = 0; i < tx.TxInputs.length; i++) {
let prevTX = await this.findTransaction(tx.TxInputs[i].ID);
prevTXs[prevTX.ID] = prevTX;
}
sign(tx, privKey, prevTXs);
}
async checkDoubleSpendingTxs(txs) {
let removeTx = [];
let spentTXOs = {};
for (let i = 0; i < txs.length; i++) {
let tx = txs[i];
let remove = false;
for (let j = 0; j < tx.TxInputs.length; j++) {
let intxId = tx.TxInputs[j].ID;
if (
spentTXOs[intxId] &&
spentTXOs[intxId].includes(tx.TxInputs[j].Out)
) {
removeTx.push(tx.ID);
remove = true;
break;
}
}
if (remove) {
continue;
}
for (let j = 0; j < tx.TxInputs.length; j++) {
let intxId = tx.TxInputs[j].ID;
if (!spentTXOs[intxId]) {
spentTXOs[intxId] = [];
}
spentTXOs[intxId].push(tx.TxInputs[j].Out);
}
}
return removeTx;
}
async verifyTransaction(tx) {
if (isCoinBaseTx(tx)) {
return true;
}
let prevTXs = {};
for (let i = 0; i < tx.TxInputs.length; i++) {
let prevTX = await this.findTransaction(tx.TxInputs[i].ID);
prevTXs[prevTX.ID] = prevTX;
}
return verify(tx, prevTXs);
}
async findTransaction(id) {
let currentHash = this.LastHash;
let tx;
while (true) {
let block = this.deserialize(await this.DB.get(currentHash));
console.log(".............................................");
block.Transactions.map((item) => {
if (item.ID == id) {
tx = item;
}
});
if (tx) {
break;
}
currentHash = block.Header.PrevHash;
if (block.Header.PrevHash == "") {
break;
}
}
return tx;
}
async iterate() {
let currentHash = this.LastHash;
console.log("currentHash", currentHash);
if (currentHash) {
while (true) {
let block = this.deserialize(await this.DB.get(currentHash));
console.log(".............................................");
currentHash = block.Header.PrevHash;
console.log(
`block ${block.Header.Height}`,
JSON.stringify(block, null, 2)
);
if (block.Header.PrevHash == "") {
break;
}
}
} else {
console.log("There is no block in chain");
}
}
async getBlockHashes(chain) {
let blocks = [];
let currentHash = this.LastHash;
while (true) {
let block = this.deserialize(await this.DB.get(currentHash));
blocks.push(block.Hash);
currentHash = block.Header.PrevHash;
if (block.Header.PrevHash == "") {
break;
}
}
return blocks;
}
async openDB(needToWrite) {
this.DB = await createDB(this.Node, needToWrite);
}
async closeDB() {
await new Promise((resolve, reject) => {
this.DB.close((err) => {
if (err) {
console.error("Error closing the database:", err);
reject(err);
} else {
console.log("Database closed successfully");
closeDBRes();
resolve();
}
});
});
}
}
module.exports = { Blockchain };