-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.js
380 lines (328 loc) · 12.3 KB
/
block.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
"use strict";
const Blockchain = require('./blockchain.js');
const utils = require('./utils.js');
const { exec } = require('child_process');
// const solutions = utils.getSolutions();
/**
* A block is a collection of transactions, with a hash connecting it
* to a previous block.
*/
module.exports = class Block {
/**
* Creates a new Block. Note that the previous block will not be stored;
* instead, its hash value will be maintained in this block.
*
* @constructor
* @param {String} rewardAddr - The address to receive all mining rewards for this block.
* @param {Block} [prevBlock] - The previous block in the blockchain.
* @param {Number} [target] - The POW target. The miner must find a proof that
* produces a smaller value when hashed.
* @param {Number} [coinbaseReward] - The gold that a miner earns for finding a block proof.
* @param {String} sudoku_puzzle
* @param {String} sudoku_result
* @param {Array.<[string, string, string]>} moves_made - An array of tuples, where each tuple consists of three strings (row,col,num)
*/
constructor(rewardAddr, prevBlock, target=Blockchain.POW_TARGET, coinbaseReward=Blockchain.COINBASE_AMT_ALLOWED) {
// console.log(prevBlock ? prevBlock : 'no prev block');
this.prevBlockHash = prevBlock ? prevBlock.hashVal() : null;
this.target = target;
if (prevBlock && prevBlock.blockTime){
this.prevBlockTime = prevBlock.blockTime;
}
// Get the balances and nonces from the previous block, if available.
// Note that balances and nonces are NOT part of the serialized format.
this.balances = prevBlock ? new Map(prevBlock.balances) : new Map();
this.nextNonce = prevBlock ? new Map(prevBlock.nextNonce) : new Map();
if (prevBlock && prevBlock.rewardAddr) {
// Add the previous block's rewards to the miner who found the proof.
let winnerBalance = this.balanceOf(prevBlock.rewardAddr) || 0;
this.balances.set(prevBlock.rewardAddr, winnerBalance + prevBlock.totalRewards());
}
// Storing transactions in a Map to preserve key order.
this.transactions = new Map();
// Adding toJSON methods for transactions and balances, which help with
// serialization.
// this.transactions.toJSON = () => {
// return JSON.stringify(Array.from(this.transactions.entries()));
// }
// this.balances.toJSON = () => {
// return JSON.stringify(Array.from(this.balances.entries()));
// }
// Used to determine the winner between competing chains.
// Note that this is a little simplistic -- an attacker
// could make a long, but low-work chain. However, this works
// well enough for us.
this.chainLength = prevBlock ? prevBlock.chainLength+1 : 0;
this.timestamp = Date.now();
// The address that will gain both the coinbase reward and transaction fees,
// assuming that the block is accepted by the network.
this.rewardAddr = rewardAddr;
this.coinbaseReward = coinbaseReward;
}
/**
* Determines whether the block is the beginning of the chain.
*
* @returns {Boolean} - True if this is the first block in the chain.
*/
isGenesisBlock() {
return this.chainLength === 0;
}
async verifySol(seed){
const pythonScript = "puzzle_scripts/seed_verify.py";
const puzzle_str = await new Promise((resolve, reject) => {
exec(`python ${pythonScript} ${seed}`, (error, stdout, stderr) => {
if (error) {
console.log(`Error: ${error}`);
reject(error);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
}
resolve(stdout);
});
});
return puzzle_str;
}
// getCellValue(fileInput, rowNumber, columnNumber) {
// return new Promise((resolve, reject) => {
// Papa.parse(fileInput, {
// complete: function(results) {
// if (results && results.data && results.data[rowNumber - 1] && results.data[rowNumber - 1][columnNumber - 1]) {
// resolve(results.data[rowNumber - 1][columnNumber - 1]);
// } else {
// reject(new Error('Data not available'));
// }
// }
// });
// });
// }
// getSolution() {
// let solution = [];
// solution = utils.getSolutions();
// return solution;
// }
/**
* Returns true if the hash of the block is less than the target
* proof of work value.
*
* @returns {Boolean} - True if the block has a valid proof.
*/
async hasValidProof() {
// let puzzle_num = 0;
// if (!this.isGenesisBlock() && this.prevBlockHash) {
// puzzle_num = utils.htonum(this.prevBlockHash);
// }
// else{
// puzzle_num = 0;
// }
let decodedMoves = JSON.parse(Buffer.from(this.moves_made, 'base64').toString('ascii'));
// let sol = await this.verifySol(puzzle_num);
// const hash_val = utils.hash(sol);
// let n = `0x${hash_val}`;
// if (this.sudoku_result !== n){
// return false;
// }
// return true;
return utils.verifySudokuSolution(this.sudoku_puzzle,this.sudoku_result,decodedMoves);
}
/**
* Converts a Block into string form. Some fields are deliberately omitted.
* Note that Block.deserialize plus block.rerun should restore the block.
*
* @returns {String} - The block in JSON format.
*/
serialize() {
return JSON.stringify(this);
//if (this.isGenesisBlock()) {
// // The genesis block does not contain a proof or transactions,
// // but is the only block than can specify balances.
// /*******return `
// {"chainLength": "${this.chainLength}",
// "timestamp": "${this.timestamp}",
// "balances": ${JSON.stringify(Array.from(this.balances.entries()))}
// }
// `;****/
// let o = {
// chainLength: this.chainLength,
// timestamp: this.timestamp,
// balances: Array.from(this.balances.entries()),
// };
// return JSON.stringify(o, ['chainLength', 'timestamp', 'balances']);
//} else {
// // Other blocks must specify transactions and proof details.
// /******return `
// {"chainLength": "${this.chainLength}",
// "timestamp": "${this.timestamp}",
// "transactions": ${JSON.stringify(Array.from(this.transactions.entries()))},
// "prevBlockHash": "${this.prevBlockHash}",
// "proof": "${this.proof}",
// "rewardAddr": "${this.rewardAddr}"
// }
// `;*****/
// let o = {
// chainLength: this.chainLength,
// timestamp: this.timestamp,
// transactions: Array.from(this.transactions.entries()),
// prevBlockHash: this.prevBlockHash,
// proof: this.proof,
// rewardAddr: this.rewardAddr,
// };
// return JSON.stringify(o, ['chainLength', 'timestamp', 'transactions',
// 'prevBlockHash', 'proof', 'rewardAddr']);
//}
}
toJSON() {
let o = {
chainLength: this.chainLength,
timestamp: this.timestamp,
};
if (this.isGenesisBlock()) {
// The genesis block does not contain a proof or transactions,
// but is the only block than can specify balances.
o.balances = Array.from(this.balances.entries());
} else {
// Other blocks must specify transactions and proof details.
o.transactions = Array.from(this.transactions.entries());
o.prevBlockHash = this.prevBlockHash;
o.prevBlockTime = this.prevBlockTime;
// o.proof = this.proof;
o.sudoku_puzzle = this.sudoku_puzzle;
o.sudoku_result = this.sudoku_result;
o.blockTime = this.blockTime;
o.moves_made = this.moves_made;
o.rewardAddr = this.rewardAddr;
}
return o;
}
/**
* Returns the cryptographic hash of the current block.
* The block is first converted to its serial form, so
* any unimportant fields are ignored.
*
* @returns {String} - cryptographic hash of the block.
*/
hashVal() {
return utils.hash(this.serialize());
}
/**
* Returns the hash of the block as its id.
*
* @returns {String} - A unique ID for the block.
*/
get id() {
return this.hashVal();
}
/**
* Accepts a new transaction if it is valid and adds it to the block.
*
* @param {Transaction} tx - The transaction to add to the block.
* @param {Client} [client] - A client object, for logging useful messages.
*
* @returns {Boolean} - True if the transaction was added successfully.
*/
addTransaction(tx, client) {
if (this.transactions.get(tx.id)) {
if (client) client.log(`Duplicate transaction ${tx.id}.`);
return false;
} else if (tx.sig === undefined) {
if (client) client.log(`Unsigned transaction ${tx.id}.`);
return false;
} else if (!tx.validSignature()) {
if (client) client.log(`Invalid signature for transaction ${tx.id}.`);
return false;
} else if (!tx.sufficientFunds(this)) {
if (client) client.log(`Insufficient gold for transaction ${tx.id}.`);
return false;
}
// Checking and updating nonce value.
// This portion prevents replay attacks.
let nonce = this.nextNonce.get(tx.from) || 0;
if (tx.nonce < nonce) {
if (client) client.log(`Replayed transaction ${tx.id}.`);
return false;
} else if (tx.nonce > nonce) {
// FIXME: Need to do something to handle this case more gracefully.
if (client) client.log(`Out of order transaction ${tx.id}.`);
return false;
} else {
this.nextNonce.set(tx.from, nonce + 1);
}
// Adding the transaction to the block
this.transactions.set(tx.id, tx);
// Taking gold from the sender
let senderBalance = this.balanceOf(tx.from);
this.balances.set(tx.from, senderBalance - tx.totalOutput());
// Giving gold to the specified output addresses
tx.outputs.forEach(({amount, address}) => {
let oldBalance = this.balanceOf(address);
this.balances.set(address, amount + oldBalance);
});
return true;
}
/**
* When a block is received from another party, it does not include balances or a record of
* the latest nonces for each client. This method restores this information be wiping out
* and re-adding all transactions. This process also identifies if any transactions were
* invalid due to insufficient funds or replayed transactions, in which case the block
* should be rejected.
*
* @param {Block} prevBlock - The previous block in the blockchain, used for initial balances.
*
* @returns {Boolean} - True if the block's transactions are all valid.
*/
rerun(prevBlock) {
// Setting balances to the previous block's balances.
this.balances = new Map(prevBlock.balances);
this.nextNonce = new Map(prevBlock.nextNonce);
// Adding coinbase reward for prevBlock.
let winnerBalance = this.balanceOf(prevBlock.rewardAddr);
if (prevBlock.rewardAddr) this.balances.set(prevBlock.rewardAddr, winnerBalance + prevBlock.totalRewards());
// Re-adding all transactions.
let txs = this.transactions;
this.transactions = new Map();
for (let tx of txs.values()) {
let success = this.addTransaction(tx);
if (!success) return false;
}
return true;
}
/**
* Gets the available gold of a user identified by an address.
* Note that this amount is a snapshot in time - IF the block is
* accepted by the network, ignoring any pending transactions,
* this is the amount of funds available to the client.
*
* @param {String} addr - Address of a client.
*
* @returns {Number} - The available gold for the specified user.
*/
balanceOf(addr) {
return this.balances.get(addr) || 0;
}
/**
* The total amount of gold paid to the miner who produced this block,
* if the block is accepted. This includes both the coinbase transaction
* and any transaction fees.
*
* @returns {Number} Total reward in gold for the user.
*
*/
totalRewards() {
return [...this.transactions].reduce(
(reward, [, tx]) => reward + tx.fee,
this.coinbaseReward);
}
/**
* Determines whether a transaction is in the block. Note that only the
* block itself is checked; if it returns false, the transaction might
* still be included in one of its ancestor blocks.
*
* @param {Transaction} tx - The transaction that we are checking for.
*
* @returns {boolean} - True if the transaction is contained in this block.
*/
contains(tx) {
return this.transactions.has(tx.id);
}
};