-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
358 lines (308 loc) · 11.6 KB
/
client.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
"use strict";
let EventEmitter = require('events');
let Blockchain = require('./blockchain.js');
let utils = require('./utils.js');
/**
* A client has a public/private keypair and an address.
* It can send and receive messages on the Blockchain network.
*/
module.exports = class Client extends EventEmitter {
/**
* The net object determines how the client communicates
* with other entities in the system. (This approach allows us to
* simplify our testing setup.)
*
* @constructor
* @param {Object} obj - The properties of the client.
* @param {String} [obj.name] - The client's name, used for debugging messages.
* @param {Object} obj.net - The network used by the client
* to send messages to all miners and clients.
* @param {Block} [obj.startingBlock] - The starting point of the blockchain for the client.
* @param {Object} [obj.keyPair] - The public private keypair for the client.
*/
constructor({name, net, startingBlock, keyPair} = {}) {
super();
this.net = net;
this.name = name;
if (keyPair === undefined) {
this.keyPair = utils.generateKeypair();
} else {
this.keyPair = keyPair;
}
this.address = utils.calcAddress(this.keyPair.public);
// Establishes order of transactions. Incremented with each
// new output transaction from this client. This feature
// avoids replay attacks.
this.nonce = 0;
// A map of transactions where the client has spent money,
// but where the transaction has not yet been confirmed.
this.pendingOutgoingTransactions = new Map();
// A map of transactions received but not yet confirmed.
this.pendingReceivedTransactions = new Map();
// A map of all block hashes to the accepted blocks.
this.blocks = new Map();
// A map of missing block IDS to the list of blocks depending
// on the missing blocks.
this.pendingBlocks = new Map();
if (startingBlock) {
this.setGenesisBlock(startingBlock);
}
// Setting up listeners to receive messages from other clients.
this.on(Blockchain.PROOF_FOUND, this.receiveBlock);
this.on(Blockchain.MISSING_BLOCK, this.provideMissingBlock);
}
/**
* The genesis block can only be set if the client does not already
* have the genesis block.
*
* @param {Block} startingBlock - The genesis block of the blockchain.
*/
setGenesisBlock(startingBlock) {
if (this.lastBlock) {
throw new Error("Cannot set genesis block for existing blockchain.");
}
// Transactions from this block or older are assumed to be confirmed,
// and therefore are spendable by the client. The transactions could
// roll back, but it is unlikely.
this.lastConfirmedBlock = startingBlock;
// The last block seen. Any transactions after lastConfirmedBlock
// up to lastBlock are considered pending.
this.lastBlock = startingBlock;
this.blocks.set(startingBlock.id, startingBlock);
}
/**
* The amount of gold available to the client, not counting any pending
* transactions. This getter looks at the last confirmed block, since
* transactions in newer blocks may roll back.
*/
get confirmedBalance() {
return this.lastConfirmedBlock.balanceOf(this.address);
}
/**
* Any gold received in the last confirmed block or before is considered
* spendable, but any gold received more recently is not yet available.
* However, any gold given by the client to other clients in unconfirmed
* transactions is treated as unavailable.
*/
get availableGold() {
let pendingSpent = 0;
this.pendingOutgoingTransactions.forEach((tx) => {
pendingSpent += tx.totalOutput();
});
return this.confirmedBalance - pendingSpent;
}
/**
* Broadcasts a transaction from the client giving gold to the clients
* specified in 'outputs'. A transaction fee may be specified, which can
* be more or less than the default value.
*
* @param {Array} outputs - The list of outputs of other addresses and
* amounts to pay.
* @param {number} [fee] - The transaction fee reward to pay the miner.
*
* @returns {Transaction} - The posted transaction.
*/
postTransaction(outputs, fee=Blockchain.DEFAULT_TX_FEE) {
// We calculate the total value of gold needed.
let totalPayments = outputs.reduce((acc, {amount}) => acc + amount, 0) + fee;
// Make sure the client has enough gold.
if (totalPayments > this.availableGold) {
throw new Error(`Requested ${totalPayments}, but account only has ${this.availableGold}.`);
}
// Create and broadcast the transaction.
return this.postGenericTransaction({
outputs: outputs,
fee: fee,
});
}
/**
* Broadcasts a transaction from the client. No validation is performed,
* so the transaction might be rejected by other miners.
*
* This method is useful for handling special transactions with unique
* parameters required, but generally should not be called directly by clients.
*
* @param {Object} txData - The key-value pairs of the transaction.
*
* @returns {Transaction} - The posted transaction.
*/
postGenericTransaction(txData) {
// Creating a transaction, with defaults for the
// from, nonce, and pubKey fields.
let tx = Blockchain.makeTransaction(
Object.assign({
from: this.address,
nonce: this.nonce,
pubKey: this.keyPair.public,
},
txData));
tx.sign(this.keyPair.private);
// Adding transaction to pending.
this.pendingOutgoingTransactions.set(tx.id, tx);
this.nonce++;
this.net.broadcast(Blockchain.POST_TRANSACTION, tx);
return tx;
}
/**
* Validates and adds a block to the list of blocks, possibly updating the head
* of the blockchain. Any transactions in the block are rerun in order to
* update the gold balances for all clients. If any transactions are found to be
* invalid due to lack of funds, the block is rejected and 'null' is returned to
* indicate failure.
*
* If any blocks cannot be connected to an existing block but seem otherwise valid,
* they are added to a list of pending blocks and a request is sent out to get the
* missing blocks from other clients.
*
* @param {Block | Object} block - The block to add to the clients list of available blocks.
*
* @returns {Block | null} The block with rerun transactions, or null for an invalid block.
*/
receiveBlock(block) {
// If the block is a string, then deserialize it.
block = Blockchain.deserializeBlock(block);
// Ignore the block if it has been received previously.
if (this.blocks.has(block.id)) return null;
// First, make sure that the block has a valid proof.
if (!block.hasValidProof() && !block.isGenesisBlock()) {
this.log(`Block ${block.id} does not have a valid proof.`);
return null;
}
// Make sure that we have the previous blocks, unless it is the genesis block.
// If we don't have the previous blocks, request the missing blocks and exit.
let prevBlock = this.blocks.get(block.prevBlockHash);
if (!prevBlock && !block.isGenesisBlock()) {
let stuckBlocks = this.pendingBlocks.get(block.prevBlockHash);
// If this is the first time that we have identified this block as missing,
// send out a request for the block.
if (stuckBlocks === undefined) {
this.requestMissingBlock(block);
stuckBlocks = new Set();
}
stuckBlocks.add(block);
this.pendingBlocks.set(block.prevBlockHash, stuckBlocks);
return null;
}
if (!block.isGenesisBlock()) {
// Verify the block, and store it if everything looks good.
// This code will trigger an exception if there are any invalid transactions.
let success = block.rerun(prevBlock);
if (!success) return null;
}
// Storing the block.
this.blocks.set(block.id, block);
// If it is a better block than the client currently has, set that
// as the new currentBlock, and update the lastConfirmedBlock.
if (this.lastBlock.chainLength < block.chainLength) {
this.lastBlock = block;
this.setLastConfirmed();
}
// Go through any blocks that were waiting for this block
// and recursively call receiveBlock.
let unstuckBlocks = this.pendingBlocks.get(block.id) || [];
// Remove these blocks from the pending set.
this.pendingBlocks.delete(block.id);
unstuckBlocks.forEach((b) => {
this.log(`Processing unstuck block ${b.id}`);
this.receiveBlock(b);
});
return block;
}
/**
* Request the previous block from the network.
*
* @param {Block} block - The block that is connected to a missing block.
*/
requestMissingBlock(block) {
this.log(`Asking for missing block: ${block.prevBlockHash}`);
let msg = {
from: this.address,
missing: block.prevBlockHash,
};
this.net.broadcast(Blockchain.MISSING_BLOCK, msg);
}
/**
* Resend any transactions in the pending list.
*/
resendPendingTransactions() {
this.pendingOutgoingTransactions.forEach((tx) => {
this.net.broadcast(Blockchain.POST_TRANSACTION, tx);
});
}
/**
* Takes an object representing a request for a missing block.
* If the client has the block, it will send the block to the
* client that requested it.
*
* @param {Object} msg - Request for a missing block.
* @param {String} msg.missing - ID of the missing block.
*/
provideMissingBlock(msg) {
if (this.blocks.has(msg.missing)) {
this.log(`Providing missing block ${msg.missing}`);
let block = this.blocks.get(msg.missing);
this.net.sendMessage(msg.from, Blockchain.PROOF_FOUND, block);
}
}
/**
* Sets the last confirmed block according to the most recently accepted block,
* also updating pending transactions according to this block.
* Note that the genesis block is always considered to be confirmed.
*/
setLastConfirmed() {
let block = this.lastBlock;
let confirmedBlockHeight = block.chainLength - Blockchain.CONFIRMED_DEPTH;
if (confirmedBlockHeight < 0) {
confirmedBlockHeight = 0;
}
while (block.chainLength > confirmedBlockHeight) {
block = this.blocks.get(block.prevBlockHash);
}
this.lastConfirmedBlock = block;
// Update pending transactions according to the new last confirmed block.
this.pendingOutgoingTransactions.forEach((tx, txID) => {
if (this.lastConfirmedBlock.contains(tx)) {
this.pendingOutgoingTransactions.delete(txID);
}
});
}
/**
* Utility method that displays all confirmed balances for all clients,
* according to the client's own perspective of the network.
*/
showAllBalances() {
let bc = Blockchain.getInstance();
this.log("Showing balances:");
for (let [id,balance] of this.lastConfirmedBlock.balances) {
let name = bc.getClientName(id);
if (name) {
console.log(` ${id} (${name}): ${balance}`);
} else {
console.log(` ${id}: ${balance}`);
}
}
}
/**
* Logs messages to stdout, including the name to make debugging easier.
* If the client does not have a name, then one is calculated from the
* client's address.
*
* @param {String} msg - The message to display to the console.
*/
log(msg) {
let name = this.name || this.address.substring(0,10);
console.log(`${name}: ${msg}`);
}
/**
* Print out the blocks in the blockchain from the current head
* to the genesis block. Only the Block IDs are printed.
*/
showBlockchain() {
let block = this.lastBlock;
console.log("BLOCKCHAIN:");
while (block !== undefined) {
console.log(block.id);
block = this.blocks.get(block.prevBlockHash);
}
}
};