-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain1.js
772 lines (680 loc) · 22.1 KB
/
chain1.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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
const crypto = require("crypto");
const Block = require("./block.js").Block;
const BlockHeader = require("./block.js").BlockHeader;
const Transaction = require("./block.js").Transaction;
const MerkleTree = require("./merkleTree.js");
const AsyncLock = require("async-lock");
const EC = require("elliptic").ec,
ec = new EC("secp256k1");
const { Level } = require("level");
const fs = require("fs");
const path = require("path");
const levelup = require("levelup");
const leveldown = require("leveldown");
const chalk = require("chalk");
const miningState = require("./miningState");
const { TRANSACTION_FEE, MINING_REWARD, MAX_SUPPLY } = require("./config.json");
const tp = require("./transactionPool");
const difficulty = 5;
const blockchain = [];
const lock = new AsyncLock();
let db;
let createDb = async (peerId) => {
let dir = path.join(__dirname, "db", peerId);
try {
await fs.promises.access(dir, fs.constants.F_OK);
// If the code reaches here, it means that the directory exists.
let levelDb = leveldown(dir);
db = levelup(levelDb);
} catch (err) {
if (err.code === "ENOENT") {
// If the directory does not exist, create it.
await fs.promises.mkdir(dir, { recursive: true });
let levelDb = leveldown(dir);
db = levelup(levelDb);
let genesisBlock = await createGenesisBlock();
blockchain.push(genesisBlock);
storeBlock(genesisBlock);
console.log(`Genesis Block Created.`);
} else {
// Some other error occurred.
console.error("Error creating or opening database:", err);
}
}
};
function calculateHashForBlock(block) {
return crypto
.createHash("sha256")
.update(
block.blockHeader.version +
block.blockHeader.previousBlockHeader +
block.blockHeader.merkleRoot +
block.blockHeader.time +
block.nonce
)
.digest("hex");
}
async function createGenesisBlock() {
let timestamp = 1690365924213;
let previousBlockHeader = "0";
let version = "1.0.0";
let merkleRoot =
"bb77e380f6d0ae7a842dc47a11b4d6a46523b05295eb86d4a583e59b90c1cbb5";
let blockHeader = new BlockHeader(
version,
previousBlockHeader,
merkleRoot,
timestamp
);
// Create a transaction
let sender = "genesis";
let receiver =
"04227ea4320cfd7d50fd821b3cc66d7bcbd80a8806dc3e5ce90fba3c6594920c482d6360933fd149363d5d1177320e108d836165ae48ece6d9c54919565c2f0562";
let amount = 100000;
let transaction = new Transaction(sender, receiver, amount);
// Add the transaction to the block
let transactions = [transaction];
let index = 0;
let block = new Block(blockHeader, index, transactions);
block.blockHeader.hash = calculateHashForBlock(block);
await updateBalance(receiver, amount);
return block;
}
async function mineBlock(block) {
console.log(
"miningState when mineBlock is called First time",
miningState.isMining
);
const existingBlock = await getBlockFromLevelDB(block.index);
if (existingBlock) {
console.log(
chalk.yellow.bold(
`Block with index ${block.index} already exists, skipping`
)
);
return;
}
let hash = calculateHashForBlock(block);
console.log(`Mining for hash`, hash);
while (hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) {
// Check if miningState.isMining is false
if (!miningState.isMining) {
console.log(
"miningState.isMining inside while loop:",
miningState.isMining
);
console.log("Mining process stopped");
return null; // Or some other value to indicate that the mining process was stopped
}
block.nonce++;
hash = calculateHashForBlock(block);
// if (block.nonce % 10000 === 0) {
// console.log(`Checking hash: ${hash}`); // This line logs each 10,000th hash that is checked
// }
}
block.blockHeader.hash = hash;
return block;
}
async function rewardMiner(block) {
try {
// Check that the first transaction is from 'coinbase'
if (block.transactions[0].sender !== "coinbase") {
throw new Error("First transaction is not from 'coinbase'");
}
let minerAddress = block.transactions[0].receiver;
// Fetch and wait for the miner's balance
let minerBalance = await getBalance(minerAddress);
minerBalance = minerBalance || 0;
let totalTransactionFees = 0;
// Start i at 1 to skip the coinbase transaction
for (let i = 1; i < block.transactions.length; i++) {
totalTransactionFees += block.transactions[i].fee;
}
// Update and wait for the miner's balance to be updated
await updateBalance(
minerAddress,
minerBalance + totalTransactionFees + MINING_REWARD
);
} catch (error) {
console.error(`Failed to reward miner: ${error.message}`);
}
}
async function createNewBlock(transactions, minerAddress) {
let userTransactions = [...transactions]; // Copy the original transactions first
let tx = userTransactions.filter(
(transaction) =>
transaction.sender !== "coinbase" && transaction.sender !== "system"
);
let blockHeader = await createNewBlockHeader(transactions);
let index = (await getBlockHeight()) + 1;
console.log(`INDEX`, index);
// Use blockTransactions for the transactions of newBlock
// And use tx for the tx field of newBlock
let newBlock = new Block(blockHeader, index, transactions, tx);
return newBlock;
}
// TODO
async function createNewBlockHeader(transactions) {
let timestamp = new Date().getTime();
let version = "1.0.0";
let previousBlockHeader = await getPreviousBlockHeader();
let merkleTree = new MerkleTree(transactions);
let merkleRoot = merkleTree.getMerkleRoot();
let difficulty = await updateDifficulty();
return new BlockHeader(
version,
previousBlockHeader,
merkleRoot,
timestamp,
difficulty
);
}
async function getPreviousBlockHeader() {
// Get the total count of blocks in your blockchain
let totalBlocks = await getBlockHeight();
let previousBlockHeader = null;
if (totalBlocks > 0) {
// if blocks exist, get the last block's hash
previousBlockHeader = (await getBlockFromLevelDB(totalBlocks)).blockHeader
.hash;
} else if (totalBlocks === 0) {
// if no blocks exist yet (other than genesis), get the genesis block's hash
previousBlockHeader = (await getBlockFromLevelDB(0)).blockHeader.hash;
} else {
// handle error case if totalBlocks is less than 0
throw new Error("Invalid block count");
}
return previousBlockHeader;
}
async function updateDifficulty() {
const targetBlockTime = 20000;
const adjustmentFactor = 1;
const TARGET_BLOCK_INTERVAL = 100;
// Add a default difficulty value for the first block.
let defaultDifficulty = difficulty;
let blockHeight = await getBlockHeight();
// If there are no blocks in the blockchain, return the default difficulty.
if (blockHeight === 0) {
return defaultDifficulty;
}
if (
blockHeight < TARGET_BLOCK_INTERVAL ||
blockHeight % TARGET_BLOCK_INTERVAL !== 0
) {
let lastBlock = await getBlockFromLevelDB(blockHeight - 1);
return lastBlock.blockHeader.difficulty;
}
let oldBlock = await getBlockFromLevelDB(blockHeight - TARGET_BLOCK_INTERVAL);
let lastBlock = await getBlockFromLevelDB(blockHeight - 1);
let timeDifference = lastBlock.blockHeader.time - oldBlock.blockHeader.time;
let newDifficulty = lastBlock.blockHeader.difficulty;
if (timeDifference < targetBlockTime * TARGET_BLOCK_INTERVAL) {
newDifficulty += adjustmentFactor;
} else if (timeDifference > targetBlockTime * TARGET_BLOCK_INTERVAL) {
newDifficulty -= adjustmentFactor;
}
console.log(`newDifficulty`, newDifficulty);
return newDifficulty;
}
function isValidNewBlock(newBlock, previousBlock) {
if (!previousBlock) {
// This is the first block. Perform specific genesis block checks.
// For simplicity, we'll only check the index here.
if (newBlock.index !== 0) {
console.log("Error: The first block's index must be 0");
return false;
}
} else {
// This is not the first block. Perform regular checks.
if (previousBlock.index + 1 !== newBlock.index) {
console.log("Error: Invalid index");
return false;
} else if (
previousBlock.blockHeader.hash !==
newBlock.blockHeader.previousBlockHeader
) {
console.log("Error: Invalid previous block header");
return false;
} else {
let hash = calculateHashForBlock(newBlock);
if (hash !== newBlock.blockHeader.hash) {
console.log(
`Error: Invalid hash: ${hash} ${newBlock.blockHeader.hash}`
);
return false;
}
}
}
return true;
}
let storeBlock = async (newBlock) => {
return new Promise((resolve, reject) => {
db.put("block_" + newBlock.index, JSON.stringify(newBlock), function (err) {
if (err) {
console.error("Error storing block:", err);
reject(err);
} else {
if (newBlock.index !== 0)
console.log("--- Inserting block index: " + newBlock.index);
resolve(newBlock); // resolve with newBlock when it's successfully stored
}
});
});
};
async function addBlockToChain(newBlock) {
const existingBlock = await getBlockFromLevelDB(newBlock.index);
if (existingBlock) {
console.log(
chalk.blue.bold(
`Block with index ${newBlock.index} already exists, skipping`
)
);
return;
}
// Get the total count of blocks in your blockchain
let totalBlocks = await getBlockHeight();
console.log(`Current Local Block No:`, totalBlocks);
let previousBlock = null;
if (totalBlocks > 0) {
// if blocks exist, get the last block
previousBlock = await getBlockFromLevelDB(totalBlocks);
} else if (totalBlocks === 0) {
// if no blocks exist yet (other than genesis), get the genesis block
previousBlock = await getBlockFromLevelDB(0);
} else {
// handle error case if totalBlocks is less than 0
throw new Error("Invalid block count");
}
// Ensure that previousBlock is not null before proceeding
if (!previousBlock) {
console.log("Error: No previous block could be retrieved");
return;
}
if (isValidNewBlock(newBlock, previousBlock)) {
try {
return await lock.acquire("transaction", async () => {
try {
// Create a helper function to handle single transaction
const handleSingleTransaction = async (transaction) => {
if (await validateTransaction(transaction)) {
// Store transaction if it's valid
await storeTransaction(transaction);
tp.removeTransactions([transaction]);
return transaction.fee;
}
// If transaction is not valid, return 0 as fee
return 0;
};
// Handle single or multiple transactions
let totalFee = 0;
if (Array.isArray(newBlock.transactions)) {
for (let transaction of newBlock.transactions) {
console.log(`Handling multiple transactions`);
totalFee += await handleSingleTransaction(transaction);
}
} else {
console.log(`Handling single transaction`);
totalFee = await handleSingleTransaction(newBlock.transactions);
}
await rewardMiner(newBlock);
// Store block
await storeBlock(newBlock);
return newBlock;
} catch (error) {
console.error("Error processing transaction:", error);
}
});
} catch (error) {
console.error("Error acquiring lock:", error);
}
// return newBlock;
} else {
console.log("Error: Invalid block");
}
}
async function validateTransaction(transactions) {
if (!Array.isArray(transactions)) {
transactions = [transactions];
}
let valid = true;
for (let transaction of transactions) {
if (transaction.sender === "coinbase") {
console.log(`Genesis Block detected`);
continue; // skip genesis block, it's already been processed
}
const key = ec.keyFromPublic(transaction.sender, "hex");
const validSignature = key.verify(
calculateHashForTransaction(transaction),
transaction.signature
);
if (!validSignature) {
console.log(
`Invalid transaction from ${transaction.sender} due to invalid signature`
);
valid = false;
break;
}
try {
let senderBalance = await getBalance(transaction.sender);
senderBalance = senderBalance || 0;
if (transaction.amount + TRANSACTION_FEE > senderBalance) {
console.log(
`Invalid transaction from ${transaction.sender} due to insufficient funds`
);
valid = false;
break;
} else {
await updateBalance(
transaction.sender,
senderBalance - transaction.amount - TRANSACTION_FEE
);
let receiverBalance = await getBalance(transaction.receiver);
receiverBalance = receiverBalance || 0;
await updateBalance(
transaction.receiver,
receiverBalance + transaction.amount
);
}
} catch (err) {
console.log(`Error fetching balance: `, err);
valid = false;
break;
}
}
return valid;
}
function calculateHashForTransaction(transaction) {
return crypto
.createHash("sha256")
.update(
transaction.sender +
transaction.receiver +
transaction.amount +
transaction.fee +
transaction.time
)
.digest("hex");
}
async function validateTransfer(transaction) {
if (transaction.sender === "genesis") {
console.log(`Genesis Block detected`);
await updateBalance(transaction.receiver, transaction.amount);
return true;
}
const key = ec.keyFromPublic(transaction.sender, "hex");
const validSignature = key.verify(
calculateHashForTransaction(transaction),
transaction.signature
);
if (!validSignature) {
console.log(
`Invalid transaction from ${transaction.sender} due to invalid signature`
);
return false;
}
try {
let senderBalance = await getBalance(transaction.sender);
senderBalance = senderBalance || 0;
if (transaction.amount + TRANSACTION_FEE > senderBalance) {
console.log(
`Invalid transaction from ${transaction.sender} due to insufficient funds`
);
return false;
} else {
return true;
}
} catch (err) {
console.log(`Error fetching balance: `, err);
return false;
}
}
async function createAndAddTransaction(block, transactions, minerAddress) {
try {
return await lock.acquire("transaction", async () => {
try {
// Create a helper function to handle single transaction
const handleSingleTransaction = async (transaction) => {
if (await validateTransfer(transaction)) {
// Calculate the hash for the transaction
let transactionHash = transaction.calculateHash();
// Store this hash in the transaction object as transaction.id
transaction.id = transactionHash;
// Check if a transaction with the same hash is already in the block
if (
!block.transactions.some(
(t) => t.calculateHash() === transactionHash
)
) {
// If not, add the transaction to the block
block.transactions.push(transaction);
return transaction.fee;
}
}
return 0;
};
// Handle single or multiple transactions
let totalFee = 0;
if (Array.isArray(transactions)) {
for (let transaction of transactions) {
totalFee += await handleSingleTransaction(transaction);
}
} else {
totalFee = await handleSingleTransaction(transactions);
}
// Check if the total supply after the transactions and the fee would exceed the maximum supply
let totalSupply = await getTotalSupply();
console.log(`totalSupply`, totalSupply);
if (
totalSupply +
block.transactions.reduce(
(sum, transaction) => sum + transaction.amount,
0
) +
totalFee >
MAX_SUPPLY
) {
console.log(
"Error: These transactions would exceed the maximum supply of tokens"
);
return;
}
// Create miner reward transaction
let minerRewardTransaction = new Transaction(
"coinbase",
minerAddress,
MINING_REWARD,
totalFee,
undefined,
new Date().getTime()
);
// Calculate the hash and assign it directly to the object
minerRewardTransaction.id = minerRewardTransaction.calculateHash();
// Add the miner reward transaction to the block
block.transactions.unshift(minerRewardTransaction);
// Recalculate the Merkle root and mine the block
block.blockHeader.merkleRoot = new MerkleTree(
block.transactions
).getMerkleRoot();
// console.log(`transactions inside block`, transactions);
return await mineBlock(block);
} catch (error) {
console.error("Error processing transaction:", error);
}
});
} catch (error) {
console.error("Error acquiring lock:", error);
}
}
function getWalletBalance(walletAddress) {
return new Promise((resolve, reject) => {
// Prepend 'wallet-' to the walletAddress key
db.get(`wallet-${walletAddress}`, function (err, balance) {
if (err) {
if (err.notFound) {
console.log(`Wallet address ${walletAddress} does not exist.`);
resolve(0);
} else {
reject(err);
}
} else {
console.log(
`The balance of wallet address ${walletAddress} is ${balance}.`
);
resolve(Number(balance));
}
});
});
}
let getLatestBlock = async () => {
const blockHeight = await getBlockHeight();
return await getBlockFromLevelDB(blockHeight);
};
let getDbBlock = (index, res) => {
db.get(index, function (err, value) {
if (err) res.send(JSON.stringify(err));
else res.send(value);
});
};
let getBlock = (index) => {
if (blockchain.length - 1 >= index) return blockchain[index];
else return null;
};
function getBalance(user) {
return new Promise((resolve, reject) => {
// Prepend 'wallet-' to the user key
db.get(`wallet-${user}`, function (err, balance) {
if (err) {
if (err.notFound) {
resolve(0);
} else {
reject(err);
}
} else {
resolve(parseInt(balance));
}
});
});
}
function updateBalance(user, amount) {
return new Promise((resolve, reject) => {
// Prepend 'wallet-' to the user key
db.put(`wallet-${user}`, amount, function (err) {
if (err) {
console.log(`Failed to update balance for ${user}: `, err);
reject(err);
} else {
resolve();
}
});
});
}
async function getBlockFromLevelDB(index) {
return new Promise((resolve, reject) => {
db.get("block_" + index, function (err, value) {
if (err) {
if (err.type === "NotFoundError") {
resolve(undefined);
} else {
console.log("Block " + index + " get failed", err);
reject(err);
}
} else {
resolve(JSON.parse(value));
}
});
});
}
async function storeTransaction(transaction) {
// Create a new Transaction instance from the received data
const transactionInstance = new Transaction(
transaction.sender,
transaction.receiver,
transaction.amount,
transaction.fee,
transaction.signature,
transaction.time,
transaction.id
);
const transactionHash = transactionInstance.calculateHash();
try {
await db.put(transactionHash, JSON.stringify(transactionInstance));
return console.log("Stored transaction with hash:", transactionHash);
} catch (err) {
console.error("Error storing transaction:", err);
}
}
function getTransaction(transactionHash) {
return new Promise((resolve, reject) => {
db.get(transactionHash, function (err, value) {
if (err) {
if (err.type === "NotFoundError") {
console.log(`Transaction not found with hash: ${transactionHash}`);
resolve(null);
} else {
console.error("Error retrieving transaction:", err);
reject(err);
}
} else {
console.log("Retrieved transaction with hash:", transactionHash);
resolve(JSON.parse(value));
}
});
});
}
let getBlockHeight = async () => {
return new Promise((resolve, reject) => {
let height = 0;
db.createReadStream()
.on("data", function (data) {
if (data.key.toString().startsWith("block_")) {
height++;
}
})
.on("error", function (err) {
console.error("Error reading data stream:", err);
reject(err);
})
.on("end", function () {
resolve(height - 1); // Subtract 1 to match the highest block index
});
});
};
async function getTotalSupply() {
let totalSupply = 0;
// Create a read stream for the database
let stream = db.createReadStream();
// Listen for data events, which are emitted for each entry in the database
stream.on("data", function (data) {
// Convert the key to a string and check if it starts with 'wallet-' before trying to parse
if (data.key.toString().startsWith("wallet-")) {
let balance = parseInt(data.value);
totalSupply += balance;
}
});
// Return a promise that resolves with the total supply when the stream ends
return new Promise((resolve, reject) => {
stream.on("end", function () {
resolve(totalSupply);
});
stream.on("error", function (err) {
reject(err);
});
});
}
module.exports = {
addBlockToChain: addBlockToChain,
createNewBlock: createNewBlock,
mineBlock: mineBlock,
createAndAddTransaction: createAndAddTransaction,
createDb: createDb,
getWalletBalance: getWalletBalance,
validateTransfer: validateTransfer,
getDbBlock: getDbBlock,
getBlock: getBlock,
getLatestBlock: getLatestBlock,
getBlockHeight: getBlockHeight,
blockchain: blockchain,
getTotalSupply: getTotalSupply,
getTransaction: getTransaction,
getBlockFromLevelDB: getBlockFromLevelDB,
};