-
Notifications
You must be signed in to change notification settings - Fork 20
/
miner.js
187 lines (161 loc) · 6.21 KB
/
miner.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
"use strict";
let Blockchain = require('./blockchain.js');
let Client = require('./client.js');
/**
* Miners are clients, but they also mine blocks looking for "proofs".
*/
module.exports = class Miner extends Client {
/**
* When a new miner is created, but the PoW search is **not** yet started.
* The initialize method kicks things off.
*
* @constructor
* @param {Object} obj - The properties of the client.
* @param {String} [obj.name] - The miner's name, used for debugging messages.
* @param {Object} net - The network that the miner will use
* to send messages to all other clients.
* @param {String} [obj.password] - The client's password, used for generating address.
* @param {Block} [startingBlock] - The most recently ALREADY ACCEPTED block.
* @param {Object} [obj.keyPair] - The public private keypair for the client.
* @param {Number} [miningRounds] - The number of rounds a miner mines before checking
* for messages. (In single-threaded mode with FakeNet, this parameter can
* simulate miners with more or less mining power.)
*/
constructor({name, password, net, startingBlock, keyPair, miningRounds=Blockchain.NUM_ROUNDS_MINING} = {}) {
super({name, password, net, startingBlock, keyPair});
this.miningRounds=miningRounds;
// Set of transactions to be added to the next block.
this.transactions = new Set();
}
/**
* Starts listeners and begins mining.
*/
initialize() {
this.startNewSearch();
this.on(Blockchain.START_MINING, this.findProof);
this.on(Blockchain.POST_TRANSACTION, this.addTransaction);
setTimeout(() => this.emit(Blockchain.START_MINING), 0);
}
/**
* Sets up the miner to start searching for a new block.
*
* @param {Set} [txSet] - Transactions the miner has that have not been accepted yet.
*/
startNewSearch(txSet=new Set()) {
this.currentBlock = Blockchain.makeBlock(this.address, this.lastBlock);
// Merging txSet into the transaction queue.
// These transactions may include transactions not already included
// by a recently received block, but that the miner is aware of.
txSet.forEach((tx) => this.transactions.add(tx));
// Add queued-up transactions to block.
this.transactions.forEach((tx) => {
this.currentBlock.addTransaction(tx, this);
});
this.transactions.clear();
// Start looking for a proof at 0.
this.currentBlock.proof = 0;
}
/**
* Looks for a "proof". It breaks after some time to listen for messages. (We need
* to do this since JS does not support concurrency).
*
* The 'oneAndDone' field is used for testing only; it prevents the findProof method
* from looking for the proof again after the first attempt.
*
* @param {boolean} oneAndDone - Give up after the first PoW search (testing only).
*/
findProof(oneAndDone=false) {
let pausePoint = this.currentBlock.proof + this.miningRounds;
while (this.currentBlock.proof < pausePoint) {
if (this.currentBlock.hasValidProof()) {
this.log(`found proof for block ${this.currentBlock.chainLength}: ${this.currentBlock.proof}`);
this.announceProof();
// Note: calling receiveBlock triggers a new search.
this.receiveBlock(this.currentBlock);
break;
}
this.currentBlock.proof++;
}
// If we are testing, don't continue the search.
if (!oneAndDone) {
// Check if anyone has found a block, and then return to mining.
setTimeout(() => this.emit(Blockchain.START_MINING), 0);
}
}
/**
* Broadcast the block, with a valid proof included.
*/
announceProof() {
this.net.broadcast(Blockchain.PROOF_FOUND, this.currentBlock);
}
/**
* Receives a block from another miner. If it is valid,
* the block will be stored. If it is also a longer chain,
* the miner will accept it and replace the currentBlock.
*
* @param {Block | Object} b - The block
*/
receiveBlock(s) {
let b = super.receiveBlock(s);
if (b === null) return null;
// We switch over to the new chain only if it is better.
if (this.currentBlock && b.chainLength >= this.currentBlock.chainLength) {
this.log(`cutting over to new chain.`);
let txSet = this.syncTransactions(b);
this.startNewSearch(txSet);
}
return b;
}
/**
* This function should determine what transactions
* need to be added or deleted. It should find a common ancestor (retrieving
* any transactions from the rolled-back blocks), remove any transactions
* already included in the newly accepted blocks, and add any remaining
* transactions to the new block.
*
* @param {Block} nb - The newly accepted block.
*
* @returns {Set} - The set of transactions that have not yet been accepted by the new block.
*/
syncTransactions(nb) {
let cb = this.currentBlock;
let cbTxs = new Set();
let nbTxs = new Set();
// The new block may be ahead of the old block. We roll back the new chain
// to the matching height, collecting any transactions.
while (nb.chainLength > cb.chainLength) {
nb.transactions.forEach((tx) => nbTxs.add(tx));
nb = this.blocks.get(nb.prevBlockHash);
}
// Step back in sync until we hit the common ancestor.
while (cb && cb.id !== nb.id) {
// Store any transactions in the two chains.
cb.transactions.forEach((tx) => cbTxs.add(tx));
nb.transactions.forEach((tx) => nbTxs.add(tx));
cb = this.blocks.get(cb.prevBlockHash);
nb = this.blocks.get(nb.prevBlockHash);
}
// Remove all transactions that the new chain already has.
nbTxs.forEach((tx) => cbTxs.delete(tx));
return cbTxs;
}
/**
* Returns false if transaction is not accepted. Otherwise stores
* the transaction to be added to the next block.
*
* @param {Transaction | String} tx - The transaction to add.
*/
addTransaction(tx) {
tx = Blockchain.makeTransaction(tx);
this.transactions.add(tx);
}
/**
* When a miner posts a transaction, it must also add it to its current list of transactions.
*
* @param {...any} args - Arguments needed for Client.postTransaction.
*/
postTransaction(...args) {
let tx = super.postTransaction(...args);
return this.addTransaction(tx);
}
};