-
Notifications
You must be signed in to change notification settings - Fork 16
/
chain.js
176 lines (152 loc) · 4.68 KB
/
chain.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
const path = require("path");
const Block = require("./block.js").Block;
const BlockHeader = require("./block.js").BlockHeader;
const verifyTransaction = require("./transaction.js").verifyTransaction;
const moment = require("moment");
const CryptoJS = require("crypto-js");
const rocksdb = require("rocksdb");
const fs = require("fs");
let db;
const MEDIAN_BLOCK_COUNT = 11;
const FUTURE_TIMESTAMP_THRESHOLD = 7200; // 2 hours in seconds
const calculateMedianTimestamp = (blockchain) => {
const blockCount = blockchain.length;
const medianIndex = Math.floor(MEDIAN_BLOCK_COUNT / 2);
let medianTimestamps = blockchain
.slice(Math.max(blockCount - MEDIAN_BLOCK_COUNT, 0)) // Get the last MEDIAN_BLOCK_COUNT blocks
.map((block) => block.blockHeader.time)
.sort((a, b) => a - b); // Sort timestamps
return medianTimestamps[medianIndex] || 0;
};
const isTimestampValid = (newBlock, blockchain) => {
if (blockchain.length < MEDIAN_BLOCK_COUNT) {
return true; // Not enough blocks for a median check
}
const medianTimestamp = calculateMedianTimestamp(blockchain);
const currentNodeTime = moment().unix();
return (
newBlock.blockHeader.time > medianTimestamp &&
newBlock.blockHeader.time <= currentNodeTime + FUTURE_TIMESTAMP_THRESHOLD
);
};
// proof of work
const calculateHash = (
index,
previousBlockHeader,
merkleRoot,
time,
nBits,
nonce
) => {
return CryptoJS.SHA256(
index + previousBlockHeader + merkleRoot + time + nBits + nonce
).toString();
};
let createDb = async (peerId) => {
let dir = path.join(__dirname, "db", peerId);
try {
await fs.promises.mkdir(dir, { recursive: true });
db = rocksdb(dir);
db.open((err) => {
if (err) {
console.error("Error opening RocksDB database:", err);
} else {
storeBlock(getGenesisBlock());
}
});
} catch (err) {
console.error("Error creating database directory:", err);
}
};
let getGenesisBlock = () => {
let blockHeader = new BlockHeader(
1,
null,
"0x1bc1100000000000000000000000000000000000000000000",
moment().unix(),
"0x171b7320",
"1CAD2B8C"
);
return new Block(blockHeader, 0, null);
};
let getLatestBlock = () => blockchain[blockchain.length - 1];
let addBlock = (newBlock) => {
let prevBlock = getLatestBlock();
if (
prevBlock.index < newBlock.index &&
newBlock.blockHeader.previousBlockHeader ===
prevBlock.blockHeader.merkleRoot &&
isTimestampValid(newBlock, blockchain)
) {
// Add the timestamp validation check
blockchain.push(newBlock);
storeBlock(newBlock);
}
{
blockchain.push(newBlock);
storeBlock(newBlock); // When you generate a new block using the generateNextBlock method, you can now store the block in the LevelDB database
}
};
// create a storeBlock method to store the new block
let storeBlock = (newBlock) => {
db.put(newBlock.index, JSON.stringify(newBlock), function (err) {
if (err) console.error("Error storing block:", err);
else console.log("--- Inserting block index: " + newBlock.index);
});
};
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;
};
const blockchain = [getGenesisBlock()];
const generateNextBlock = (txns) => {
txns = txns || []; // Default to an empty array if txns is not provided or is not an array
const prevBlock = getLatestBlock(),
prevMerkleRoot = prevBlock.blockHeader.merkleRoot;
const nextIndex = prevBlock.index + 1,
nextTime = moment().unix();
let nonce = 0; // Start with a nonce of 0
let nextMerkleRoot, hash;
do {
nonce++;
nextMerkleRoot = CryptoJS.SHA256(
1,
prevMerkleRoot,
nextTime + nonce
).toString();
hash = calculateHash(1, prevMerkleRoot, nextMerkleRoot, nextTime, 4, nonce); // Assuming a difficulty of 4 leading zeros
} while (hash.substring(0, 4) !== "0000");
const blockHeader = new BlockHeader(
1,
prevMerkleRoot,
nextMerkleRoot,
nextTime,
4,
nonce
);
// Verify transactions
for (const txn of txns) {
if (!verifyTransaction(txn, blockchain)) {
throw new Error("Invalid transaction");
}
}
const newBlock = new Block(blockHeader, nextIndex, txns);
blockchain.push(newBlock);
storeBlock(newBlock);
return newBlock;
};
if (typeof exports != "undefined") {
exports.addBlock = addBlock;
exports.getBlock = getBlock;
exports.blockchain = blockchain;
exports.getLatestBlock = getLatestBlock;
exports.generateNextBlock = generateNextBlock;
exports.createDb = createDb;
exports.getDbBlock = getDbBlock;
}