forked from bcoin-org/bcoin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spvnode.js
346 lines (286 loc) · 7.47 KB
/
spvnode.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
/*!
* spvnode.js - spv node for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
* https://github.com/bcoin-org/bcoin
*/
'use strict';
const Lock = require('../utils/lock');
const Chain = require('../blockchain/chain');
const Pool = require('../net/pool');
const HTTPServer = require('../http/server');
const RPC = require('../http/rpc');
const Node = require('./node');
/**
* Create an spv node which only maintains
* a chain, a pool, and an http server.
* @alias module:node.SPVNode
* @extends Node
* @constructor
* @param {Object?} options
* @param {Buffer?} options.sslKey
* @param {Buffer?} options.sslCert
* @param {Number?} options.httpPort
* @param {String?} options.httpHost
* @property {Boolean} loaded
* @property {Chain} chain
* @property {Pool} pool
* @property {HTTPServer} http
* @emits SPVNode#block
* @emits SPVNode#tx
* @emits SPVNode#error
*/
function SPVNode(options) {
if (!(this instanceof SPVNode))
return new SPVNode(options);
Node.call(this, options);
// SPV flag.
this.spv = true;
this.chain = new Chain({
network: this.network,
logger: this.logger,
db: this.config.str('db'),
prefix: this.config.prefix,
maxFiles: this.config.uint('max-files'),
cacheSize: this.config.mb('cache-size'),
entryCache: this.config.uint('entry-cache'),
forceFlags: this.config.bool('force-flags'),
checkpoints: this.config.bool('checkpoints'),
bip91: this.config.bool('bip91'),
bip148: this.config.bool('bip148'),
spv: true
});
this.pool = new Pool({
network: this.network,
logger: this.logger,
chain: this.chain,
prefix: this.config.prefix,
proxy: this.config.str('proxy'),
onion: this.config.bool('onion'),
upnp: this.config.bool('upnp'),
seeds: this.config.array('seeds'),
nodes: this.config.array('nodes'),
only: this.config.array('only'),
bip151: this.config.bool('bip151'),
bip150: this.config.bool('bip150'),
identityKey: this.config.buf('identity-key'),
maxOutbound: this.config.uint('max-outbound'),
persistent: this.config.bool('persistent'),
selfish: true,
listen: false
});
this.rpc = new RPC(this);
if (!HTTPServer.unsupported) {
this.http = new HTTPServer({
network: this.network,
logger: this.logger,
node: this,
prefix: this.config.prefix,
ssl: this.config.bool('ssl'),
keyFile: this.config.path('ssl-key'),
certFile: this.config.path('ssl-cert'),
host: this.config.str('http-host'),
port: this.config.uint('http-port'),
apiKey: this.config.str('api-key'),
noAuth: this.config.bool('no-auth')
});
}
this.rescanJob = null;
this.scanLock = new Lock();
this.watchLock = new Lock();
this._init();
}
Object.setPrototypeOf(SPVNode.prototype, Node.prototype);
/**
* Initialize the node.
* @private
*/
SPVNode.prototype._init = function _init() {
// Bind to errors
this.chain.on('error', err => this.error(err));
this.pool.on('error', err => this.error(err));
if (this.http)
this.http.on('error', err => this.error(err));
this.pool.on('tx', (tx) => {
if (this.rescanJob)
return;
this.emit('tx', tx);
});
this.chain.on('block', (block) => {
this.emit('block', block);
});
this.chain.on('connect', async (entry, block) => {
if (this.rescanJob) {
try {
await this.watchBlock(entry, block);
} catch (e) {
this.error(e);
}
return;
}
this.emit('connect', entry, block);
});
this.chain.on('disconnect', (entry, block) => {
this.emit('disconnect', entry, block);
});
this.chain.on('reorganize', (tip, competitor) => {
this.emit('reorganize', tip, competitor);
});
this.chain.on('reset', (tip) => {
this.emit('reset', tip);
});
this.loadPlugins();
};
/**
* Open the node and all its child objects,
* wait for the database to load.
* @alias SPVNode#open
* @returns {Promise}
*/
SPVNode.prototype._open = async function _open(callback) {
await this.chain.open();
await this.pool.open();
await this.openPlugins();
if (this.http)
await this.http.open();
this.logger.info('Node is loaded.');
};
/**
* Close the node, wait for the database to close.
* @alias SPVNode#close
* @returns {Promise}
*/
SPVNode.prototype._close = async function _close() {
if (this.http)
await this.http.close();
await this.closePlugins();
await this.pool.close();
await this.chain.close();
};
/**
* Scan for any missed transactions.
* Note that this will replay the blockchain sync.
* @param {Number|Hash} start - Start block.
* @param {Bloom} filter
* @param {Function} iter - Iterator.
* @returns {Promise}
*/
SPVNode.prototype.scan = async function scan(start, filter, iter) {
const unlock = await this.scanLock.lock();
const height = this.chain.height;
try {
await this.chain.replay(start);
if (this.chain.height < height) {
// We need to somehow defer this.
// await this.connect();
// this.startSync();
// await this.watchUntil(height, iter);
}
} finally {
unlock();
}
};
/**
* Watch the blockchain until a certain height.
* @param {Number} height
* @param {Function} iter
* @returns {Promise}
*/
SPVNode.prototype.watchUntil = function watchUntil(height, iter) {
return new Promise((resolve, reject) => {
this.rescanJob = new RescanJob(resolve, reject, height, iter);
});
};
/**
* Handled watched block.
* @param {ChainEntry} entry
* @param {MerkleBlock} block
* @returns {Promise}
*/
SPVNode.prototype.watchBlock = async function watchBlock(entry, block) {
const unlock = await this.watchLock.lock();
try {
if (entry.height < this.rescanJob.height) {
await this.rescanJob.iter(entry, block.txs);
return;
}
this.rescanJob.resolve();
this.rescanJob = null;
} catch (e) {
this.rescanJob.reject(e);
this.rescanJob = null;
} finally {
unlock();
}
};
/**
* Broadcast a transaction (note that this will _not_ be verified
* by the mempool - use with care, lest you get banned from
* bitcoind nodes).
* @param {TX|Block} item
* @returns {Promise}
*/
SPVNode.prototype.broadcast = async function broadcast(item) {
try {
await this.pool.broadcast(item);
} catch (e) {
this.emit('error', e);
}
};
/**
* Broadcast a transaction (note that this will _not_ be verified
* by the mempool - use with care, lest you get banned from
* bitcoind nodes).
* @param {TX} tx
* @returns {Promise}
*/
SPVNode.prototype.sendTX = function sendTX(tx) {
return this.broadcast(tx);
};
/**
* Broadcast a transaction. Silence errors.
* @param {TX} tx
* @returns {Promise}
*/
SPVNode.prototype.relay = function relay(tx) {
return this.broadcast(tx);
};
/**
* Connect to the network.
* @returns {Promise}
*/
SPVNode.prototype.connect = function connect() {
return this.pool.connect();
};
/**
* Disconnect from the network.
* @returns {Promise}
*/
SPVNode.prototype.disconnect = function disconnect() {
return this.pool.disconnect();
};
/**
* Start the blockchain sync.
*/
SPVNode.prototype.startSync = function startSync() {
return this.pool.startSync();
};
/**
* Stop syncing the blockchain.
*/
SPVNode.prototype.stopSync = function stopSync() {
return this.pool.stopSync();
};
/*
* Helpers
*/
function RescanJob(resolve, reject, height, iter) {
this.resolve = resolve;
this.reject = reject;
this.height = height;
this.iter = iter;
}
/*
* Expose
*/
module.exports = SPVNode;