itns-sidechain/lib/node/fullnode.js

545 lines
13 KiB
JavaScript
Raw Normal View History

/*!
2018-02-01 13:28:31 -08:00
* fullnode.js - full node for hsk
2018-02-01 13:40:45 -08:00
* Copyright (c) 2017-2018, Christopher Jeffrey (MIT License).
2018-02-01 13:28:31 -08:00
* https://github.com/handshakecompany/hsk
2016-03-10 02:40:33 -08:00
*/
2016-06-13 01:06:01 -07:00
'use strict';
2017-11-01 12:57:11 -07:00
const assert = require('assert');
2017-06-29 20:54:07 -07:00
const Chain = require('../blockchain/chain');
const Fees = require('../mempool/fees');
const Mempool = require('../mempool/mempool');
const Pool = require('../net/pool');
const Miner = require('../mining/miner');
const Node = require('./node');
2017-10-26 12:31:08 -07:00
const HTTP = require('./http');
const RPC = require('./rpc');
2018-01-02 20:24:56 -08:00
const pkg = require('../pkg');
2018-02-03 20:48:36 -08:00
const {HandshakeServer} = require('../covenants/dns');
2016-03-10 02:40:33 -08:00
/**
2017-11-16 19:43:07 -08:00
* Full Node
2017-02-07 14:17:41 -08:00
* Respresents a fullnode complete with a
* chain, mempool, miner, etc.
2017-02-03 22:47:26 -08:00
* @alias module:node.FullNode
* @extends Node
2016-03-10 02:40:33 -08:00
*/
2017-11-16 19:43:07 -08:00
class FullNode extends Node {
/**
* Create a full node.
* @constructor
* @param {Object?} options
*/
constructor(options) {
2018-01-02 20:24:56 -08:00
super(pkg.name, pkg.cfg, 'debug.log', options);
2017-11-16 19:43:07 -08:00
this.opened = false;
// SPV flag.
this.spv = false;
// Instantiate blockchain.
this.chain = new Chain({
network: this.network,
logger: this.logger,
workers: this.workers,
2017-12-06 17:05:00 -08:00
memory: this.config.bool('memory'),
2017-11-16 19:43:07 -08:00
prefix: this.config.prefix,
maxFiles: this.config.uint('max-files'),
cacheSize: this.config.mb('cache-size'),
forceFlags: this.config.bool('force-flags'),
prune: this.config.bool('prune'),
checkpoints: this.config.bool('checkpoints'),
coinCache: this.config.mb('coin-cache'),
entryCache: this.config.uint('entry-cache'),
indexTX: this.config.bool('index-tx'),
indexAddress: this.config.bool('index-address')
});
// Fee estimation.
this.fees = new Fees(this.logger);
this.fees.init();
// Mempool needs access to the chain.
this.mempool = new Mempool({
network: this.network,
logger: this.logger,
workers: this.workers,
chain: this.chain,
fees: this.fees,
2017-12-06 17:05:00 -08:00
memory: this.config.bool('memory'),
2017-11-16 19:43:07 -08:00
prefix: this.config.prefix,
persistent: this.config.bool('persistent-mempool'),
maxSize: this.config.mb('mempool-size'),
limitFree: this.config.bool('limit-free'),
limitFreeRelay: this.config.uint('limit-free-relay'),
requireStandard: this.config.bool('require-standard'),
rejectAbsurdFees: this.config.bool('reject-absurd-fees'),
indexAddress: this.config.bool('index-address')
});
// Pool needs access to the chain and mempool.
this.pool = new Pool({
network: this.network,
logger: this.logger,
chain: this.chain,
mempool: this.mempool,
prefix: this.config.prefix,
selfish: this.config.bool('selfish'),
compact: this.config.bool('compact'),
bip37: this.config.bool('bip37'),
identityKey: this.config.buf('identity-key'),
maxOutbound: this.config.uint('max-outbound'),
maxInbound: this.config.uint('max-inbound'),
createSocket: this.config.func('create-socket'),
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'),
publicHost: this.config.str('public-host'),
publicPort: this.config.uint('public-port'),
host: this.config.str('host'),
port: this.config.uint('port'),
listen: this.config.bool('listen'),
2017-12-06 17:05:00 -08:00
memory: this.config.bool('memory')
2017-11-16 19:43:07 -08:00
});
// Miner needs access to the chain and mempool.
this.miner = new Miner({
network: this.network,
logger: this.logger,
workers: this.workers,
chain: this.chain,
mempool: this.mempool,
address: this.config.array('coinbase-address'),
coinbaseFlags: this.config.str('coinbase-flags'),
preverify: this.config.bool('preverify'),
maxWeight: this.config.uint('max-weight'),
reservedWeight: this.config.uint('reserved-weight'),
reservedSigops: this.config.uint('reserved-sigops')
});
// RPC needs access to the node.
this.rpc = new RPC(this);
// HTTP needs access to the node.
this.http = new HTTP({
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')
});
2018-02-03 20:48:36 -08:00
this.dns = new HandshakeServer(this.chain.cdb, 'udp4');
2017-11-16 19:43:07 -08:00
this.init();
}
2017-11-16 19:43:07 -08:00
/**
* Initialize the node.
* @private
*/
init() {
// Bind to errors
this.chain.on('error', err => this.error(err));
this.mempool.on('error', err => this.error(err));
this.pool.on('error', err => this.error(err));
this.miner.on('error', err => this.error(err));
if (this.http)
this.http.on('error', err => this.error(err));
this.mempool.on('tx', (tx) => {
this.miner.cpu.notifyEntry();
this.emit('tx', tx);
});
this.chain.on('connect', async (entry, block) => {
try {
await this.mempool._addBlock(entry, block.txs);
} catch (e) {
this.error(e);
}
this.emit('block', block);
this.emit('connect', entry, block);
});
this.chain.on('disconnect', async (entry, block) => {
try {
await this.mempool._removeBlock(entry, block.txs);
} catch (e) {
this.error(e);
}
this.emit('disconnect', entry, block);
});
this.chain.on('reorganize', async (tip, competitor) => {
try {
await this.mempool._handleReorg();
} catch (e) {
this.error(e);
}
this.emit('reorganize', tip, competitor);
});
this.chain.on('reset', async (tip) => {
try {
await this.mempool._reset();
} catch (e) {
this.error(e);
}
this.emit('reset', tip);
});
2018-02-04 22:31:27 -08:00
const logger = this.logger.context('dns');
this.dns.on('error', (err) => {
logger.error(err);
});
this.dns.on('query', (req, res) => {
2018-02-19 01:48:17 -08:00
{
logger.debug('Request:');
const parts = req.toString().split('\n');
for (const part of parts)
logger.debug(part);
}
{
logger.debug('Response:');
const parts = res.toString().split('\n');
for (const part of parts)
logger.debug(part);
}
2018-02-04 22:31:27 -08:00
});
this.dns.on('log', (...args) => {
logger.debug(...args);
});
2017-11-16 19:43:07 -08:00
this.loadPlugins();
}
2016-04-04 18:45:02 -07:00
2017-11-16 19:43:07 -08:00
/**
* Open the node and all its child objects,
* wait for the database to load.
* @alias FullNode#open
* @returns {Promise}
*/
2017-11-16 19:43:07 -08:00
async open() {
assert(!this.opened, 'FullNode is already open.');
this.opened = true;
2017-11-01 12:57:11 -07:00
2017-11-16 19:43:07 -08:00
await this.handlePreopen();
2018-02-03 20:48:36 -08:00
await this.chain.open(53);
2017-11-16 19:43:07 -08:00
await this.mempool.open();
await this.miner.open();
await this.pool.open();
2017-11-16 19:43:07 -08:00
await this.openPlugins();
2016-09-20 14:56:54 -07:00
2017-11-16 19:43:07 -08:00
await this.http.open();
2018-02-18 05:12:44 -08:00
await this.dns.open(5368, '127.0.0.1');
2018-02-19 01:48:17 -08:00
// await this.dns.open(53, '127.0.0.2');
2017-11-16 19:43:07 -08:00
await this.handleOpen();
2017-02-28 14:10:45 -08:00
2017-11-16 19:43:07 -08:00
this.logger.info('Node is loaded.');
}
2017-11-16 19:43:07 -08:00
/**
* Close the node, wait for the database to close.
* @alias FullNode#close
* @returns {Promise}
*/
2017-11-16 19:43:07 -08:00
async close() {
assert(this.opened, 'FullNode is not open.');
this.opened = false;
2017-11-01 12:57:11 -07:00
2017-11-16 19:43:07 -08:00
await this.handlePreclose();
await this.http.close();
2018-02-03 20:48:36 -08:00
await this.dns.close();
2016-09-20 14:56:54 -07:00
2017-11-16 19:43:07 -08:00
await this.closePlugins();
2016-09-23 18:32:49 -07:00
2017-11-16 19:43:07 -08:00
await this.pool.close();
await this.miner.close();
await this.mempool.close();
await this.chain.close();
await this.handleClose();
2017-11-16 19:43:07 -08:00
this.logger.info('Node is closed.');
}
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
/**
* Rescan for any missed transactions.
* @param {Number|Hash} start - Start block.
* @param {Bloom} filter
* @param {Function} iter - Iterator.
* @returns {Promise}
*/
2017-11-16 19:43:07 -08:00
scan(start, filter, iter) {
return this.chain.scan(start, filter, iter);
}
2017-11-16 19:43:07 -08:00
/**
* 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}
*/
2017-11-16 19:43:07 -08:00
async broadcast(item) {
try {
await this.pool.broadcast(item);
} catch (e) {
this.emit('error', e);
}
}
2016-03-29 16:14:39 -07:00
2017-11-16 19:43:07 -08:00
/**
* Add transaction to mempool, broadcast.
* @param {TX} tx
*/
async sendTX(tx) {
let missing;
2017-11-16 19:43:07 -08:00
try {
missing = await this.mempool.addTX(tx);
} catch (err) {
if (err.type === 'VerifyError' && err.score === 0) {
this.error(err);
this.logger.warning('Verification failed for tx: %s.', tx.txid());
this.logger.warning('Attempting to broadcast anyway...');
this.broadcast(tx);
return;
}
throw err;
}
2017-11-16 19:43:07 -08:00
if (missing) {
this.logger.warning('TX was orphaned in mempool: %s.', tx.txid());
2016-09-21 22:58:27 -07:00
this.logger.warning('Attempting to broadcast anyway...');
this.broadcast(tx);
2016-10-02 17:45:45 -07:00
return;
2016-08-26 05:02:08 -07:00
}
2016-04-08 18:03:17 -07:00
2017-11-16 19:43:07 -08:00
// We need to announce by hand if
// we're running in selfish mode.
if (this.pool.options.selfish)
this.pool.broadcast(tx);
}
2017-11-16 19:43:07 -08:00
/**
* Add transaction to mempool, broadcast. Silence errors.
* @param {TX} tx
* @returns {Promise}
*/
2016-03-29 16:14:39 -07:00
2017-11-16 19:43:07 -08:00
async relay(tx) {
try {
await this.sendTX(tx);
} catch (e) {
this.error(e);
}
2017-01-14 19:21:46 -08:00
}
2017-11-16 19:43:07 -08:00
/**
* Connect to the network.
* @returns {Promise}
*/
2016-05-19 11:56:11 -07:00
2017-11-16 19:43:07 -08:00
connect() {
return this.pool.connect();
}
2017-11-16 19:43:07 -08:00
/**
* Disconnect from the network.
* @returns {Promise}
*/
2016-04-03 06:11:30 -07:00
2017-11-16 19:43:07 -08:00
disconnect() {
return this.pool.disconnect();
}
2017-11-16 19:43:07 -08:00
/**
* Start the blockchain sync.
*/
2016-03-22 17:36:58 -07:00
2017-11-16 19:43:07 -08:00
startSync() {
return this.pool.startSync();
}
2017-11-16 19:43:07 -08:00
/**
* Stop syncing the blockchain.
*/
2016-03-22 17:36:58 -07:00
2017-11-16 19:43:07 -08:00
stopSync() {
return this.pool.stopSync();
}
2017-11-16 19:43:07 -08:00
/**
* Retrieve a block from the chain database.
* @param {Hash} hash
* @returns {Promise} - Returns {@link Block}.
*/
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
getBlock(hash) {
return this.chain.getBlock(hash);
}
2017-11-16 19:43:07 -08:00
/**
* Retrieve a coin from the mempool or chain database.
* Takes into account spent coins in the mempool.
* @param {Hash} hash
* @param {Number} index
* @returns {Promise} - Returns {@link Coin}.
*/
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
async getCoin(hash, index) {
const coin = this.mempool.getCoin(hash, index);
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
if (coin)
return coin;
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
if (this.mempool.isSpent(hash, index))
return null;
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
return this.chain.getCoin(hash, index);
}
2017-11-16 19:43:07 -08:00
/**
* Get coins that pertain to an address from the mempool or chain database.
* Takes into account spent coins in the mempool.
* @param {Address} addrs
* @returns {Promise} - Returns {@link Coin}[].
*/
2016-08-15 15:46:37 -07:00
2017-11-16 19:43:07 -08:00
async getCoinsByAddress(addrs) {
const mempool = this.mempool.getCoinsByAddress(addrs);
const chain = await this.chain.getCoinsByAddress(addrs);
const out = [];
2016-03-21 16:29:02 -07:00
2017-11-16 19:43:07 -08:00
for (const coin of chain) {
const spent = this.mempool.isSpent(coin.hash, coin.index);
2017-11-16 19:43:07 -08:00
if (spent)
continue;
2017-11-16 19:43:07 -08:00
out.push(coin);
}
2016-03-21 16:29:02 -07:00
2017-11-16 19:43:07 -08:00
for (const coin of mempool)
out.push(coin);
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
return out;
}
2016-08-26 05:02:08 -07:00
2017-11-16 19:43:07 -08:00
/**
* Retrieve transactions pertaining to an
* address from the mempool or chain database.
* @param {Address} addrs
* @returns {Promise} - Returns {@link TXMeta}[].
*/
async getMetaByAddress(addrs) {
const mempool = this.mempool.getMetaByAddress(addrs);
const chain = await this.chain.getMetaByAddress(addrs);
return chain.concat(mempool);
}
2016-08-26 05:02:08 -07:00
2017-11-16 19:43:07 -08:00
/**
* Retrieve a transaction from the mempool or chain database.
* @param {Hash} hash
* @returns {Promise} - Returns {@link TXMeta}.
*/
2017-11-16 19:43:07 -08:00
async getMeta(hash) {
const meta = this.mempool.getMeta(hash);
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
if (meta)
return meta;
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
return this.chain.getMeta(hash);
}
2016-03-21 16:29:02 -07:00
2017-11-16 19:43:07 -08:00
/**
* Retrieve a spent coin viewpoint from mempool or chain database.
* @param {TXMeta} meta
* @returns {Promise} - Returns {@link CoinView}.
*/
2017-11-16 19:43:07 -08:00
async getMetaView(meta) {
if (meta.height === -1)
return this.mempool.getSpentView(meta.tx);
return this.chain.getSpentView(meta.tx);
}
2017-11-16 19:43:07 -08:00
/**
* Retrieve transactions pertaining to an
* address from the mempool or chain database.
* @param {Address} addrs
* @returns {Promise} - Returns {@link TX}[].
*/
2017-11-16 19:43:07 -08:00
async getTXByAddress(addrs) {
const mtxs = await this.getMetaByAddress(addrs);
const out = [];
2017-11-16 19:43:07 -08:00
for (const mtx of mtxs)
out.push(mtx.tx);
2017-11-16 19:43:07 -08:00
return out;
}
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
/**
* Retrieve a transaction from the mempool or chain database.
* @param {Hash} hash
* @returns {Promise} - Returns {@link TX}.
*/
2017-11-16 19:43:07 -08:00
async getTX(hash) {
const mtx = await this.getMeta(hash);
2017-11-16 19:43:07 -08:00
if (!mtx)
return null;
2017-11-16 19:43:07 -08:00
return mtx.tx;
}
2017-11-16 19:43:07 -08:00
/**
* Test whether the mempool or chain contains a transaction.
* @param {Hash} hash
* @returns {Promise} - Returns Boolean.
*/
2017-11-16 19:43:07 -08:00
async hasTX(hash) {
if (this.mempool.hasEntry(hash))
return true;
2016-03-10 02:40:33 -08:00
2017-11-16 19:43:07 -08:00
return this.chain.hasTX(hash);
}
}
2016-03-10 02:40:33 -08:00
2016-05-15 18:07:06 -07:00
/*
* Expose
*/
module.exports = FullNode;