diff --git a/README.md b/README.md index 2b2d3f31..7db5abf1 100644 --- a/README.md +++ b/README.md @@ -167,9 +167,7 @@ miner.createBlock(function(err, attempt) { ### Connecting to the P2P network ``` js -var bcoin = require('bcoin'); - -bcoin.protocol.network.set('testnet'); +var bcoin = require('bcoin')('testnet'); var chain = new bcoin.chain({ db: 'leveldb' }); var mempool = new bcoin.mempool({ chain: chain, db: 'memory' }); @@ -200,9 +198,7 @@ pool.on('tx', function(tx) { ### Doing an SPV sync ``` js -var bcoin = require('bcoin'); - -bcoin.protocol.network.set('testnet'); +var bcoin = require('bcoin')('testnet'); var chain = new bcoin.chain({ db: 'leveldb', diff --git a/bin/bcoin-cli b/bin/bcoin-cli index 040f4047..050ddeeb 100755 --- a/bin/bcoin-cli +++ b/bin/bcoin-cli @@ -1,18 +1,13 @@ #!/usr/bin/env node -var bcoin = require('bcoin'); +var argv = parseArg(process.argv); + +var bcoin = require('bcoin')(argv.network); var utils = bcoin.utils; var assert = utils.assert; var Client = bcoin.http.client; -var argv = parseArg(process.argv); - -if (argv.network) - bcoin.protocol.network.set(argv.network); - -var client = new Client(argv.url || 'localhost:8080', { - setNetwork: argv.network == null -}); +var client = new Client(argv.url || 'localhost:8080'); function getID() { if (process.env.BCOIN_WALLET_ID) diff --git a/bin/node b/bin/node index f3ce7c3f..0ddd1e39 100755 --- a/bin/node +++ b/bin/node @@ -1,11 +1,10 @@ #!/usr/bin/env node -var bcoin = require('bcoin'); +var bcoin = require('bcoin')({ debug: true }); var utils = bcoin.utils; var assert = utils.assert; var node = bcoin.fullnode({ - debug: true, passphrase: 'node', prune: process.argv.indexOf('--prune') !== -1, useCheckpoints: process.argv.indexOf('--checkpoints') !== -1, @@ -15,7 +14,7 @@ var node = bcoin.fullnode({ }); node.on('error', function(err) { - utils.debug(err.message); + bcoin.debug(err.stack + ''); }); node.open(function(err) { diff --git a/bin/spvnode b/bin/spvnode index 29712c6d..3abfc9e1 100755 --- a/bin/spvnode +++ b/bin/spvnode @@ -1,18 +1,17 @@ #!/usr/bin/env node -var bcoin = require('bcoin'); +var bcoin = require('bcoin')({ debug: true }); var utils = bcoin.utils; var assert = utils.assert; var node = bcoin.spvnode({ - debug: true, passphrase: 'node', preload: process.argv.indexOf('--preload') !== -1, useCheckpoints: process.argv.indexOf('--checkpoints') !== -1 }); node.on('error', function(err) { - utils.debug(err.message); + bcoin.debug(err.message); }); node.open(function(err) { diff --git a/lib/bcoin.js b/lib/bcoin.js index a8b29624..0c6dabad 100644 --- a/lib/bcoin.js +++ b/lib/bcoin.js @@ -1,133 +1,12 @@ /** * bcoin - javascript bitcoin library * Copyright (c) 2014-2015, Fedor Indutny (MIT License). + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = exports; -var utils = require('./bcoin/utils'); -var assert = utils.assert; -var fs; +var Environment = require('./bcoin/env'); -try { - fs = require('f' + 's'); -} catch (e) { - ; -} - -bcoin.isBrowser = - (typeof process !== 'undefined' && process.browser) - || typeof window !== 'undefined'; - -bcoin.prefix = process.env.BCOIN_PREFIX || process.env.HOME + '/.bcoin'; -bcoin.debugLogs = +process.env.BCOIN_DEBUG === 1; -bcoin.debugFile = +process.env.BCOIN_DEBUGFILE !== 0; -bcoin.profile = +process.env.BCOIN_PROFILE === 1; -bcoin.fresh = +process.env.BCOIN_FRESH === 1; -bcoin.useWorkers = +process.env.BCOIN_WORKERS > 0; - -bcoin.ensurePrefix = function ensurePrefix() { - if (bcoin.isBrowser) - return; - - if (bcoin._ensured) - return; - - bcoin._ensured = true; - - if (bcoin.fresh && bcoin.prefix.indexOf('bcoin') !== -1) - bcoin.rimraf(bcoin.prefix); - - try { - fs.statSync(bcoin.prefix); - } catch (e) { - fs.mkdirSync(bcoin.prefix, 0750); - } +module.exports = function BCoin(options) { + return new Environment(options); }; - -bcoin.rimraf = function rimraf(file) { - var cp; - - if (bcoin.isBrowser) - return; - - cp = require('child_' + 'process'); - - assert(typeof file === 'string'); - assert(file !== '/'); - assert(file !== process.env.HOME); - - cp.execFileSync('rm', ['-rf', file], { stdio: 'ignore' }); -}; - -bcoin.debug = function debug() { - var args = Array.prototype.slice.call(arguments); - var msg; - - if (bcoin.debugLogs) { - msg = utils.format(args, true); - process.stdout.write(msg); - } - - if (bcoin.debugFile && !bcoin.isBrowser) { - if (!bcoin._debug) { - bcoin.ensurePrefix(); - bcoin._debug = fs.createWriteStream( - bcoin.prefix + '/debug.log', { flags: 'a' }); - } - msg = utils.format(args, false); - bcoin._debug.write(process.pid + ': ' + msg); - } -}; - -bcoin.utils = utils; -bcoin.utils.debug = bcoin.debug; -bcoin.utils.ensurePrefix = bcoin.ensurePrefix; -bcoin.bn = require('bn.js'); -bcoin.locker = require('./bcoin/locker'); -bcoin.reader = require('./bcoin/reader'); -bcoin.writer = require('./bcoin/writer'); -bcoin.profiler = require('./bcoin/profiler'); -bcoin.ec = require('./bcoin/ec'); -bcoin.lru = require('./bcoin/lru'); -bcoin.protocol = require('./bcoin/protocol'); -bcoin.bloom = require('./bcoin/bloom'); -bcoin.script = require('./bcoin/script'); -bcoin.input = require('./bcoin/input'); -bcoin.output = require('./bcoin/output'); -bcoin.coin = require('./bcoin/coin'); -bcoin.coins = require('./bcoin/coins'); -bcoin.coinview = require('./bcoin/coinview'); -bcoin.tx = require('./bcoin/tx'); -bcoin.mtx = require('./bcoin/mtx'); -bcoin.ldb = require('./bcoin/ldb'); -bcoin.txdb = require('./bcoin/txdb'); -bcoin.abstractblock = require('./bcoin/abstractblock'); -bcoin.compactblock = require('./bcoin/compactblock'); -bcoin.block = require('./bcoin/block'); -bcoin.merkleblock = require('./bcoin/merkleblock'); -bcoin.headers = require('./bcoin/headers'); -bcoin.ramdisk = require('./bcoin/ramdisk'); -bcoin.node = require('./bcoin/node'); -bcoin.spvnode = require('./bcoin/spvnode'); -bcoin.fullnode = require('./bcoin/fullnode'); -bcoin.chainblock = require('./bcoin/chainblock'); -bcoin.chaindb = require('./bcoin/chaindb'); -bcoin.chain = require('./bcoin/chain'); -bcoin.mempool = require('./bcoin/mempool'); -bcoin.keypair = require('./bcoin/keypair'); -bcoin.address = require('./bcoin/address'); -bcoin.walletdb = require('./bcoin/walletdb'); -bcoin.wallet = require('./bcoin/wallet'); -bcoin.peer = require('./bcoin/peer'); -bcoin.pool = require('./bcoin/pool'); -bcoin.hd = require('./bcoin/hd'); -bcoin.miner = require('./bcoin/miner'); -bcoin.http = !bcoin.isBrowser - ? require('./bcoin/ht' + 'tp') - : null; -bcoin.workers = bcoin.useWorkers && !bcoin.isBrowser - ? require('./bcoin/work' + 'ers') - : null; - -bcoin.protocol.network.set(process.env.BCOIN_NETWORK || 'main'); diff --git a/lib/bcoin/abstractblock.js b/lib/bcoin/abstractblock.js index 1b1a0272..6b1fa524 100644 --- a/lib/bcoin/abstractblock.js +++ b/lib/bcoin/abstractblock.js @@ -1,11 +1,13 @@ /** * abstractblock.js - abstract block object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); -var utils = require('./utils'); +module.exports = function(bcoin) { + +var utils = bcoin.utils; var network = bcoin.protocol.network; /** @@ -104,4 +106,5 @@ AbstractBlock.prototype.__defineGetter__('rhash', function() { * Expose */ -module.exports = AbstractBlock; +return AbstractBlock; +}; diff --git a/lib/bcoin/address.js b/lib/bcoin/address.js index 9fa164ad..ce9c5caf 100644 --- a/lib/bcoin/address.js +++ b/lib/bcoin/address.js @@ -1,10 +1,12 @@ /** * address.js - address object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = bcoin.utils; var assert = utils.assert; var network = bcoin.protocol.network; @@ -587,4 +589,5 @@ Address.fromJSON = function fromJSON(json, passphrase) { * Expose */ -module.exports = Address; +return Address; +}; diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index 9e5ea0ee..0efbc38f 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -1,10 +1,12 @@ /** * block.js - block object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var bn = require('bn.js'); var utils = require('./utils'); var assert = utils.assert; @@ -473,4 +475,5 @@ Block.isBlock = function isBlock(obj) { * Expose */ -module.exports = Block; +return Block; +}; diff --git a/lib/bcoin/bloom.js b/lib/bcoin/bloom.js index 594a9211..bce73547 100644 --- a/lib/bcoin/bloom.js +++ b/lib/bcoin/bloom.js @@ -1,6 +1,7 @@ /** * bloom.js - bloom filter for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/bst.js b/lib/bcoin/bst.js index 7e62fa18..301f7262 100644 --- a/lib/bcoin/bst.js +++ b/lib/bcoin/bst.js @@ -1,6 +1,7 @@ /** * bst.js - iterative binary search tree for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index ca9882f2..68d6e672 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -1,12 +1,14 @@ /** * chain.js - blockchain management for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; @@ -66,12 +68,12 @@ Chain.prototype._init = function _init() { if (self.height < 400000) return; - utils.debug('Block %s (%d) added to chain (%s)', + bcoin.debug('Block %s (%d) added to chain (%s)', utils.revHex(entry.hash), entry.height, getHost()); }); this.on('competitor', function(block, entry) { - utils.debug('Heads up: Competing chain at height %d:' + bcoin.debug('Heads up: Competing chain at height %d:' + ' tip-height=%d competitor-height=%d' + ' tip-hash=%s competitor-hash=%s' + ' tip-chainwork=%s competitor-chainwork=%s' @@ -88,17 +90,17 @@ Chain.prototype._init = function _init() { }); this.on('resolved', function(block, entry) { - utils.debug('Orphan %s (%d) was resolved (%s)', + bcoin.debug('Orphan %s (%d) was resolved (%s)', utils.revHex(entry.hash), entry.height, getHost()); }); this.on('checkpoint', function(block, data) { - utils.debug('Hit checkpoint block %s (%d) (%s)', + bcoin.debug('Hit checkpoint block %s (%d) (%s)', utils.revHex(data.checkpoint), data.height, getHost()); }); this.on('fork', function(block, data) { - utils.debug( + bcoin.debug( 'Fork at height %d: expected=%s received=%s checkpoint=%s', data.height, utils.revHex(data.expected), @@ -107,36 +109,36 @@ Chain.prototype._init = function _init() { getHost() ); if (data.checkpoint) - utils.debug('WARNING: Block failed a checkpoint.'); + bcoin.debug('WARNING: Block failed a checkpoint.'); }); this.on('invalid', function(block, data) { - utils.debug( + bcoin.debug( 'Invalid block at height %d: hash=%s (%s)', data.height, utils.revHex(data.hash), getHost() ); if (data.chain) { - utils.debug( + bcoin.debug( 'Peer is sending an invalid continuation chain (%s)', getHost()); } else if (data.seen) { - utils.debug('Peer is sending an invalid chain (%s)', getHost()); + bcoin.debug('Peer is sending an invalid chain (%s)', getHost()); } }); this.on('exists', function(block, data) { - utils.debug('Already have block %s (%s)', + bcoin.debug('Already have block %s (%s)', data.height, getHost()); }); this.on('orphan', function(block, data) { - utils.debug('Handled orphan %s (%s)', utils.revHex(data.hash), getHost()); + bcoin.debug('Handled orphan %s (%s)', utils.revHex(data.hash), getHost()); }); this.on('purge', function(count, size) { - utils.debug('Warning: %d (%dmb) orphans cleared!', count, utils.mb(size)); + bcoin.debug('Warning: %d (%dmb) orphans cleared!', count, utils.mb(size)); }); this.db.on('add entry', function(entry) { @@ -155,7 +157,7 @@ Chain.prototype._init = function _init() { self.emit('remove block', block); }); - utils.debug('Chain is loading.'); + bcoin.debug('Chain is loading.'); self.db.open(function(err) { if (err) @@ -182,7 +184,7 @@ Chain.prototype._init = function _init() { return self.emit('error', err); if (result) - utils.debug('Segwit is active.'); + bcoin.debug('Segwit is active.'); self.loaded = true; self.emit('open'); @@ -231,9 +233,9 @@ Chain.prototype._preload = function _preload(callback) { return callback(); if (network.type !== 'main') - return callback(new Error('Electrum.org only offers `main` headers.')); + return callback(); - utils.debug('Loading %s', url); + bcoin.debug('Loading %s', url); function parseHeader(buf) { var headers = bcoin.protocol.parser.parseBlockHeaders(buf); @@ -362,7 +364,7 @@ Chain.prototype._preload = function _preload(callback) { save(entry); if ((height + 1) % 50000 === 0) - utils.debug('Received %d headers from electrum.org.', height + 1); + bcoin.debug('Received %d headers from electrum.org.', height + 1); lastEntry = entry; height++; @@ -928,7 +930,7 @@ Chain.prototype._setBestChain = function _setBestChain(entry, block, callback) { // A higher fork has arrived. // Time to reorganize the chain. - utils.debug('WARNING: Reorganizing chain.'); + bcoin.debug('WARNING: Reorganizing chain.'); return this._reorganize(entry, block, done); }; @@ -2056,4 +2058,5 @@ Chain.prototype.checkLocks = function checkLocks(tx, flags, entry, callback, for * Expose */ -module.exports = Chain; +return Chain; +}; diff --git a/lib/bcoin/chainblock.js b/lib/bcoin/chainblock.js index bc31b19b..a1422046 100644 --- a/lib/bcoin/chainblock.js +++ b/lib/bcoin/chainblock.js @@ -1,10 +1,12 @@ /** * chainblock.js - chainblock object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; @@ -311,4 +313,5 @@ ChainBlock.isChainBlock = function isChainBlock(obj) { * Expose */ -module.exports = ChainBlock; +return ChainBlock; +}; diff --git a/lib/bcoin/chaindb.js b/lib/bcoin/chaindb.js index d151b0db..ef3b6243 100644 --- a/lib/bcoin/chaindb.js +++ b/lib/bcoin/chaindb.js @@ -1,12 +1,14 @@ /** * chaindb.js - blockchain data management for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var network = bcoin.protocol.network; var utils = require('./utils'); var assert = utils.assert; @@ -68,7 +70,7 @@ ChainDB.prototype._init = function _init() { writeBufferSize: 8 << 20 }); - utils.debug('Starting chain load.'); + bcoin.debug('Starting chain load.'); this.db.open(function(err) { if (err) @@ -78,7 +80,7 @@ ChainDB.prototype._init = function _init() { if (err) return self.emit('error', err); - utils.debug('Chain successfully loaded.'); + bcoin.debug('Chain successfully loaded.'); self.loaded = true; self.emit('open'); @@ -1487,4 +1489,5 @@ NullCache.prototype.reset = function reset() {}; * Expose */ -module.exports = ChainDB; +return ChainDB; +}; diff --git a/lib/bcoin/coin.js b/lib/bcoin/coin.js index b4453a0c..0a269328 100644 --- a/lib/bcoin/coin.js +++ b/lib/bcoin/coin.js @@ -1,11 +1,13 @@ /** * coin.js - coin object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var bn = require('bn.js'); -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = utils.assert; var network = bcoin.protocol.network; @@ -205,4 +207,5 @@ Coin.isCoin = function isCoin(obj) { * Expose */ -module.exports = Coin; +return Coin; +}; diff --git a/lib/bcoin/coins.js b/lib/bcoin/coins.js index 06cd6617..12f2052c 100644 --- a/lib/bcoin/coins.js +++ b/lib/bcoin/coins.js @@ -1,10 +1,12 @@ /** * coins.js - coins object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -194,4 +196,5 @@ Coins.fromRaw = function fromRaw(buf, hash) { * Expose */ -module.exports = Coins; +return Coins; +}; diff --git a/lib/bcoin/coinview.js b/lib/bcoin/coinview.js index 848645cd..c08e8fb2 100644 --- a/lib/bcoin/coinview.js +++ b/lib/bcoin/coinview.js @@ -1,10 +1,12 @@ /** * coinview.js - coinview object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -101,4 +103,5 @@ CoinView.prototype.toArray = function toArray() { * Expose */ -module.exports = CoinView; +return CoinView; +}; diff --git a/lib/bcoin/compactblock.js b/lib/bcoin/compactblock.js index 0a46857a..aebd6559 100644 --- a/lib/bcoin/compactblock.js +++ b/lib/bcoin/compactblock.js @@ -1,10 +1,12 @@ /** * compactblock.js - compact block object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var bn = require('bn.js'); var utils = require('./utils'); var assert = utils.assert; @@ -48,8 +50,15 @@ CompactBlock.prototype.toBlock = function toBlock() { return block; }; +CompactBlock.isCompactBlock = function isCompactBlock(block) { + return block + && block.type === 'compactblock' + && typeof block.toBlock === 'function'; +}; + /** * Expose */ -module.exports = CompactBlock; +return CompactBlock; +}; diff --git a/lib/bcoin/ec.js b/lib/bcoin/ec.js index f9b9b6c7..6bc8e56a 100644 --- a/lib/bcoin/ec.js +++ b/lib/bcoin/ec.js @@ -1,17 +1,17 @@ /** * ec.js - ecdsa wrapper for secp256k1 and elliptic * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); var elliptic = require('elliptic'); var utils = require('./utils'); var assert = utils.assert; var ec = exports; var crypto, secp256k1; -if (!bcoin.isBrowser) +if (!utils.isBrowser) crypto = require('cry' + 'pto'); try { @@ -91,7 +91,7 @@ ec.verify = function verify(msg, sig, key, historical) { return ec.elliptic.verify(msg, sig, key); } catch (e) { // if (!ec.publicKeyVerify(key)) - // utils.debug('Public key is invalid.'); + // bcoin.debug('Public key is invalid.'); return false; } }; diff --git a/lib/bcoin/env.js b/lib/bcoin/env.js new file mode 100644 index 00000000..ca8865c2 --- /dev/null +++ b/lib/bcoin/env.js @@ -0,0 +1,202 @@ +/** + * env.js - environment for bcoin + * Copyright (c) 2014-2015, Fedor Indutny (MIT License). + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). + * https://github.com/indutny/bcoin + */ + +var utils = require('./utils'); +var assert = utils.assert; +var fs; + +try { + fs = require('f' + 's'); +} catch (e) { + ; +} + +/** + * Environment + */ + +function Environment(options) { + if (!(this instanceof Environment)) + return new Environment(options); + + if (!options) + options = {}; + + if (typeof options === 'string') + options = { network: options }; + + this.options = options; + + this.isBrowser = + (typeof process !== 'undefined' && process.browser) + || typeof window !== 'undefined'; + + this.prefix = process.env.BCOIN_PREFIX + || options.prefix + || process.env.HOME + '/.bcoin'; + + this.debugLogs = options.debug; + + if (process.env.BCOIN_DEBUG != null) + this.debugLogs = +process.env.BCOIN_DEBUG === 1; + + this.debugFile = options.debugFile; + + if (options.debugFile == null) + this.debugFile = true; + + if (process.env.BCOIN_DEBUGFILE != null) { + if (process.env.BCOIN_DEBUGFILE === '0' + || process.env.BCOIN_DEBUGFILE === '1') { + this.debugFile = +process.env.BCOIN_DEBUGFILE !== 0; + } else { + this.debugFile = process.env.BCOIN_DEBUGFILE; + } + } + + if (this.debugFile && typeof this.debugFile !== 'string') + this.debugFile = this.prefix + '/debug.log' + + this.profile = options.profile; + + if (process.env.BCOIN_PROFILE != null) + this.profile = +process.env.BCOIN_PROFILE === 1; + + this.fresh = options.fresh; + + if (process.env.BCOIN_FRESH != null) + this.fresh = +process.env.BCOIN_FRESH === 1; + + this.useWorkers = options.useWorkers; + + if (process.env.BCOIN_USE_WORKERS != null) + this.useWorkers = +process.env.BCOIN_USE_WORKERS === 1; + + this.useWorkers = options.maxWorkers; + + if (process.env.BCOIN_MAX_WORKERS != null) + this.maxWorkers = +process.env.BCOIN_MAX_WORKERS; + + this.workerTimeout = options.workerTimeout; + + if (process.env.BCOIN_WORKER_TIMEOUT != null) + this.workerTimeout = +process.env.BCOIN_WORKER_TIMEOUT; + + this.networkType = process.env.BCOIN_NETWORK + || options.network + || 'main'; + + this.bn = require('bn.js'); + this.utils = require('./utils'); + this.locker = require('./locker'); + this.reader = require('./reader'); + this.writer = require('./writer'); + this.ec = require('./ec'); + this.lru = require('./lru'); + this.bloom = require('./bloom'); + this.bst = require('./bst'); + + this.protocol = require('./protocol')(this); + this.profiler = require('./profiler')(this); + this.ldb = require('./ldb')(this); + this.script = require('./script')(this); + this.stack = this.script.stack; + this.witness = this.script.witness; + this.input = require('./input')(this); + this.output = require('./output')(this); + this.coin = require('./coin')(this); + this.coins = require('./coins')(this); + this.coinview = require('./coinview')(this); + this.tx = require('./tx')(this); + this.mtx = require('./mtx')(this); + this.txdb = require('./txdb')(this); + this.abstractblock = require('./abstractblock')(this); + this.compactblock = require('./compactblock')(this); + this.block = require('./block')(this); + this.merkleblock = require('./merkleblock')(this); + this.headers = require('./headers')(this); + this.node = require('./node')(this); + this.spvnode = require('./spvnode')(this); + this.fullnode = require('./fullnode')(this); + this.chainblock = require('./chainblock')(this); + this.chaindb = require('./chaindb')(this); + this.chain = require('./chain')(this); + this.mempool = require('./mempool')(this); + this.keypair = require('./keypair')(this); + this.address = require('./address')(this); + this.walletdb = require('./walletdb')(this); + this.provider = this.walletdb.provider; + this.wallet = require('./wallet')(this); + this.peer = require('./peer')(this); + this.pool = require('./pool')(this); + this.hd = require('./hd')(this); + this.miner = require('./miner')(this); + this.minerblock = this.miner.minerblock; + this.http = require('./http')(this); + this.workers = this.useWorkers && !this.isBrowser + ? require('./work' + 'ers')(this) + : null; +} + +Environment.prototype.ensurePrefix = function ensurePrefix() { + if (this.isBrowser) + return; + + if (this._ensured) + return; + + this._ensured = true; + + if (this.fresh && this.prefix.indexOf('bcoin') !== -1) + this.rimraf(this.prefix); + + try { + fs.statSync(this.prefix); + } catch (e) { + fs.mkdirSync(this.prefix, 0750); + } +}; + +Environment.prototype.rimraf = function rimraf(file) { + var cp; + + if (this.isBrowser) + return; + + cp = require('child_' + 'process'); + + assert(typeof file === 'string'); + assert(file !== '/'); + assert(file !== process.env.HOME); + + cp.execFileSync('rm', ['-rf', file], { stdio: 'ignore' }); +}; + +Environment.prototype.debug = function debug() { + var args = Array.prototype.slice.call(arguments); + var msg; + + if (this.debugLogs) { + msg = utils.format(args, true); + process.stderr.write(msg); + } + + if (this.debugFile && !this.isBrowser) { + if (!this._debug) { + this.ensurePrefix(); + this._debug = fs.createWriteStream(this.debugFile, { flags: 'a' }); + } + msg = utils.format(args, false); + this._debug.write(process.pid + ': ' + msg); + } +}; + +/** + * Expose + */ + +module.exports = Environment; diff --git a/lib/bcoin/fullnode.js b/lib/bcoin/fullnode.js index 1cb02d53..bf5baa23 100644 --- a/lib/bcoin/fullnode.js +++ b/lib/bcoin/fullnode.js @@ -1,10 +1,12 @@ /** * fullnode.js - full node for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); var assert = utils.assert; @@ -155,7 +157,7 @@ Fullnode.prototype._init = function _init() { self.loaded = true; self.emit('open'); - utils.debug('Node is loaded.'); + bcoin.debug('Node is loaded.'); } options = utils.merge({ @@ -245,7 +247,7 @@ Fullnode.prototype.createWallet = function createWallet(options, callback) { assert(wallet); - utils.debug('Loaded wallet with id=%s address=%s', + bcoin.debug('Loaded wallet with id=%s address=%s', wallet.id, wallet.getAddress()); self.pool.addWallet(wallet, function(err) { @@ -413,4 +415,5 @@ Fullnode.prototype.getConfidence = function getConfidence(tx, callback) { * Expose */ -module.exports = Fullnode; +return Fullnode; +}; diff --git a/lib/bcoin/hd.js b/lib/bcoin/hd.js index 3f9cecb2..62377aa6 100644 --- a/lib/bcoin/hd.js +++ b/lib/bcoin/hd.js @@ -1,6 +1,7 @@ /** * hd.js - hd seeds and keys (BIP32, BIP39) for bcoin. * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki * https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki @@ -46,18 +47,19 @@ * THE SOFTWARE. */ +module.exports = function(bcoin) { + /** * Modules */ -var bcoin = require('../bcoin'); var bn = require('bn.js'); var utils = require('./utils'); var ec = require('./ec'); var assert = utils.assert; var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; -var KeyPair = require('./keypair'); +var KeyPair = bcoin.keypair; var LRU = require('./lru'); var BufferWriter = require('./writer'); var BufferReader = require('./reader'); @@ -883,7 +885,7 @@ HDPrivateKey.prototype.toSecret = function toSecret() { * Expose */ -exports = HD; +var exports = HD; exports.seed = HDSeed; exports.priv = HDPrivateKey; @@ -892,4 +894,5 @@ exports.privateKey = HDPrivateKey; exports.publicKey = HDPublicKey; exports.fromJSON = HDPrivateKey.fromJSON; -module.exports = HD; +return exports; +}; diff --git a/lib/bcoin/headers.js b/lib/bcoin/headers.js index 3548a3c3..e6d0ffce 100644 --- a/lib/bcoin/headers.js +++ b/lib/bcoin/headers.js @@ -1,10 +1,12 @@ /** * headers.js - headers object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); /** @@ -85,4 +87,5 @@ Headers.isHeaders = function isHeaders(obj) { * Expose */ -module.exports = Headers; +return Headers; +}; diff --git a/lib/bcoin/http/client.js b/lib/bcoin/http/client.js index 26581d1b..c042b5d8 100644 --- a/lib/bcoin/http/client.js +++ b/lib/bcoin/http/client.js @@ -1,11 +1,13 @@ /** * client.js - http client for wallets * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../../bcoin'); var network = bcoin.protocol.network; var utils = require('../utils'); var request = require('./request'); @@ -53,10 +55,9 @@ Client.prototype._init = function _init() { this.socket.on('open', function() { self.socket.on('version', function(info) { - utils.debug('Connected to bcoin server: %s (%s)', + bcoin.debug('Connected to bcoin server: %s (%s)', info.version, info.network); - if (self.options.setNetwork) - network.set(info.network); + assert(info.network === network.type); }); self.socket.on('tx', function(tx, map) { @@ -176,11 +177,8 @@ Client.prototype._request = function _request(method, endpoint, json, callback) if (err) return callback(err); - if (self.options.setNetwork) { - networkType = res.headers['x-bcoin-network']; - if (networkType && network.type !== networkType) - network.set(networkType); - } + networkType = res.headers['x-bcoin-network']; + assert(networkType === network.type); if (res.statusCode === 404) return callback(); @@ -661,4 +659,5 @@ Client.prototype.getInfo = function getInfo(callback) { * Expose */ -module.exports = Client; +return Client; +}; diff --git a/lib/bcoin/http/http.js b/lib/bcoin/http/http.js index 3eae7ef8..5e987c5d 100644 --- a/lib/bcoin/http/http.js +++ b/lib/bcoin/http/http.js @@ -1,6 +1,7 @@ /** * http.js - http server for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ @@ -99,9 +100,9 @@ HTTPServer.prototype._initRouter = function _initRouter() { req.destroy(); req.socket.destroy(); } catch (e) { - utils.debug(e.stack + ''); + self.emit('error', e); } - utils.debug(err.stack + ''); + self.emit('error', err); } } @@ -111,8 +112,7 @@ HTTPServer.prototype._initRouter = function _initRouter() { done(e); } - utils.debug('Request from %s path=%s', - req.socket.remoteAddress, req.pathname); + self.emit('request', req, res); parseBody(req, function(err) { var method, routes, i; @@ -259,21 +259,23 @@ HTTPServer.prototype.del = function del(path, callback) { this.routes.del.push({ path: path, callback: callback }); }; +HTTPServer.prototype.address = function address() { + return this.server.address(); +}; + HTTPServer.prototype.listen = function listen(port, host, callback) { var self = this; this.server.listen(port, host, function(err) { - var address; + if (!callback) { + if (err) + throw err; + return; + } if (err) - throw err; + return callback(err); - address = self.server.address(); - - utils.debug('Listening - host=%s port=%d', - address.address, address.port); - - if (callback) - callback(); + return callback(null, self.address()); }); }; @@ -299,7 +301,7 @@ function send(res, code, msg) { res.write(msg); res.end(); } catch (e) { - utils.debug('Write failed: %s', e.message); + ; } } diff --git a/lib/bcoin/http/index.js b/lib/bcoin/http/index.js index 0f2df51a..9acbcd84 100644 --- a/lib/bcoin/http/index.js +++ b/lib/bcoin/http/index.js @@ -1,5 +1,21 @@ -exports.http = require('./http'); -exports.server = require('./server'); -exports.client = require('./client'); -exports.request = require('./request'); -exports.provider = require('./provider'); +/** + * http/index.js - http for bcoin + * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). + * https://github.com/indutny/bcoin + */ + +module.exports = function(bcoin) { + bcoin.http = {}; + + bcoin.http.request = require('./request'); + bcoin.http.client = require('./client')(bcoin); + bcoin.http.provider = require('./provider')(bcoin); + + if (!bcoin.isBrowser) { + bcoin.http.http = require('./ht' + 'tp'); + bcoin.http.server = require('./ser' + 'ver')(bcoin); + } + + return bcoin.http; +}; diff --git a/lib/bcoin/http/provider.js b/lib/bcoin/http/provider.js index 0cb792ac..33df4cad 100644 --- a/lib/bcoin/http/provider.js +++ b/lib/bcoin/http/provider.js @@ -1,14 +1,17 @@ /** * provider.js - http provider for wallets * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; var utils = require('../utils'); var assert = utils.assert; -var Client = require('./client'); +var Client = bcoin.http.client; /** * Provider @@ -133,4 +136,5 @@ Provider.prototype.zap = function zap(now, age, callback) { * Expose */ -module.exports = Provider; +return Provider; +}; diff --git a/lib/bcoin/http/request.js b/lib/bcoin/http/request.js index 5a1cb825..fbc70aee 100644 --- a/lib/bcoin/http/request.js +++ b/lib/bcoin/http/request.js @@ -1,6 +1,7 @@ /** * request.js - http request for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/http/server.js b/lib/bcoin/http/server.js index f3cbb278..c540445a 100644 --- a/lib/bcoin/http/server.js +++ b/lib/bcoin/http/server.js @@ -1,14 +1,16 @@ /** * server.js - http server for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../../bcoin'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; -var HTTPServer = require('./http'); +var HTTPServer = bcoin.http.http; var utils = require('../utils'); var assert = utils.assert; @@ -40,6 +42,11 @@ utils.inherits(NodeServer, EventEmitter); NodeServer.prototype._init = function _init() { var self = this; + this.server.on('request', function(req, res) { + bcoin.debug('Request from %s path=%s', + req.socket.remoteAddress, req.pathname); + }); + this.use(function(req, res, next, send) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Credentials', 'true'); @@ -624,13 +631,16 @@ NodeServer.prototype.del = function del(path, callback) { NodeServer.prototype.listen = function listen(port, host, callback) { var self = this; - return this.server.listen(port, host, function(err) { + return this.server.listen(port, host, function(err, address) { if (err) { if (callback) return callback(err); return self.emit('error', err); } + bcoin.debug('Listening - host=%s port=%d', + address.address, address.port); + self.loaded = true; self.emit('open'); @@ -643,4 +653,5 @@ NodeServer.prototype.listen = function listen(port, host, callback) { * Expose */ -module.exports = NodeServer; +return NodeServer; +}; diff --git a/lib/bcoin/input.js b/lib/bcoin/input.js index 0366924b..0b5f486c 100644 --- a/lib/bcoin/input.js +++ b/lib/bcoin/input.js @@ -1,10 +1,12 @@ /** * input.js - input object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -283,4 +285,5 @@ Input.isInput = function isInput(obj) { * Expose */ -module.exports = Input; +return Input; +}; diff --git a/lib/bcoin/keypair.js b/lib/bcoin/keypair.js index 03ec97e8..400e68b6 100644 --- a/lib/bcoin/keypair.js +++ b/lib/bcoin/keypair.js @@ -1,10 +1,12 @@ /** * keypair.js - keypair object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); var assert = utils.assert; var network = bcoin.protocol.network; @@ -183,4 +185,5 @@ KeyPair.fromJSON = function fromJSON(json, passphrase) { * Expose */ -module.exports = KeyPair; +return KeyPair; +}; diff --git a/lib/bcoin/ldb.js b/lib/bcoin/ldb.js index b90578a3..236a7470 100644 --- a/lib/bcoin/ldb.js +++ b/lib/bcoin/ldb.js @@ -1,14 +1,17 @@ /** * ldb.js - global ldb tracker * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +var db = {}; + +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var utils = bcoin.utils; var network = bcoin.protocol.network; -var db = {}; /** * LDB @@ -206,9 +209,10 @@ LowlevelUp.prototype.approximateSize = function approximateSize(start, end, call * Expose */ -exports = ldb; +var exports = ldb; exports.LowlevelUp = LowlevelUp; exports.destroy = destroy; exports.repair = repair; -module.exports = exports; +return exports; +}; diff --git a/lib/bcoin/locker.js b/lib/bcoin/locker.js index 3f90875f..5a237143 100644 --- a/lib/bcoin/locker.js +++ b/lib/bcoin/locker.js @@ -1,6 +1,7 @@ /** * locker.js - lock and queue for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ @@ -103,7 +104,7 @@ Locker.prototype.purgePending = function purgePending() { assert(this.add); - utils.debug('Warning: %dmb of pending objects. Purging.', + bcoin.debug('Warning: %dmb of pending objects. Purging.', utils.mb(this.pendingSize)); this.pending.forEach(function(obj) { diff --git a/lib/bcoin/lru.js b/lib/bcoin/lru.js index f94bbf9c..eb052b54 100644 --- a/lib/bcoin/lru.js +++ b/lib/bcoin/lru.js @@ -1,6 +1,7 @@ /** * lru.js - LRU cache for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/mempool.js b/lib/bcoin/mempool.js index 193c4b7f..6019292f 100644 --- a/lib/bcoin/mempool.js +++ b/lib/bcoin/mempool.js @@ -1,12 +1,14 @@ /** * mempool.js - mempool for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; @@ -427,7 +429,7 @@ Mempool.prototype.addTX = function addTX(tx, callback, force) { 'mempool full', 0)); } - utils.debug('Added orphan %s to mempool.', tx.rhash); + bcoin.debug('Added orphan %s to mempool.', tx.rhash); return self.storeOrphan(tx, callback); } @@ -465,7 +467,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) { self.emit('tx', tx); self.emit('add tx', tx); - utils.debug('Added tx %s to the mempool.', tx.rhash); + bcoin.debug('Added tx %s to the mempool.', tx.rhash); self.resolveOrphans(tx, function(err, resolved) { if (err) @@ -475,7 +477,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) { self.verify(tx, function(err) { if (err) { if (err.type === 'VerifyError') { - utils.debug('Could not resolved orphan %s: %s.', + bcoin.debug('Could not resolved orphan %s: %s.', tx.rhash, err.message); return next(); @@ -488,7 +490,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) { self.emit('error', err); return next(); } - utils.debug('Resolved orphan %s in mempool.', tx.rhash); + bcoin.debug('Resolved orphan %s in mempool.', tx.rhash); next(); }); }); @@ -1221,4 +1223,5 @@ Mempool.prototype._removeUnchecked = function removeUnchecked(hash, callback, fo * Expose */ -module.exports = Mempool; +return Mempool; +}; diff --git a/lib/bcoin/merkleblock.js b/lib/bcoin/merkleblock.js index 569514b1..8539ee16 100644 --- a/lib/bcoin/merkleblock.js +++ b/lib/bcoin/merkleblock.js @@ -1,10 +1,12 @@ /** * merkleblock.js - merkleblock object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); /** @@ -280,4 +282,5 @@ MerkleBlock.fromBlock = function fromBlock(block, bloom) { * Expose */ -module.exports = MerkleBlock; +return MerkleBlock; +}; diff --git a/lib/bcoin/miner.js b/lib/bcoin/miner.js index 5b6aa2fe..7cb863df 100644 --- a/lib/bcoin/miner.js +++ b/lib/bcoin/miner.js @@ -1,10 +1,12 @@ /** * miner.js - inefficient miner for bcoin (because we can) * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -86,16 +88,16 @@ Miner.prototype._init = function _init() { }); this.on('block', function(block) { - utils.debug( + bcoin.debug( 'Found block: %d (%s)', block.height, block.hash('hex')); // Emit the block hex as a failsafe (in case we can't send it) - utils.debug('Raw: %s', utils.toHex(block.render())); + bcoin.debug('Raw: %s', utils.toHex(block.render())); }); this.on('status', function(stat) { - utils.debug( + bcoin.debug( 'hashrate=%dkhs hashes=%d target=%d height=%d best=%s', stat.hashrate / 1000 | 0, stat.hashes, @@ -144,7 +146,7 @@ Miner.prototype.start = function start() { self.chain.add(block, function(err) { if (err) { if (err.type === 'VerifyError') - utils.debug('%s could not be added to chain.', block.rhash); + bcoin.debug('%s could not be added to chain.', block.rhash); self.emit('error', err); return self.start(); } @@ -504,6 +506,7 @@ function rcmp(a, b) { * Expose */ -exports = Miner; +var exports = Miner; exports.minerblock = MinerBlock; -module.exports = exports; +return exports; +}; diff --git a/lib/bcoin/mtx.js b/lib/bcoin/mtx.js index e4035d79..98f90986 100644 --- a/lib/bcoin/mtx.js +++ b/lib/bcoin/mtx.js @@ -1,12 +1,13 @@ /** * mtx.js - mutable transaction object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bn = require('bn.js'); +module.exports = function(bcoin) { -var bcoin = require('../bcoin'); +var bn = require('bn.js'); var utils = require('./utils'); var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -1123,4 +1124,5 @@ MTX.isMTX = function isMTX(obj) { * Expose */ -module.exports = MTX; +return MTX; +}; diff --git a/lib/bcoin/node.js b/lib/bcoin/node.js index 9cdf85e4..beee86c6 100644 --- a/lib/bcoin/node.js +++ b/lib/bcoin/node.js @@ -1,11 +1,13 @@ /** * node.js - node object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var network = bcoin.protocol.network; var utils = require('./utils'); @@ -24,15 +26,6 @@ function Node(options) { this.options = options; - if (this.options.debug != null) - bcoin.debugLogs = this.options.debug; - - if (this.options.debugFile != null) - bcoin.debugFile = this.options.debugFile; - - if (this.options.network) - network.set(this.options.network); - this.network = network; this.mempool = null; this.pool = null; @@ -47,4 +40,5 @@ utils.inherits(Node, EventEmitter); * Expose */ -module.exports = Node; +return Node; +}; diff --git a/lib/bcoin/output.js b/lib/bcoin/output.js index 66349290..661869c5 100644 --- a/lib/bcoin/output.js +++ b/lib/bcoin/output.js @@ -1,11 +1,13 @@ /** * output.js - output object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var bn = require('bn.js'); -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = utils.assert; @@ -148,4 +150,5 @@ Output.isOutput = function isOutput(obj) { * Expose */ -module.exports = Output; +return Output; +}; diff --git a/lib/bcoin/peer.js b/lib/bcoin/peer.js index 505f67ac..023975cf 100644 --- a/lib/bcoin/peer.js +++ b/lib/bcoin/peer.js @@ -1,12 +1,14 @@ /** * peer.js - peer object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var bn = require('bn.js'); var utils = require('./utils'); var assert = utils.assert; @@ -142,7 +144,7 @@ Peer.prototype._init = function init() { }); this.parser.on('error', function(err) { - utils.debug(err.stack + ''); + bcoin.debug(err.stack + ''); self.sendReject(null, 'malformed', 'error parsing message', 100); self._error(err); // Something is wrong here. @@ -211,12 +213,12 @@ Peer.prototype.createSocket = function createSocket(port, host) { socket = net.connect(port, host); } - utils.debug( + bcoin.debug( 'Connecting to %s:%d (priority=%s)', host, port, this.priority); socket.on('connect', function() { - utils.debug( + bcoin.debug( 'Connected to %s:%d (priority=%s)', host, port, self.priority); }); @@ -512,7 +514,7 @@ Peer.prototype._onPacket = function onPacket(packet) { this._emit(cmd, payload); break; default: - utils.debug('Unknown packet: %s', cmd); + bcoin.debug('Unknown packet: %s', cmd); this._emit(cmd, payload); break; } @@ -555,7 +557,7 @@ Peer.prototype._handleUTXOs = function _handleUTXOs(payload) { payload.coins = payload.coins(function(coin) { return new bcoin.coin(coin); }); - utils.debug('Received %d utxos from %s.', payload.coins.length, this.host); + bcoin.debug('Received %d utxos from %s.', payload.coins.length, this.host); this._emit('utxos', payload); }; @@ -894,7 +896,7 @@ Peer.prototype._handleMempool = function _handleMempool() { for (i = 0; i < hashes.length; i++) items.push({ type: constants.inv.tx, hash: hashes[i] }); - utils.debug('Sending mempool snapshot to %s.', self.host); + bcoin.debug('Sending mempool snapshot to %s.', self.host); self._write(self.framer.inv(items)); }); @@ -923,13 +925,13 @@ Peer.prototype._handleGetData = function handleGetData(items) { } if ((item.type & ~constants.invWitnessMask) !== entry.type) { - utils.debug( + bcoin.debug( 'Peer %s requested an existing item with the wrong type.', this.host); continue; } - utils.debug( + bcoin.debug( 'Peer %s requested %s:%s as a %s packet.', this.host, entry.packetType, @@ -1064,7 +1066,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { if (err) self.emit('error', err); - utils.debug( + bcoin.debug( 'Served %d items to %s with getdata (notfound=%d).', items.length - notfound.length, self.host, @@ -1104,7 +1106,7 @@ Peer.prototype._handleAddr = function handleAddr(addrs) { }); } - utils.debug( + bcoin.debug( 'Recieved %d peers (seeds=%d, peers=%d).', addrs.length, this.pool.seeds.length, @@ -1217,9 +1219,9 @@ Peer.prototype._handleAlert = function handleAlert(details) { var signature = details.signature; if (!bcoin.ec.verify(hash, signature, network.alertKey)) { - utils.debug('Peer %s sent a phony alert packet.', this.host); + bcoin.debug('Peer %s sent a phony alert packet.', this.host); // Let's look at it because why not? - utils.debug(details); + bcoin.debug(details); this.setMisbehavior(100); return; } @@ -1228,11 +1230,11 @@ Peer.prototype._handleAlert = function handleAlert(details) { }; Peer.prototype.getHeaders = function getHeaders(locator, stop) { - utils.debug( + bcoin.debug( 'Requesting headers packet from %s with getheaders', this.host); - utils.debug('Height: %s, Hash: %s, Stop: %s', + bcoin.debug('Height: %s, Hash: %s, Stop: %s', locator && locator.length ? this.chain._getCachedHeight(locator[0]) : null, locator && locator.length ? utils.revHex(locator[0]) : 0, stop ? utils.revHex(stop) : 0); @@ -1241,11 +1243,11 @@ Peer.prototype.getHeaders = function getHeaders(locator, stop) { }; Peer.prototype.getBlocks = function getBlocks(locator, stop) { - utils.debug( + bcoin.debug( 'Requesting inv packet from %s with getblocks', this.host); - utils.debug('Height: %s, Hash: %s, Stop: %s', + bcoin.debug('Height: %s, Hash: %s, Stop: %s', locator && locator.length ? this.chain._getCachedHeight(locator[0]) : null, locator && locator.length ? utils.revHex(locator[0]) : 0, stop ? utils.revHex(stop) : 0); @@ -1254,7 +1256,7 @@ Peer.prototype.getBlocks = function getBlocks(locator, stop) { }; Peer.prototype.getMempool = function getMempool() { - utils.debug( + bcoin.debug( 'Requesting inv packet from %s with mempool', this.host); @@ -1262,7 +1264,7 @@ Peer.prototype.getMempool = function getMempool() { }; Peer.prototype.reject = function reject(details) { - utils.debug( + bcoin.debug( 'Sending reject packet to %s', this.host); @@ -1285,4 +1287,5 @@ Peer.prototype.sendReject = function sendReject(obj, code, reason, score) { * Expose */ -module.exports = Peer; +return Peer; +}; diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index c41d6d22..05ac2110 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -1,12 +1,14 @@ /** * pool.js - peer management for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = utils.assert; var network = bcoin.protocol.network; @@ -228,7 +230,7 @@ Pool.prototype._init = function _init() { self.getMempool(); self.synced = true; self.emit('full'); - utils.debug('Chain is fully synced (height=%d).', self.chain.height); + bcoin.debug('Chain is fully synced (height=%d).', self.chain.height); }); (this.options.wallets || []).forEach(function(wallet) { @@ -264,19 +266,19 @@ Pool.prototype.resolveOrphan = function resolveOrphan(peer, top, orphan, callbac // Was probably resolved. if (!orphan) { - utils.debug('Orphan root was already resolved.'); + bcoin.debug('Orphan root was already resolved.'); return callback(); } // If we're already processing the block // that would resolve this, ignore. // if (self.request.map[orphan.soil]) { - // utils.debug('Already requested orphan "soil".'); + // bcoin.debug('Already requested orphan "soil".'); // return callback(); // } // if (self.chain.hasPending(orphan.soil)) { - // utils.debug('Already processing orphan "soil".'); + // bcoin.debug('Already processing orphan "soil".'); // return callback(); // } @@ -323,7 +325,7 @@ Pool.prototype.startServer = function startServer(callback) { this.server.on('listening', function() { var data = self.server.address(); - utils.debug( + bcoin.debug( 'Bitcoin server listening on %s (port=%d)', data.address, data.port); }); @@ -359,7 +361,7 @@ Pool.prototype._startTimer = function _startTimer() { if (self.peers.load) { self.peers.load.destroy(); - utils.debug('Timer ran out. Finding new loader peer.'); + bcoin.debug('Timer ran out. Finding new loader peer.'); } } @@ -387,7 +389,7 @@ Pool.prototype._startInterval = function _startInterval() { if (self.chain.isFull()) return; - utils.debug('Stall recovery: loading again.'); + bcoin.debug('Stall recovery: loading again.'); // self._load(); } @@ -422,7 +424,7 @@ Pool.prototype._addLoader = function _addLoader() { assert(peer); - utils.debug('Added loader peer: %s', peer.host); + bcoin.debug('Added loader peer: %s', peer.host); this.peers.load = peer; this.peers.all.push(peer); @@ -553,7 +555,7 @@ Pool.prototype._handleHeaders = function _handleHeaders(headers, peer, callback) if (headers.length === 0) return callback(); - utils.debug( + bcoin.debug( 'Recieved %s headers from %s', headers.length, peer.host); @@ -611,7 +613,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer, callback) { if (hashes.length === 0) return callback(); - utils.debug( + bcoin.debug( 'Recieved %s block hashes from %s', hashes.length, peer.host); @@ -636,7 +638,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer, callback) { // Resolve orphan chain. if (self.chain.hasOrphan(hash)) { - utils.debug('Peer sent a hash that is already a known orphan.'); + bcoin.debug('Peer sent a hash that is already a known orphan.'); self.resolveOrphan(peer, null, hash, next); return; } @@ -712,7 +714,7 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer, callback) { // Someone is sending us blocks without // us requesting them. if (!requested) { - utils.debug( + bcoin.debug( 'Recieved unrequested block: %s (%s)', block.rhash, peer.host); return callback(); @@ -745,7 +747,7 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer, callback) { self.emit('chain-progress', self.chain.getProgress(), peer); if (self.chain.total % 20 === 0) { - utils.debug( + bcoin.debug( 'Status: tip=%s ts=%s height=%d blocks=%d orphans=%d active=%d' + ' queue=%d target=%s peers=%d pending=%d highest=%d jobs=%d', block.rhash, @@ -815,7 +817,7 @@ Pool.prototype._createPeer = function _createPeer(options) { ? utils.revHex(utils.toHex(payload.data)) : null; - utils.debug( + bcoin.debug( 'Reject (%s): msg=%s ccode=%s reason=%s data=%s', peer.host, payload.message, @@ -827,8 +829,8 @@ Pool.prototype._createPeer = function _createPeer(options) { }); peer.on('alert', function(payload) { - utils.debug('Received alert from: %s', peer.host); - utils.debug(payload); + bcoin.debug('Received alert from: %s', peer.host); + bcoin.debug(payload); self.emit('alert', payload, peer); }); @@ -887,7 +889,7 @@ Pool.prototype._createPeer = function _createPeer(options) { if (version.height > self.block.versionHeight) self.block.versionHeight = version.height; - utils.debug( + bcoin.debug( 'Received version from %s: version=%d height=%d agent=%s', peer.host, version.version, version.height, version.agent); @@ -1153,7 +1155,7 @@ Pool.prototype._removePeer = function _removePeer(peer) { this.peers.all.splice(i, 1); if (this.peers.load === peer) { - utils.debug('Removed loader peer (%s).', peer.host); + bcoin.debug('Removed loader peer (%s).', peer.host); this.peers.load = null; } }; @@ -1300,12 +1302,12 @@ Pool.prototype.searchWallet = function(wallet, callback) { self.chain.reset(height, function(err) { if (err) { - utils.debug('Failed to reset height: %s', err.stack + ''); + bcoin.debug('Failed to reset height: %s', err.stack + ''); return callback(err); } - utils.debug('Wallet height: %s', height); - utils.debug( + bcoin.debug('Wallet height: %s', height); + bcoin.debug( 'Reverted chain to height=%d (%s)', self.chain.height, new Date(self.chain.tip.ts * 1000) @@ -1322,12 +1324,12 @@ Pool.prototype.searchWallet = function(wallet, callback) { self.chain.resetTime(ts, function(err) { if (err) { - utils.debug('Failed to reset time: %s', err.stack + ''); + bcoin.debug('Failed to reset time: %s', err.stack + ''); return callback(err); } - utils.debug('Wallet time: %s', new Date(ts * 1000)); - utils.debug( + bcoin.debug('Wallet time: %s', new Date(ts * 1000)); + bcoin.debug( 'Reverted chain to height=%d (%s)', self.chain.height, new Date(self.chain.tip.ts * 1000) @@ -1437,7 +1439,7 @@ Pool.prototype.getData = function getData(peer, type, hash, options, callback) { if (type === self.tx.type) { if (peer.queue.tx.length === 0) { utils.nextTick(function() { - utils.debug( + bcoin.debug( 'Requesting %d/%d txs from %s with getdata', peer.queue.tx.length, self.request.activeTX, @@ -1513,7 +1515,7 @@ Pool.prototype._sendRequests = function _sendRequests(peer) { return item.start(); }); - utils.debug( + bcoin.debug( 'Requesting %d/%d blocks from %s with getdata', items.length, this.request.activeBlocks, @@ -1880,7 +1882,7 @@ Pool.prototype.setMisbehavior = function setMisbehavior(peer, score) { if (peer.banScore >= constants.banScore) { this.peers.misbehaving[peer.host] = utils.now(); - utils.debug('Ban threshold exceeded for %s', peer.host); + bcoin.debug('Ban threshold exceeded for %s', peer.host); peer.destroy(); return true; } @@ -1912,7 +1914,7 @@ Pool.prototype.isMisbehaving = function isMisbehaving(host) { Pool.prototype.reject = function reject(peer, obj, code, reason, score) { if (obj) { - utils.debug('Rejecting %s %s from %s: ccode=%s reason=%s', + bcoin.debug('Rejecting %s %s from %s: ccode=%s reason=%s', obj.type, obj.hash('hex'), peer.host, code, reason); peer.reject({ @@ -1921,7 +1923,7 @@ Pool.prototype.reject = function reject(peer, obj, code, reason, score) { data: obj.hash() }); } else { - utils.debug('Rejecting packet from %s: ccode=%s reason=%s', + bcoin.debug('Rejecting packet from %s: ccode=%s reason=%s', peer.host, code, reason); peer.reject({ @@ -2002,4 +2004,5 @@ LoadRequest.prototype.finish = function finish() { * Expose */ -module.exports = Pool; +return Pool; +}; diff --git a/lib/bcoin/profiler.js b/lib/bcoin/profiler.js index ba6c80b1..35088b82 100644 --- a/lib/bcoin/profiler.js +++ b/lib/bcoin/profiler.js @@ -1,10 +1,14 @@ /** * profiler.js - profiler for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + +var exports = {}; + var utils = require('./utils'); var assert = utils.assert; var fs, profiler; @@ -16,7 +20,7 @@ if (bcoin.profile && !bcoin.isBrowser) { if (profiler) { utils.nextTick(function() { - utils.debug('Starting node with profiler enabled.'); + bcoin.debug('Starting node with profiler enabled.'); }); } @@ -27,7 +31,7 @@ if (profiler) { function Profile(name) { if (profiler) { name = 'profile-' + (name ? name + '-' : '') + Profile.uid++; - utils.debug('Starting CPU profile: %s', name); + bcoin.debug('Starting CPU profile: %s', name); this.profile = profiler.startProfiling(name, true); this.name = name; } @@ -63,7 +67,7 @@ Profile.prototype.save = function save(callback) { assert(this.profile); - utils.debug('Saving CPU profile: %s', this.name); + bcoin.debug('Saving CPU profile: %s', this.name); return this.profile['export'](function(err, result) { var file; @@ -87,7 +91,7 @@ Profile.prototype.save = function save(callback) { function Snapshot(name) { if (profiler) { name = 'snapshot-' + (name ? name + '-' : '') + Snapshot.uid++; - utils.debug('Taking heap snapshot: %s', name); + bcoin.debug('Taking heap snapshot: %s', name); this.snapshot = profiler.takeSnapshot(name); this.name = name; } @@ -132,7 +136,7 @@ Snapshot.prototype.save = function save(callback) { assert(this.snapshot); - utils.debug('Saving heap snapshot: %s', this.name); + bcoin.debug('Saving heap snapshot: %s', this.name); return this.snapshot['export'](function(err, result) { var file; @@ -171,7 +175,7 @@ exports.snapshot = function snapshot(name, callback) { if (bcoin.debugLogs) { mem = process.memoryUsage(); - utils.debug('Memory: rss=%dmb, js-heap=%d/%dmb native-heap=%dmb', + bcoin.debug('Memory: rss=%dmb, js-heap=%d/%dmb native-heap=%dmb', utils.mb(mem.rss), utils.mb(mem.heapUsed), utils.mb(mem.heapTotal), @@ -184,3 +188,6 @@ exports.snapshot = function snapshot(name, callback) { snapshot = new Snapshot(name); snapshot.save(callback); }; + +return exports; +}; diff --git a/lib/bcoin/protocol/constants.js b/lib/bcoin/protocol/constants.js index 30454cba..9f7a33dd 100644 --- a/lib/bcoin/protocol/constants.js +++ b/lib/bcoin/protocol/constants.js @@ -1,6 +1,7 @@ /** * constants.js - bitcoin constants for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/protocol/framer.js b/lib/bcoin/protocol/framer.js index 3980e214..ee2cbcc1 100644 --- a/lib/bcoin/protocol/framer.js +++ b/lib/bcoin/protocol/framer.js @@ -1,11 +1,13 @@ /** * framer.js - packet framer for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../../bcoin'); -var network = require('./network'); +module.exports = function(bcoin) { + +var network = bcoin.protocol.network; var constants = require('./constants'); var utils = require('../utils'); var assert = utils.assert; @@ -937,4 +939,5 @@ Framer.tx.virtualSize = function txVirtualSize(tx) { * Expose */ -module.exports = Framer; +return Framer; +}; diff --git a/lib/bcoin/protocol/index.js b/lib/bcoin/protocol/index.js index 849aded0..119d5860 100644 --- a/lib/bcoin/protocol/index.js +++ b/lib/bcoin/protocol/index.js @@ -1,12 +1,17 @@ /** * protocol/index.js - bitcoin protocol for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var protocol = exports; +module.exports = function(bcoin) { + bcoin.protocol = {}; -protocol.constants = require('./constants'); -protocol.framer = require('./framer'); -protocol.parser = require('./parser'); -protocol.network = require('./network'); + bcoin.protocol.constants = require('./constants'); + bcoin.protocol.network = require('./network').get(bcoin.networkType); + bcoin.protocol.framer = require('./framer')(bcoin); + bcoin.protocol.parser = require('./parser')(bcoin); + + return bcoin.protocol; +}; diff --git a/lib/bcoin/protocol/network.js b/lib/bcoin/protocol/network.js index f6bb99c2..a4fb2d98 100644 --- a/lib/bcoin/protocol/network.js +++ b/lib/bcoin/protocol/network.js @@ -1,11 +1,13 @@ /** * network.js - bitcoin networks for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ var bn = require('bn.js'); var utils = require('../utils'); +var assert = utils.assert; /** * Network @@ -14,13 +16,13 @@ var utils = require('../utils'); var network = exports; var main, testnet, regtest, segnet3, segnet4; -network.set = function set(type) { - var net = network[type]; - utils.merge(network, net); -}; - network.types = ['main', 'testnet', 'regtest', 'segnet3', 'segnet4']; +network.get = function get(type) { + assert(network[type], 'Network not found.'); + return utils.merge({}, network, network[type]); +}; + /** * Main */ @@ -145,7 +147,7 @@ main.deployments = { timeout: 1491004800 // April 1st, 2017 } // bip109: { - // bit: 28, + // bit: 4, // startTime: 1453939200, // Jan 28th, 2016 // timeout: 1514764800 // Jan 1st, 2018 // } @@ -494,7 +496,7 @@ segnet4.deployments = utils.merge({}, main.deployments, { timeout: 999999999999 } // bip109: { - // bit: 28, + // bit: 4, // startTime: 1453939200, // Jan 28th, 2016 // timeout: 1514764800 // Jan 1st, 2018 // } @@ -514,6 +516,10 @@ segnet4.genesis = { segnet4.genesisBlock = '0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a7d719856ffff011e000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000'; +/** + * Global + */ + network.xprivkeys = { '76066276': 'main', '70615956': 'testnet', diff --git a/lib/bcoin/protocol/parser.js b/lib/bcoin/protocol/parser.js index 5e6e8d0c..7323d47a 100644 --- a/lib/bcoin/protocol/parser.js +++ b/lib/bcoin/protocol/parser.js @@ -1,15 +1,17 @@ /** * parser.js - packet parser for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../../bcoin'); var utils = require('../utils'); var assert = utils.assert; var constants = require('./constants'); -var network = require('./network'); +var network = bcoin.protocol.network; var BufferReader = require('../reader'); /** @@ -256,7 +258,7 @@ Parser.prototype.parsePayload = function parsePayload(cmd, p) { case 'utxos': return Parser.parseUTXOs(p); default: - utils.debug('Unknown packet: %s', cmd); + bcoin.debug('Unknown packet: %s', cmd); return p; } }; @@ -1010,4 +1012,5 @@ Parser.parseAlert = function parseAlert(p) { * Expose */ -module.exports = Parser; +return Parser; +}; diff --git a/lib/bcoin/ramdisk.js b/lib/bcoin/ramdisk.js deleted file mode 100644 index 798f99e7..00000000 --- a/lib/bcoin/ramdisk.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * ramdisk.js - file in ram for bcoin - * Copyright (c) 2014-2015, Fedor Indutny (MIT License) - * https://github.com/indutny/bcoin - */ - -var utils = require('./utils'); -var assert = utils.assert; - -/** - * Ramdisk - */ - -function Ramdisk(fileData, size) { - if (!(this instanceof Ramdisk)) - return new Ramdisk(fileData, size); - - if (size == null) { - size = fileData; - fileData = new Buffer([]); - } - - assert(Buffer.isBuffer(fileData)); - assert(typeof size === 'number'); - - if (size < fileData.length) - size = fileData.length + (fileData.length / 2 | 0); - - this.size = fileData.length; - this.heap = new Buffer(size); - - fileData.copy(this.heap, 0, 0, fileData.length); -} - -Ramdisk.prototype.brk = function brk() { - var heap = new Buffer(this.heap.length + (this.heap.length / 2 | 0)); - utils.debug('brk1(%d, %d)', this.heap.length, heap.length); - this.heap.copy(heap, 0, 0, this.heap.length); - utils.debug('brk2(%d, %d)', this.heap.length, heap.length); - this.heap = heap; -}; - -Ramdisk.prototype.write = function write(data, offset) { - var added = Math.max(0, (offset + data.length) - this.size); - - while (offset + data.length > this.heap.length) - this.brk(); - - data.copy(this.heap, offset, 0, data.length); - - this.size += added; - - return data.length; -}; - -Ramdisk.prototype.truncate = function truncate(size) { - assert(size <= this.size); - this.size = size; -}; - -Ramdisk.prototype.read = function read(size, offset) { - var data, ret; - - if (offset + size > this.size) - return; - - data = this.heap.slice(offset, offset + size); - ret = new Buffer(size); - - data.copy(ret, 0, 0, data.length); - - return ret; -}; - -/** - * Expose - */ - -module.exports = Ramdisk; diff --git a/lib/bcoin/reader.js b/lib/bcoin/reader.js index 7572bbe1..02b36a78 100644 --- a/lib/bcoin/reader.js +++ b/lib/bcoin/reader.js @@ -1,6 +1,7 @@ /** * reader.js - buffer reader for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ diff --git a/lib/bcoin/script.js b/lib/bcoin/script.js index 1cb28a26..070c4e3e 100644 --- a/lib/bcoin/script.js +++ b/lib/bcoin/script.js @@ -1,10 +1,12 @@ /** * script.js - script interpreter for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var bn = require('bn.js'); var constants = bcoin.protocol.constants; var utils = require('./utils'); @@ -545,10 +547,10 @@ Script.prototype.execute = function execute(stack, flags, tx, index, version) { return this.interpret(stack, flags, tx, index, version); } catch (e) { if (e.type === 'ScriptError') { - utils.debug('Script error: %s.', e.message); + bcoin.debug('Script error: %s.', e.message); } else { - utils.debug('Script interpreter threw:'); - utils.debug(e.stack + ''); + bcoin.debug('Script interpreter threw:'); + bcoin.debug(e.stack + ''); } return false; } @@ -2017,7 +2019,7 @@ Script.isValidKey = function isValidKey(key, flags) { if (flags & constants.flags.VERIFY_STRICTENC) { if (!Script.isKeyEncoding(key)) { - utils.debug('Script failed key encoding test.'); + bcoin.debug('Script failed key encoding test.'); return false; } } @@ -2060,21 +2062,21 @@ Script.isValidSignature = function isValidSignature(sig, flags) { || (flags & constants.flags.VERIFY_LOW_S) || (flags & constants.flags.VERIFY_STRICTENC)) { if (!Script.isSignatureEncoding(sig)) { - utils.debug('Script does not have a proper signature encoding.'); + bcoin.debug('Script does not have a proper signature encoding.'); return false; } } if (flags & constants.flags.VERIFY_LOW_S) { if (!Script.isLowDER(sig)) { - utils.debug('Script does not have a low DER.'); + bcoin.debug('Script does not have a low DER.'); return false; } } if (flags & constants.flags.VERIFY_STRICTENC) { if (!Script.isHashType(sig)) { - utils.debug('Script does not have a valid hash type.'); + bcoin.debug('Script does not have a valid hash type.'); return false; } } @@ -2527,12 +2529,12 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) { // Failure on version=0 (bad program data length) if (!program.type) { - utils.debug('Malformed witness program.'); + bcoin.debug('Malformed witness program.'); return false; } if (program.version > 0) { - utils.debug('Unknown witness program version: %s', program.version); + bcoin.debug('Unknown witness program version: %s', program.version); // Anyone can spend (we can return true here // if we want to always relay these transactions). // Otherwise, if we want to act like an "old" @@ -2822,4 +2824,5 @@ utils.inherits(ScriptError, Error); Script.witness = Witness; Script.stack = Stack; Script.error = ScriptError; -module.exports = Script; +return Script; +}; diff --git a/lib/bcoin/spvnode.js b/lib/bcoin/spvnode.js index fe884765..388a2306 100644 --- a/lib/bcoin/spvnode.js +++ b/lib/bcoin/spvnode.js @@ -1,10 +1,12 @@ /** * spvnode.js - spv node for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var utils = require('./utils'); var assert = utils.assert; @@ -109,7 +111,7 @@ SPVNode.prototype._init = function _init() { self.loaded = true; self.emit('open'); - utils.debug('Node is loaded.'); + bcoin.debug('Node is loaded.'); } options = utils.merge({ @@ -191,7 +193,7 @@ SPVNode.prototype.createWallet = function createWallet(options, callback) { assert(wallet); - utils.debug('Loaded wallet with id=%s address=%s', + bcoin.debug('Loaded wallet with id=%s address=%s', wallet.id, wallet.getAddress()); self.pool.addWallet(wallet, function(err) { @@ -211,4 +213,5 @@ SPVNode.prototype.getWallet = function getWallet(id, passphrase, callback) { * Expose */ -module.exports = SPVNode; +return SPVNode; +}; diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 18eb28e6..959d57d2 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -1,12 +1,14 @@ /** * tx.js - transaction object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var bn = require('bn.js'); -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -410,7 +412,7 @@ TX.prototype.verify = function verify(index, force, flags) { continue; if (!input.coin) { - utils.debug('Warning: Not all coins are available for tx.verify().'); + bcoin.debug('Warning: Not all coins are available for tx.verify().'); return false; } @@ -1402,4 +1404,5 @@ TX.isTX = function isTX(obj) { * Expose */ -module.exports = TX; +return TX; +}; diff --git a/lib/bcoin/txdb.js b/lib/bcoin/txdb.js index 3eeee40d..03c03896 100644 --- a/lib/bcoin/txdb.js +++ b/lib/bcoin/txdb.js @@ -1,11 +1,13 @@ /** * txdb.js - persistent transaction pool * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var bn = require('bn.js'); -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = bcoin.utils.assert; var EventEmitter = require('events').EventEmitter; @@ -1666,4 +1668,5 @@ TXPool.prototype.zap = function zap(address, now, age, callback, force) { * Expose */ -module.exports = TXPool; +return TXPool; +}; diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index cd066b3e..370d0e42 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -1,6 +1,7 @@ /** * utils.js - utils for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ @@ -27,9 +28,6 @@ utils.nop = function() {}; utils.gc = !utils.isBrowser && typeof gc === 'function' ? gc : utils.nop; -if (utils.gc !== utils.nop) - console.error('bcoin started with --expose-gc enabled.'); - utils.slice = function slice(buf, start, end) { var clone; @@ -713,9 +711,6 @@ utils.print = function print() { return process.stdout.write(utils.format(args, true)); }; -utils.debug = utils.nop; -utils.ensurePrefix = utils.nop; - utils.merge = function merge(target) { var args = Array.prototype.slice.call(arguments, 1); args.forEach(function(obj) { diff --git a/lib/bcoin/wallet.js b/lib/bcoin/wallet.js index f9e8aa71..67825017 100644 --- a/lib/bcoin/wallet.js +++ b/lib/bcoin/wallet.js @@ -1,10 +1,12 @@ /** * wallet.js - wallet object for bcoin * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; var utils = require('./utils'); var assert = utils.assert; @@ -132,7 +134,7 @@ Wallet.prototype._init = function _init() { this.provider.setID(this.id); this.on('error', function(err) { - utils.debug('Wallet Error: %s', err.message); + bcoin.debug('Wallet Error: %s', err.message); }); this.provider.on('error', function(err) { @@ -1275,4 +1277,5 @@ Wallet.isWallet = function isWallet(obj) { * Expose */ -module.exports = Wallet; +return Wallet; +}; diff --git a/lib/bcoin/walletdb.js b/lib/bcoin/walletdb.js index f29d30d4..cab6dcab 100644 --- a/lib/bcoin/walletdb.js +++ b/lib/bcoin/walletdb.js @@ -1,12 +1,14 @@ /** * walletdb.js - storage for wallets * Copyright (c) 2014-2015, Fedor Indutny (MIT License) + * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License). * https://github.com/indutny/bcoin */ +module.exports = function(bcoin) { + var EventEmitter = require('events').EventEmitter; -var bcoin = require('../bcoin'); var utils = require('./utils'); var assert = utils.assert; var DUMMY = new Buffer([0]); @@ -794,4 +796,8 @@ Provider.prototype.zap = function zap(wallet, address) { * Expose */ -module.exports = WalletDB; +WalletDB.Provider = Provider; + +return WalletDB; + +}; diff --git a/lib/bcoin/workers.js b/lib/bcoin/workers.js index 4ed3ac50..6d3b9585 100644 --- a/lib/bcoin/workers.js +++ b/lib/bcoin/workers.js @@ -4,7 +4,8 @@ * https://github.com/indutny/bcoin */ -var bcoin = require('../bcoin'); +module.exports = function(bcoin) { + var bn = require('bn.js'); var constants = bcoin.protocol.constants; var utils = require('./utils'); @@ -12,7 +13,7 @@ var assert = utils.assert; var BufferWriter = require('./writer'); var BufferReader = require('./reader'); var cp = require('child_process'); -var workers = exports; +var workers = {}; var HEADER_SIZE = 12; @@ -20,35 +21,36 @@ var HEADER_SIZE = 12; * Master */ -workers.MAX_WORKERS = +process.env.BCOIN_WORKERS || 6; -workers.TIMEOUT = 10000; +workers.MAX_WORKERS = bcoin.maxWorkers || 6; +workers.TIMEOUT = bcoin.workerTimeout || 10000; workers.children = {}; workers.uid = 0; workers.spawn = function spawn(index) { var child; - utils.debug('Spawning worker process: %d', index); + bcoin.debug('Spawning worker process: %d', index); child = cp.spawn(process.argv[0], [__filename], { stdio: ['pipe', 'pipe', 'inherit'], env: utils.merge({}, process.env, { - BCOIN_WORKER_ID: index + '' + BCOIN_WORKER_ID: index + '', + BCOIN_WORKER_OPTIONS: JSON.stringify(bcoin.options) }) }); child.on('error', function(err) { - utils.debug('Worker %d error: %s', index, err.message); + bcoin.debug('Worker %d error: %s', index, err.message); }); child.on('exit', function(code) { - utils.debug('Worker %d exited: %s', index, code); + bcoin.debug('Worker %d exited: %s', index, code); if (workers.children[index] === child) delete workers.children[index]; }); child.on('close', function() { - utils.debug('Worker %d closed', index); + bcoin.debug('Worker %d closed', index); if (workers.children[index] === child) delete workers.children[index]; }); @@ -141,7 +143,6 @@ workers.listen = function listen() { return console.error.apply(console.error, arguments); }; - utils.debug = bcoin.debug; utils.print = bcoin.debug; process.stdin.on('data', parser(function(id, body) { @@ -150,7 +151,7 @@ workers.listen = function listen() { try { res = workers[body.name].apply(workers[body.name], body.items); } catch (e) { - utils.debug(e.stack + ''); + bcoin.debug(e.stack + ''); return process.stdout.write(createPacket(id, null, [{ message: e.message, stack: e.stack + '' @@ -182,7 +183,7 @@ workers.mine = function mine(attempt) { dsha256: utils.dsha256 }); attempt.on('status', function(stat) { - utils.debug( + bcoin.debug( 'hashrate=%dkhs hashes=%d target=%d height=%d best=%s', stat.hashrate / 1000 | 0, stat.hashes, @@ -377,7 +378,7 @@ function parser(onPacket) { buf = []; waiting = HEADER_SIZE; read = 0; - utils.debug('Bad magic number: %d', header.magic); + bcoin.debug('Bad magic number: %d', header.magic); return; } @@ -394,7 +395,7 @@ function parser(onPacket) { try { packet = parseBody(packet); } catch (e) { - utils.debug(e.stack + ''); + bcoin.debug(e.stack + ''); return; } @@ -410,5 +411,10 @@ function parser(onPacket) { }; } -if (process.env.BCOIN_WORKER_ID) - workers.listen(); +return workers; +}; + +if (process.env.BCOIN_WORKER_ID) { + var env = require('./env')(JSON.parse(process.env.BCOIN_WORKER_OPTIONS)); + env.workers.listen(); +} diff --git a/test/block-test.js b/test/block-test.js index 2a45a05e..60408fdd 100644 --- a/test/block-test.js +++ b/test/block-test.js @@ -1,6 +1,6 @@ var assert = require('assert'); var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); describe('Block', function() { var parser = bcoin.protocol.parser; diff --git a/test/bloom-test.js b/test/bloom-test.js index a9385985..059e5d15 100644 --- a/test/bloom-test.js +++ b/test/bloom-test.js @@ -1,5 +1,5 @@ var assert = require('assert'); -var bcoin = require('../'); +var bcoin = require('../')(); describe('Bloom', function() { it('should do proper murmur3', function() { diff --git a/test/hd-test.js b/test/hd-test.js index 80c0abfe..c02d0b6f 100644 --- a/test/hd-test.js +++ b/test/hd-test.js @@ -1,6 +1,6 @@ // var assert = require('assert'); var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); var utils = bcoin.utils; var assert = utils.assert; diff --git a/test/node-test.js b/test/node-test.js index 821b1fd4..e5d7f5f8 100644 --- a/test/node-test.js +++ b/test/node-test.js @@ -1,5 +1,5 @@ var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); var constants = bcoin.protocol.constants; var utils = bcoin.utils; var assert = utils.assert; diff --git a/test/protocol-test.js b/test/protocol-test.js index f0150b1b..9210eabd 100644 --- a/test/protocol-test.js +++ b/test/protocol-test.js @@ -1,5 +1,5 @@ var assert = require('assert'); -var bcoin = require('../'); +var bcoin = require('../')(); var constants = bcoin.protocol.constants; var utils = bcoin.utils; diff --git a/test/script-test.js b/test/script-test.js index 3509ef38..ece5951b 100644 --- a/test/script-test.js +++ b/test/script-test.js @@ -1,5 +1,5 @@ var assert = require('assert'); -var bcoin = require('../'); +var bcoin = require('../')(); var Script = bcoin.script; var Stack = bcoin.script.stack; var opcodes = bcoin.protocol.constants.opcodes; diff --git a/test/tx-test.js b/test/tx-test.js index 00366ae4..4cd10b3f 100644 --- a/test/tx-test.js +++ b/test/tx-test.js @@ -1,6 +1,6 @@ var assert = require('assert'); var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); describe('TX', function() { var parser = bcoin.protocol.parser; diff --git a/test/utils-test.js b/test/utils-test.js index e460fdf2..288e4640 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -1,6 +1,6 @@ var assert = require('assert'); var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); var utils = bcoin.utils; describe('Utils', function() { diff --git a/test/wallet-test.js b/test/wallet-test.js index d0ff7c11..98bfdd10 100644 --- a/test/wallet-test.js +++ b/test/wallet-test.js @@ -1,5 +1,5 @@ var bn = require('bn.js'); -var bcoin = require('../'); +var bcoin = require('../')(); var constants = bcoin.protocol.constants; var utils = bcoin.utils; var assert = utils.assert;