add environment.

This commit is contained in:
Christopher Jeffrey 2016-04-06 18:20:03 -07:00
parent 5830cc044b
commit 0a7f118528
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
66 changed files with 632 additions and 487 deletions

View File

@ -167,9 +167,7 @@ miner.createBlock(function(err, attempt) {
### Connecting to the P2P network ### Connecting to the P2P network
``` js ``` js
var bcoin = require('bcoin'); var bcoin = require('bcoin')('testnet');
bcoin.protocol.network.set('testnet');
var chain = new bcoin.chain({ db: 'leveldb' }); var chain = new bcoin.chain({ db: 'leveldb' });
var mempool = new bcoin.mempool({ chain: chain, db: 'memory' }); var mempool = new bcoin.mempool({ chain: chain, db: 'memory' });
@ -200,9 +198,7 @@ pool.on('tx', function(tx) {
### Doing an SPV sync ### Doing an SPV sync
``` js ``` js
var bcoin = require('bcoin'); var bcoin = require('bcoin')('testnet');
bcoin.protocol.network.set('testnet');
var chain = new bcoin.chain({ var chain = new bcoin.chain({
db: 'leveldb', db: 'leveldb',

View File

@ -1,18 +1,13 @@
#!/usr/bin/env node #!/usr/bin/env node
var bcoin = require('bcoin'); var argv = parseArg(process.argv);
var bcoin = require('bcoin')(argv.network);
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var Client = bcoin.http.client; var Client = bcoin.http.client;
var argv = parseArg(process.argv); var client = new Client(argv.url || 'localhost:8080');
if (argv.network)
bcoin.protocol.network.set(argv.network);
var client = new Client(argv.url || 'localhost:8080', {
setNetwork: argv.network == null
});
function getID() { function getID() {
if (process.env.BCOIN_WALLET_ID) if (process.env.BCOIN_WALLET_ID)

View File

@ -1,11 +1,10 @@
#!/usr/bin/env node #!/usr/bin/env node
var bcoin = require('bcoin'); var bcoin = require('bcoin')({ debug: true });
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var node = bcoin.fullnode({ var node = bcoin.fullnode({
debug: true,
passphrase: 'node', passphrase: 'node',
prune: process.argv.indexOf('--prune') !== -1, prune: process.argv.indexOf('--prune') !== -1,
useCheckpoints: process.argv.indexOf('--checkpoints') !== -1, useCheckpoints: process.argv.indexOf('--checkpoints') !== -1,
@ -15,7 +14,7 @@ var node = bcoin.fullnode({
}); });
node.on('error', function(err) { node.on('error', function(err) {
utils.debug(err.message); bcoin.debug(err.stack + '');
}); });
node.open(function(err) { node.open(function(err) {

View File

@ -1,18 +1,17 @@
#!/usr/bin/env node #!/usr/bin/env node
var bcoin = require('bcoin'); var bcoin = require('bcoin')({ debug: true });
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var node = bcoin.spvnode({ var node = bcoin.spvnode({
debug: true,
passphrase: 'node', passphrase: 'node',
preload: process.argv.indexOf('--preload') !== -1, preload: process.argv.indexOf('--preload') !== -1,
useCheckpoints: process.argv.indexOf('--checkpoints') !== -1 useCheckpoints: process.argv.indexOf('--checkpoints') !== -1
}); });
node.on('error', function(err) { node.on('error', function(err) {
utils.debug(err.message); bcoin.debug(err.message);
}); });
node.open(function(err) { node.open(function(err) {

View File

@ -1,133 +1,12 @@
/** /**
* bcoin - javascript bitcoin library * bcoin - javascript bitcoin library
* Copyright (c) 2014-2015, Fedor Indutny (MIT License). * Copyright (c) 2014-2015, Fedor Indutny (MIT License).
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = exports; var Environment = require('./bcoin/env');
var utils = require('./bcoin/utils');
var assert = utils.assert;
var fs;
try { module.exports = function BCoin(options) {
fs = require('f' + 's'); return new Environment(options);
} 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);
}
}; };
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');

View File

@ -1,11 +1,13 @@
/** /**
* abstractblock.js - abstract block object for bcoin * abstractblock.js - abstract block object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils');
var utils = bcoin.utils;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
/** /**
@ -104,4 +106,5 @@ AbstractBlock.prototype.__defineGetter__('rhash', function() {
* Expose * Expose
*/ */
module.exports = AbstractBlock; return AbstractBlock;
};

View File

@ -1,10 +1,12 @@
/** /**
* address.js - address object for bcoin * address.js - address object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -587,4 +589,5 @@ Address.fromJSON = function fromJSON(json, passphrase) {
* Expose * Expose
*/ */
module.exports = Address; return Address;
};

View File

@ -1,10 +1,12 @@
/** /**
* block.js - block object for bcoin * block.js - block object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -473,4 +475,5 @@ Block.isBlock = function isBlock(obj) {
* Expose * Expose
*/ */
module.exports = Block; return Block;
};

View File

@ -1,6 +1,7 @@
/** /**
* bloom.js - bloom filter for bcoin * bloom.js - bloom filter for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,6 +1,7 @@
/** /**
* bst.js - iterative binary search tree for bcoin * bst.js - iterative binary search tree for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,12 +1,14 @@
/** /**
* chain.js - blockchain management for bcoin * chain.js - blockchain management for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var bn = require('bn.js'); var bn = require('bn.js');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -66,12 +68,12 @@ Chain.prototype._init = function _init() {
if (self.height < 400000) if (self.height < 400000)
return; 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()); utils.revHex(entry.hash), entry.height, getHost());
}); });
this.on('competitor', function(block, entry) { 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-height=%d competitor-height=%d'
+ ' tip-hash=%s competitor-hash=%s' + ' tip-hash=%s competitor-hash=%s'
+ ' tip-chainwork=%s competitor-chainwork=%s' + ' tip-chainwork=%s competitor-chainwork=%s'
@ -88,17 +90,17 @@ Chain.prototype._init = function _init() {
}); });
this.on('resolved', function(block, entry) { 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()); utils.revHex(entry.hash), entry.height, getHost());
}); });
this.on('checkpoint', function(block, data) { 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()); utils.revHex(data.checkpoint), data.height, getHost());
}); });
this.on('fork', function(block, data) { this.on('fork', function(block, data) {
utils.debug( bcoin.debug(
'Fork at height %d: expected=%s received=%s checkpoint=%s', 'Fork at height %d: expected=%s received=%s checkpoint=%s',
data.height, data.height,
utils.revHex(data.expected), utils.revHex(data.expected),
@ -107,36 +109,36 @@ Chain.prototype._init = function _init() {
getHost() getHost()
); );
if (data.checkpoint) if (data.checkpoint)
utils.debug('WARNING: Block failed a checkpoint.'); bcoin.debug('WARNING: Block failed a checkpoint.');
}); });
this.on('invalid', function(block, data) { this.on('invalid', function(block, data) {
utils.debug( bcoin.debug(
'Invalid block at height %d: hash=%s (%s)', 'Invalid block at height %d: hash=%s (%s)',
data.height, data.height,
utils.revHex(data.hash), utils.revHex(data.hash),
getHost() getHost()
); );
if (data.chain) { if (data.chain) {
utils.debug( bcoin.debug(
'Peer is sending an invalid continuation chain (%s)', 'Peer is sending an invalid continuation chain (%s)',
getHost()); getHost());
} else if (data.seen) { } 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) { this.on('exists', function(block, data) {
utils.debug('Already have block %s (%s)', bcoin.debug('Already have block %s (%s)',
data.height, getHost()); data.height, getHost());
}); });
this.on('orphan', function(block, data) { 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) { 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) { this.db.on('add entry', function(entry) {
@ -155,7 +157,7 @@ Chain.prototype._init = function _init() {
self.emit('remove block', block); self.emit('remove block', block);
}); });
utils.debug('Chain is loading.'); bcoin.debug('Chain is loading.');
self.db.open(function(err) { self.db.open(function(err) {
if (err) if (err)
@ -182,7 +184,7 @@ Chain.prototype._init = function _init() {
return self.emit('error', err); return self.emit('error', err);
if (result) if (result)
utils.debug('Segwit is active.'); bcoin.debug('Segwit is active.');
self.loaded = true; self.loaded = true;
self.emit('open'); self.emit('open');
@ -231,9 +233,9 @@ Chain.prototype._preload = function _preload(callback) {
return callback(); return callback();
if (network.type !== 'main') 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) { function parseHeader(buf) {
var headers = bcoin.protocol.parser.parseBlockHeaders(buf); var headers = bcoin.protocol.parser.parseBlockHeaders(buf);
@ -362,7 +364,7 @@ Chain.prototype._preload = function _preload(callback) {
save(entry); save(entry);
if ((height + 1) % 50000 === 0) 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; lastEntry = entry;
height++; height++;
@ -928,7 +930,7 @@ Chain.prototype._setBestChain = function _setBestChain(entry, block, callback) {
// A higher fork has arrived. // A higher fork has arrived.
// Time to reorganize the chain. // Time to reorganize the chain.
utils.debug('WARNING: Reorganizing chain.'); bcoin.debug('WARNING: Reorganizing chain.');
return this._reorganize(entry, block, done); return this._reorganize(entry, block, done);
}; };
@ -2056,4 +2058,5 @@ Chain.prototype.checkLocks = function checkLocks(tx, flags, entry, callback, for
* Expose * Expose
*/ */
module.exports = Chain; return Chain;
};

View File

@ -1,10 +1,12 @@
/** /**
* chainblock.js - chainblock object for bcoin * chainblock.js - chainblock object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -311,4 +313,5 @@ ChainBlock.isChainBlock = function isChainBlock(obj) {
* Expose * Expose
*/ */
module.exports = ChainBlock; return ChainBlock;
};

View File

@ -1,12 +1,14 @@
/** /**
* chaindb.js - blockchain data management for bcoin * chaindb.js - blockchain data management for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -68,7 +70,7 @@ ChainDB.prototype._init = function _init() {
writeBufferSize: 8 << 20 writeBufferSize: 8 << 20
}); });
utils.debug('Starting chain load.'); bcoin.debug('Starting chain load.');
this.db.open(function(err) { this.db.open(function(err) {
if (err) if (err)
@ -78,7 +80,7 @@ ChainDB.prototype._init = function _init() {
if (err) if (err)
return self.emit('error', err); return self.emit('error', err);
utils.debug('Chain successfully loaded.'); bcoin.debug('Chain successfully loaded.');
self.loaded = true; self.loaded = true;
self.emit('open'); self.emit('open');
@ -1487,4 +1489,5 @@ NullCache.prototype.reset = function reset() {};
* Expose * Expose
*/ */
module.exports = ChainDB; return ChainDB;
};

View File

@ -1,11 +1,13 @@
/** /**
* coin.js - coin object for bcoin * coin.js - coin object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -205,4 +207,5 @@ Coin.isCoin = function isCoin(obj) {
* Expose * Expose
*/ */
module.exports = Coin; return Coin;
};

View File

@ -1,10 +1,12 @@
/** /**
* coins.js - coins object for bcoin * coins.js - coins object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -194,4 +196,5 @@ Coins.fromRaw = function fromRaw(buf, hash) {
* Expose * Expose
*/ */
module.exports = Coins; return Coins;
};

View File

@ -1,10 +1,12 @@
/** /**
* coinview.js - coinview object for bcoin * coinview.js - coinview object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -101,4 +103,5 @@ CoinView.prototype.toArray = function toArray() {
* Expose * Expose
*/ */
module.exports = CoinView; return CoinView;
};

View File

@ -1,10 +1,12 @@
/** /**
* compactblock.js - compact block object for bcoin * compactblock.js - compact block object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -48,8 +50,15 @@ CompactBlock.prototype.toBlock = function toBlock() {
return block; return block;
}; };
CompactBlock.isCompactBlock = function isCompactBlock(block) {
return block
&& block.type === 'compactblock'
&& typeof block.toBlock === 'function';
};
/** /**
* Expose * Expose
*/ */
module.exports = CompactBlock; return CompactBlock;
};

View File

@ -1,17 +1,17 @@
/** /**
* ec.js - ecdsa wrapper for secp256k1 and elliptic * ec.js - ecdsa wrapper for secp256k1 and elliptic
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin');
var elliptic = require('elliptic'); var elliptic = require('elliptic');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var ec = exports; var ec = exports;
var crypto, secp256k1; var crypto, secp256k1;
if (!bcoin.isBrowser) if (!utils.isBrowser)
crypto = require('cry' + 'pto'); crypto = require('cry' + 'pto');
try { try {
@ -91,7 +91,7 @@ ec.verify = function verify(msg, sig, key, historical) {
return ec.elliptic.verify(msg, sig, key); return ec.elliptic.verify(msg, sig, key);
} catch (e) { } catch (e) {
// if (!ec.publicKeyVerify(key)) // if (!ec.publicKeyVerify(key))
// utils.debug('Public key is invalid.'); // bcoin.debug('Public key is invalid.');
return false; return false;
} }
}; };

202
lib/bcoin/env.js Normal file
View File

@ -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;

View File

@ -1,10 +1,12 @@
/** /**
* fullnode.js - full node for bcoin * fullnode.js - full node for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -155,7 +157,7 @@ Fullnode.prototype._init = function _init() {
self.loaded = true; self.loaded = true;
self.emit('open'); self.emit('open');
utils.debug('Node is loaded.'); bcoin.debug('Node is loaded.');
} }
options = utils.merge({ options = utils.merge({
@ -245,7 +247,7 @@ Fullnode.prototype.createWallet = function createWallet(options, callback) {
assert(wallet); assert(wallet);
utils.debug('Loaded wallet with id=%s address=%s', bcoin.debug('Loaded wallet with id=%s address=%s',
wallet.id, wallet.getAddress()); wallet.id, wallet.getAddress());
self.pool.addWallet(wallet, function(err) { self.pool.addWallet(wallet, function(err) {
@ -413,4 +415,5 @@ Fullnode.prototype.getConfidence = function getConfidence(tx, callback) {
* Expose * Expose
*/ */
module.exports = Fullnode; return Fullnode;
};

View File

@ -1,6 +1,7 @@
/** /**
* hd.js - hd seeds and keys (BIP32, BIP39) for bcoin. * hd.js - hd seeds and keys (BIP32, BIP39) for bcoin.
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
* https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki * https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
* https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki * https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
@ -46,18 +47,19 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
module.exports = function(bcoin) {
/** /**
* Modules * Modules
*/ */
var bcoin = require('../bcoin');
var bn = require('bn.js'); var bn = require('bn.js');
var utils = require('./utils'); var utils = require('./utils');
var ec = require('./ec'); var ec = require('./ec');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var KeyPair = require('./keypair'); var KeyPair = bcoin.keypair;
var LRU = require('./lru'); var LRU = require('./lru');
var BufferWriter = require('./writer'); var BufferWriter = require('./writer');
var BufferReader = require('./reader'); var BufferReader = require('./reader');
@ -883,7 +885,7 @@ HDPrivateKey.prototype.toSecret = function toSecret() {
* Expose * Expose
*/ */
exports = HD; var exports = HD;
exports.seed = HDSeed; exports.seed = HDSeed;
exports.priv = HDPrivateKey; exports.priv = HDPrivateKey;
@ -892,4 +894,5 @@ exports.privateKey = HDPrivateKey;
exports.publicKey = HDPublicKey; exports.publicKey = HDPublicKey;
exports.fromJSON = HDPrivateKey.fromJSON; exports.fromJSON = HDPrivateKey.fromJSON;
module.exports = HD; return exports;
};

View File

@ -1,10 +1,12 @@
/** /**
* headers.js - headers object for bcoin * headers.js - headers object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
/** /**
@ -85,4 +87,5 @@ Headers.isHeaders = function isHeaders(obj) {
* Expose * Expose
*/ */
module.exports = Headers; return Headers;
};

View File

@ -1,11 +1,13 @@
/** /**
* client.js - http client for wallets * client.js - http client for wallets
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../../bcoin');
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var utils = require('../utils'); var utils = require('../utils');
var request = require('./request'); var request = require('./request');
@ -53,10 +55,9 @@ Client.prototype._init = function _init() {
this.socket.on('open', function() { this.socket.on('open', function() {
self.socket.on('version', function(info) { 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); info.version, info.network);
if (self.options.setNetwork) assert(info.network === network.type);
network.set(info.network);
}); });
self.socket.on('tx', function(tx, map) { self.socket.on('tx', function(tx, map) {
@ -176,11 +177,8 @@ Client.prototype._request = function _request(method, endpoint, json, callback)
if (err) if (err)
return callback(err); return callback(err);
if (self.options.setNetwork) { networkType = res.headers['x-bcoin-network'];
networkType = res.headers['x-bcoin-network']; assert(networkType === network.type);
if (networkType && network.type !== networkType)
network.set(networkType);
}
if (res.statusCode === 404) if (res.statusCode === 404)
return callback(); return callback();
@ -661,4 +659,5 @@ Client.prototype.getInfo = function getInfo(callback) {
* Expose * Expose
*/ */
module.exports = Client; return Client;
};

View File

@ -1,6 +1,7 @@
/** /**
* http.js - http server for bcoin * http.js - http server for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
@ -99,9 +100,9 @@ HTTPServer.prototype._initRouter = function _initRouter() {
req.destroy(); req.destroy();
req.socket.destroy(); req.socket.destroy();
} catch (e) { } 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); done(e);
} }
utils.debug('Request from %s path=%s', self.emit('request', req, res);
req.socket.remoteAddress, req.pathname);
parseBody(req, function(err) { parseBody(req, function(err) {
var method, routes, i; var method, routes, i;
@ -259,21 +259,23 @@ HTTPServer.prototype.del = function del(path, callback) {
this.routes.del.push({ path: path, callback: 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) { HTTPServer.prototype.listen = function listen(port, host, callback) {
var self = this; var self = this;
this.server.listen(port, host, function(err) { this.server.listen(port, host, function(err) {
var address; if (!callback) {
if (err)
throw err;
return;
}
if (err) if (err)
throw err; return callback(err);
address = self.server.address(); return callback(null, self.address());
utils.debug('Listening - host=%s port=%d',
address.address, address.port);
if (callback)
callback();
}); });
}; };
@ -299,7 +301,7 @@ function send(res, code, msg) {
res.write(msg); res.write(msg);
res.end(); res.end();
} catch (e) { } catch (e) {
utils.debug('Write failed: %s', e.message); ;
} }
} }

View File

@ -1,5 +1,21 @@
exports.http = require('./http'); /**
exports.server = require('./server'); * http/index.js - http for bcoin
exports.client = require('./client'); * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
exports.request = require('./request'); * Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
exports.provider = require('./provider'); * 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;
};

View File

@ -1,14 +1,17 @@
/** /**
* provider.js - http provider for wallets * provider.js - http provider for wallets
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var utils = require('../utils'); var utils = require('../utils');
var assert = utils.assert; var assert = utils.assert;
var Client = require('./client'); var Client = bcoin.http.client;
/** /**
* Provider * Provider
@ -133,4 +136,5 @@ Provider.prototype.zap = function zap(now, age, callback) {
* Expose * Expose
*/ */
module.exports = Provider; return Provider;
};

View File

@ -1,6 +1,7 @@
/** /**
* request.js - http request for bcoin * request.js - http request for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,14 +1,16 @@
/** /**
* server.js - http server for bcoin * server.js - http server for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../../bcoin');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var HTTPServer = require('./http'); var HTTPServer = bcoin.http.http;
var utils = require('../utils'); var utils = require('../utils');
var assert = utils.assert; var assert = utils.assert;
@ -40,6 +42,11 @@ utils.inherits(NodeServer, EventEmitter);
NodeServer.prototype._init = function _init() { NodeServer.prototype._init = function _init() {
var self = this; 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) { this.use(function(req, res, next, send) {
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true'); 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) { NodeServer.prototype.listen = function listen(port, host, callback) {
var self = this; var self = this;
return this.server.listen(port, host, function(err) { return this.server.listen(port, host, function(err, address) {
if (err) { if (err) {
if (callback) if (callback)
return callback(err); return callback(err);
return self.emit('error', err); return self.emit('error', err);
} }
bcoin.debug('Listening - host=%s port=%d',
address.address, address.port);
self.loaded = true; self.loaded = true;
self.emit('open'); self.emit('open');
@ -643,4 +653,5 @@ NodeServer.prototype.listen = function listen(port, host, callback) {
* Expose * Expose
*/ */
module.exports = NodeServer; return NodeServer;
};

View File

@ -1,10 +1,12 @@
/** /**
* input.js - input object for bcoin * input.js - input object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -283,4 +285,5 @@ Input.isInput = function isInput(obj) {
* Expose * Expose
*/ */
module.exports = Input; return Input;
};

View File

@ -1,10 +1,12 @@
/** /**
* keypair.js - keypair object for bcoin * keypair.js - keypair object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -183,4 +185,5 @@ KeyPair.fromJSON = function fromJSON(json, passphrase) {
* Expose * Expose
*/ */
module.exports = KeyPair; return KeyPair;
};

View File

@ -1,14 +1,17 @@
/** /**
* ldb.js - global ldb tracker * ldb.js - global ldb tracker
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var db = {};
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var utils = bcoin.utils; var utils = bcoin.utils;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var db = {};
/** /**
* LDB * LDB
@ -206,9 +209,10 @@ LowlevelUp.prototype.approximateSize = function approximateSize(start, end, call
* Expose * Expose
*/ */
exports = ldb; var exports = ldb;
exports.LowlevelUp = LowlevelUp; exports.LowlevelUp = LowlevelUp;
exports.destroy = destroy; exports.destroy = destroy;
exports.repair = repair; exports.repair = repair;
module.exports = exports; return exports;
};

View File

@ -1,6 +1,7 @@
/** /**
* locker.js - lock and queue for bcoin * locker.js - lock and queue for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
@ -103,7 +104,7 @@ Locker.prototype.purgePending = function purgePending() {
assert(this.add); assert(this.add);
utils.debug('Warning: %dmb of pending objects. Purging.', bcoin.debug('Warning: %dmb of pending objects. Purging.',
utils.mb(this.pendingSize)); utils.mb(this.pendingSize));
this.pending.forEach(function(obj) { this.pending.forEach(function(obj) {

View File

@ -1,6 +1,7 @@
/** /**
* lru.js - LRU cache for bcoin * lru.js - LRU cache for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,12 +1,14 @@
/** /**
* mempool.js - mempool for bcoin * mempool.js - mempool for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var bn = require('bn.js'); var bn = require('bn.js');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -427,7 +429,7 @@ Mempool.prototype.addTX = function addTX(tx, callback, force) {
'mempool full', 'mempool full',
0)); 0));
} }
utils.debug('Added orphan %s to mempool.', tx.rhash); bcoin.debug('Added orphan %s to mempool.', tx.rhash);
return self.storeOrphan(tx, callback); return self.storeOrphan(tx, callback);
} }
@ -465,7 +467,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) {
self.emit('tx', tx); self.emit('tx', tx);
self.emit('add 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) { self.resolveOrphans(tx, function(err, resolved) {
if (err) if (err)
@ -475,7 +477,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) {
self.verify(tx, function(err) { self.verify(tx, function(err) {
if (err) { if (err) {
if (err.type === 'VerifyError') { if (err.type === 'VerifyError') {
utils.debug('Could not resolved orphan %s: %s.', bcoin.debug('Could not resolved orphan %s: %s.',
tx.rhash, tx.rhash,
err.message); err.message);
return next(); return next();
@ -488,7 +490,7 @@ Mempool.prototype.addUnchecked = function addUnchecked(tx, callback) {
self.emit('error', err); self.emit('error', err);
return next(); return next();
} }
utils.debug('Resolved orphan %s in mempool.', tx.rhash); bcoin.debug('Resolved orphan %s in mempool.', tx.rhash);
next(); next();
}); });
}); });
@ -1221,4 +1223,5 @@ Mempool.prototype._removeUnchecked = function removeUnchecked(hash, callback, fo
* Expose * Expose
*/ */
module.exports = Mempool; return Mempool;
};

View File

@ -1,10 +1,12 @@
/** /**
* merkleblock.js - merkleblock object for bcoin * merkleblock.js - merkleblock object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
/** /**
@ -280,4 +282,5 @@ MerkleBlock.fromBlock = function fromBlock(block, bloom) {
* Expose * Expose
*/ */
module.exports = MerkleBlock; return MerkleBlock;
};

View File

@ -1,10 +1,12 @@
/** /**
* miner.js - inefficient miner for bcoin (because we can) * miner.js - inefficient miner for bcoin (because we can)
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -86,16 +88,16 @@ Miner.prototype._init = function _init() {
}); });
this.on('block', function(block) { this.on('block', function(block) {
utils.debug( bcoin.debug(
'Found block: %d (%s)', 'Found block: %d (%s)',
block.height, block.height,
block.hash('hex')); block.hash('hex'));
// Emit the block hex as a failsafe (in case we can't send it) // 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) { this.on('status', function(stat) {
utils.debug( bcoin.debug(
'hashrate=%dkhs hashes=%d target=%d height=%d best=%s', 'hashrate=%dkhs hashes=%d target=%d height=%d best=%s',
stat.hashrate / 1000 | 0, stat.hashrate / 1000 | 0,
stat.hashes, stat.hashes,
@ -144,7 +146,7 @@ Miner.prototype.start = function start() {
self.chain.add(block, function(err) { self.chain.add(block, function(err) {
if (err) { if (err) {
if (err.type === 'VerifyError') 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); self.emit('error', err);
return self.start(); return self.start();
} }
@ -504,6 +506,7 @@ function rcmp(a, b) {
* Expose * Expose
*/ */
exports = Miner; var exports = Miner;
exports.minerblock = MinerBlock; exports.minerblock = MinerBlock;
module.exports = exports; return exports;
};

View File

@ -1,12 +1,13 @@
/** /**
* mtx.js - mutable transaction object for bcoin * mtx.js - mutable transaction object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * 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 utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -1123,4 +1124,5 @@ MTX.isMTX = function isMTX(obj) {
* Expose * Expose
*/ */
module.exports = MTX; return MTX;
};

View File

@ -1,11 +1,13 @@
/** /**
* node.js - node object for bcoin * node.js - node object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
var utils = require('./utils'); var utils = require('./utils');
@ -24,15 +26,6 @@ function Node(options) {
this.options = 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.network = network;
this.mempool = null; this.mempool = null;
this.pool = null; this.pool = null;
@ -47,4 +40,5 @@ utils.inherits(Node, EventEmitter);
* Expose * Expose
*/ */
module.exports = Node; return Node;
};

View File

@ -1,11 +1,13 @@
/** /**
* output.js - output object for bcoin * output.js - output object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -148,4 +150,5 @@ Output.isOutput = function isOutput(obj) {
* Expose * Expose
*/ */
module.exports = Output; return Output;
};

View File

@ -1,12 +1,14 @@
/** /**
* peer.js - peer object for bcoin * peer.js - peer object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var bn = require('bn.js'); var bn = require('bn.js');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -142,7 +144,7 @@ Peer.prototype._init = function init() {
}); });
this.parser.on('error', function(err) { this.parser.on('error', function(err) {
utils.debug(err.stack + ''); bcoin.debug(err.stack + '');
self.sendReject(null, 'malformed', 'error parsing message', 100); self.sendReject(null, 'malformed', 'error parsing message', 100);
self._error(err); self._error(err);
// Something is wrong here. // Something is wrong here.
@ -211,12 +213,12 @@ Peer.prototype.createSocket = function createSocket(port, host) {
socket = net.connect(port, host); socket = net.connect(port, host);
} }
utils.debug( bcoin.debug(
'Connecting to %s:%d (priority=%s)', 'Connecting to %s:%d (priority=%s)',
host, port, this.priority); host, port, this.priority);
socket.on('connect', function() { socket.on('connect', function() {
utils.debug( bcoin.debug(
'Connected to %s:%d (priority=%s)', 'Connected to %s:%d (priority=%s)',
host, port, self.priority); host, port, self.priority);
}); });
@ -512,7 +514,7 @@ Peer.prototype._onPacket = function onPacket(packet) {
this._emit(cmd, payload); this._emit(cmd, payload);
break; break;
default: default:
utils.debug('Unknown packet: %s', cmd); bcoin.debug('Unknown packet: %s', cmd);
this._emit(cmd, payload); this._emit(cmd, payload);
break; break;
} }
@ -555,7 +557,7 @@ Peer.prototype._handleUTXOs = function _handleUTXOs(payload) {
payload.coins = payload.coins(function(coin) { payload.coins = payload.coins(function(coin) {
return new bcoin.coin(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); this._emit('utxos', payload);
}; };
@ -894,7 +896,7 @@ Peer.prototype._handleMempool = function _handleMempool() {
for (i = 0; i < hashes.length; i++) for (i = 0; i < hashes.length; i++)
items.push({ type: constants.inv.tx, hash: hashes[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)); self._write(self.framer.inv(items));
}); });
@ -923,13 +925,13 @@ Peer.prototype._handleGetData = function handleGetData(items) {
} }
if ((item.type & ~constants.invWitnessMask) !== entry.type) { if ((item.type & ~constants.invWitnessMask) !== entry.type) {
utils.debug( bcoin.debug(
'Peer %s requested an existing item with the wrong type.', 'Peer %s requested an existing item with the wrong type.',
this.host); this.host);
continue; continue;
} }
utils.debug( bcoin.debug(
'Peer %s requested %s:%s as a %s packet.', 'Peer %s requested %s:%s as a %s packet.',
this.host, this.host,
entry.packetType, entry.packetType,
@ -1064,7 +1066,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
if (err) if (err)
self.emit('error', err); self.emit('error', err);
utils.debug( bcoin.debug(
'Served %d items to %s with getdata (notfound=%d).', 'Served %d items to %s with getdata (notfound=%d).',
items.length - notfound.length, items.length - notfound.length,
self.host, self.host,
@ -1104,7 +1106,7 @@ Peer.prototype._handleAddr = function handleAddr(addrs) {
}); });
} }
utils.debug( bcoin.debug(
'Recieved %d peers (seeds=%d, peers=%d).', 'Recieved %d peers (seeds=%d, peers=%d).',
addrs.length, addrs.length,
this.pool.seeds.length, this.pool.seeds.length,
@ -1217,9 +1219,9 @@ Peer.prototype._handleAlert = function handleAlert(details) {
var signature = details.signature; var signature = details.signature;
if (!bcoin.ec.verify(hash, signature, network.alertKey)) { 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? // Let's look at it because why not?
utils.debug(details); bcoin.debug(details);
this.setMisbehavior(100); this.setMisbehavior(100);
return; return;
} }
@ -1228,11 +1230,11 @@ Peer.prototype._handleAlert = function handleAlert(details) {
}; };
Peer.prototype.getHeaders = function getHeaders(locator, stop) { Peer.prototype.getHeaders = function getHeaders(locator, stop) {
utils.debug( bcoin.debug(
'Requesting headers packet from %s with getheaders', 'Requesting headers packet from %s with getheaders',
this.host); 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 ? this.chain._getCachedHeight(locator[0]) : null,
locator && locator.length ? utils.revHex(locator[0]) : 0, locator && locator.length ? utils.revHex(locator[0]) : 0,
stop ? utils.revHex(stop) : 0); stop ? utils.revHex(stop) : 0);
@ -1241,11 +1243,11 @@ Peer.prototype.getHeaders = function getHeaders(locator, stop) {
}; };
Peer.prototype.getBlocks = function getBlocks(locator, stop) { Peer.prototype.getBlocks = function getBlocks(locator, stop) {
utils.debug( bcoin.debug(
'Requesting inv packet from %s with getblocks', 'Requesting inv packet from %s with getblocks',
this.host); 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 ? this.chain._getCachedHeight(locator[0]) : null,
locator && locator.length ? utils.revHex(locator[0]) : 0, locator && locator.length ? utils.revHex(locator[0]) : 0,
stop ? utils.revHex(stop) : 0); stop ? utils.revHex(stop) : 0);
@ -1254,7 +1256,7 @@ Peer.prototype.getBlocks = function getBlocks(locator, stop) {
}; };
Peer.prototype.getMempool = function getMempool() { Peer.prototype.getMempool = function getMempool() {
utils.debug( bcoin.debug(
'Requesting inv packet from %s with mempool', 'Requesting inv packet from %s with mempool',
this.host); this.host);
@ -1262,7 +1264,7 @@ Peer.prototype.getMempool = function getMempool() {
}; };
Peer.prototype.reject = function reject(details) { Peer.prototype.reject = function reject(details) {
utils.debug( bcoin.debug(
'Sending reject packet to %s', 'Sending reject packet to %s',
this.host); this.host);
@ -1285,4 +1287,5 @@ Peer.prototype.sendReject = function sendReject(obj, code, reason, score) {
* Expose * Expose
*/ */
module.exports = Peer; return Peer;
};

View File

@ -1,12 +1,14 @@
/** /**
* pool.js - peer management for bcoin * pool.js - peer management for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var network = bcoin.protocol.network; var network = bcoin.protocol.network;
@ -228,7 +230,7 @@ Pool.prototype._init = function _init() {
self.getMempool(); self.getMempool();
self.synced = true; self.synced = true;
self.emit('full'); 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) { (this.options.wallets || []).forEach(function(wallet) {
@ -264,19 +266,19 @@ Pool.prototype.resolveOrphan = function resolveOrphan(peer, top, orphan, callbac
// Was probably resolved. // Was probably resolved.
if (!orphan) { if (!orphan) {
utils.debug('Orphan root was already resolved.'); bcoin.debug('Orphan root was already resolved.');
return callback(); return callback();
} }
// If we're already processing the block // If we're already processing the block
// that would resolve this, ignore. // that would resolve this, ignore.
// if (self.request.map[orphan.soil]) { // if (self.request.map[orphan.soil]) {
// utils.debug('Already requested orphan "soil".'); // bcoin.debug('Already requested orphan "soil".');
// return callback(); // return callback();
// } // }
// if (self.chain.hasPending(orphan.soil)) { // if (self.chain.hasPending(orphan.soil)) {
// utils.debug('Already processing orphan "soil".'); // bcoin.debug('Already processing orphan "soil".');
// return callback(); // return callback();
// } // }
@ -323,7 +325,7 @@ Pool.prototype.startServer = function startServer(callback) {
this.server.on('listening', function() { this.server.on('listening', function() {
var data = self.server.address(); var data = self.server.address();
utils.debug( bcoin.debug(
'Bitcoin server listening on %s (port=%d)', 'Bitcoin server listening on %s (port=%d)',
data.address, data.port); data.address, data.port);
}); });
@ -359,7 +361,7 @@ Pool.prototype._startTimer = function _startTimer() {
if (self.peers.load) { if (self.peers.load) {
self.peers.load.destroy(); 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()) if (self.chain.isFull())
return; return;
utils.debug('Stall recovery: loading again.'); bcoin.debug('Stall recovery: loading again.');
// self._load(); // self._load();
} }
@ -422,7 +424,7 @@ Pool.prototype._addLoader = function _addLoader() {
assert(peer); assert(peer);
utils.debug('Added loader peer: %s', peer.host); bcoin.debug('Added loader peer: %s', peer.host);
this.peers.load = peer; this.peers.load = peer;
this.peers.all.push(peer); this.peers.all.push(peer);
@ -553,7 +555,7 @@ Pool.prototype._handleHeaders = function _handleHeaders(headers, peer, callback)
if (headers.length === 0) if (headers.length === 0)
return callback(); return callback();
utils.debug( bcoin.debug(
'Recieved %s headers from %s', 'Recieved %s headers from %s',
headers.length, headers.length,
peer.host); peer.host);
@ -611,7 +613,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer, callback) {
if (hashes.length === 0) if (hashes.length === 0)
return callback(); return callback();
utils.debug( bcoin.debug(
'Recieved %s block hashes from %s', 'Recieved %s block hashes from %s',
hashes.length, hashes.length,
peer.host); peer.host);
@ -636,7 +638,7 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer, callback) {
// Resolve orphan chain. // Resolve orphan chain.
if (self.chain.hasOrphan(hash)) { 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); self.resolveOrphan(peer, null, hash, next);
return; return;
} }
@ -712,7 +714,7 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer, callback) {
// Someone is sending us blocks without // Someone is sending us blocks without
// us requesting them. // us requesting them.
if (!requested) { if (!requested) {
utils.debug( bcoin.debug(
'Recieved unrequested block: %s (%s)', 'Recieved unrequested block: %s (%s)',
block.rhash, peer.host); block.rhash, peer.host);
return callback(); return callback();
@ -745,7 +747,7 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer, callback) {
self.emit('chain-progress', self.chain.getProgress(), peer); self.emit('chain-progress', self.chain.getProgress(), peer);
if (self.chain.total % 20 === 0) { if (self.chain.total % 20 === 0) {
utils.debug( bcoin.debug(
'Status: tip=%s ts=%s height=%d blocks=%d orphans=%d active=%d' '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', + ' queue=%d target=%s peers=%d pending=%d highest=%d jobs=%d',
block.rhash, block.rhash,
@ -815,7 +817,7 @@ Pool.prototype._createPeer = function _createPeer(options) {
? utils.revHex(utils.toHex(payload.data)) ? utils.revHex(utils.toHex(payload.data))
: null; : null;
utils.debug( bcoin.debug(
'Reject (%s): msg=%s ccode=%s reason=%s data=%s', 'Reject (%s): msg=%s ccode=%s reason=%s data=%s',
peer.host, peer.host,
payload.message, payload.message,
@ -827,8 +829,8 @@ Pool.prototype._createPeer = function _createPeer(options) {
}); });
peer.on('alert', function(payload) { peer.on('alert', function(payload) {
utils.debug('Received alert from: %s', peer.host); bcoin.debug('Received alert from: %s', peer.host);
utils.debug(payload); bcoin.debug(payload);
self.emit('alert', payload, peer); self.emit('alert', payload, peer);
}); });
@ -887,7 +889,7 @@ Pool.prototype._createPeer = function _createPeer(options) {
if (version.height > self.block.versionHeight) if (version.height > self.block.versionHeight)
self.block.versionHeight = version.height; self.block.versionHeight = version.height;
utils.debug( bcoin.debug(
'Received version from %s: version=%d height=%d agent=%s', 'Received version from %s: version=%d height=%d agent=%s',
peer.host, version.version, version.height, version.agent); peer.host, version.version, version.height, version.agent);
@ -1153,7 +1155,7 @@ Pool.prototype._removePeer = function _removePeer(peer) {
this.peers.all.splice(i, 1); this.peers.all.splice(i, 1);
if (this.peers.load === peer) { 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; this.peers.load = null;
} }
}; };
@ -1300,12 +1302,12 @@ Pool.prototype.searchWallet = function(wallet, callback) {
self.chain.reset(height, function(err) { self.chain.reset(height, function(err) {
if (err) { if (err) {
utils.debug('Failed to reset height: %s', err.stack + ''); bcoin.debug('Failed to reset height: %s', err.stack + '');
return callback(err); return callback(err);
} }
utils.debug('Wallet height: %s', height); bcoin.debug('Wallet height: %s', height);
utils.debug( bcoin.debug(
'Reverted chain to height=%d (%s)', 'Reverted chain to height=%d (%s)',
self.chain.height, self.chain.height,
new Date(self.chain.tip.ts * 1000) new Date(self.chain.tip.ts * 1000)
@ -1322,12 +1324,12 @@ Pool.prototype.searchWallet = function(wallet, callback) {
self.chain.resetTime(ts, function(err) { self.chain.resetTime(ts, function(err) {
if (err) { if (err) {
utils.debug('Failed to reset time: %s', err.stack + ''); bcoin.debug('Failed to reset time: %s', err.stack + '');
return callback(err); return callback(err);
} }
utils.debug('Wallet time: %s', new Date(ts * 1000)); bcoin.debug('Wallet time: %s', new Date(ts * 1000));
utils.debug( bcoin.debug(
'Reverted chain to height=%d (%s)', 'Reverted chain to height=%d (%s)',
self.chain.height, self.chain.height,
new Date(self.chain.tip.ts * 1000) 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 (type === self.tx.type) {
if (peer.queue.tx.length === 0) { if (peer.queue.tx.length === 0) {
utils.nextTick(function() { utils.nextTick(function() {
utils.debug( bcoin.debug(
'Requesting %d/%d txs from %s with getdata', 'Requesting %d/%d txs from %s with getdata',
peer.queue.tx.length, peer.queue.tx.length,
self.request.activeTX, self.request.activeTX,
@ -1513,7 +1515,7 @@ Pool.prototype._sendRequests = function _sendRequests(peer) {
return item.start(); return item.start();
}); });
utils.debug( bcoin.debug(
'Requesting %d/%d blocks from %s with getdata', 'Requesting %d/%d blocks from %s with getdata',
items.length, items.length,
this.request.activeBlocks, this.request.activeBlocks,
@ -1880,7 +1882,7 @@ Pool.prototype.setMisbehavior = function setMisbehavior(peer, score) {
if (peer.banScore >= constants.banScore) { if (peer.banScore >= constants.banScore) {
this.peers.misbehaving[peer.host] = utils.now(); 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(); peer.destroy();
return true; return true;
} }
@ -1912,7 +1914,7 @@ Pool.prototype.isMisbehaving = function isMisbehaving(host) {
Pool.prototype.reject = function reject(peer, obj, code, reason, score) { Pool.prototype.reject = function reject(peer, obj, code, reason, score) {
if (obj) { 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); obj.type, obj.hash('hex'), peer.host, code, reason);
peer.reject({ peer.reject({
@ -1921,7 +1923,7 @@ Pool.prototype.reject = function reject(peer, obj, code, reason, score) {
data: obj.hash() data: obj.hash()
}); });
} else { } 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.host, code, reason);
peer.reject({ peer.reject({
@ -2002,4 +2004,5 @@ LoadRequest.prototype.finish = function finish() {
* Expose * Expose
*/ */
module.exports = Pool; return Pool;
};

View File

@ -1,10 +1,14 @@
/** /**
* profiler.js - profiler for bcoin * profiler.js - profiler for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var exports = {};
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var fs, profiler; var fs, profiler;
@ -16,7 +20,7 @@ if (bcoin.profile && !bcoin.isBrowser) {
if (profiler) { if (profiler) {
utils.nextTick(function() { 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) { function Profile(name) {
if (profiler) { if (profiler) {
name = 'profile-' + (name ? name + '-' : '') + Profile.uid++; 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.profile = profiler.startProfiling(name, true);
this.name = name; this.name = name;
} }
@ -63,7 +67,7 @@ Profile.prototype.save = function save(callback) {
assert(this.profile); 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) { return this.profile['export'](function(err, result) {
var file; var file;
@ -87,7 +91,7 @@ Profile.prototype.save = function save(callback) {
function Snapshot(name) { function Snapshot(name) {
if (profiler) { if (profiler) {
name = 'snapshot-' + (name ? name + '-' : '') + Snapshot.uid++; 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.snapshot = profiler.takeSnapshot(name);
this.name = name; this.name = name;
} }
@ -132,7 +136,7 @@ Snapshot.prototype.save = function save(callback) {
assert(this.snapshot); 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) { return this.snapshot['export'](function(err, result) {
var file; var file;
@ -171,7 +175,7 @@ exports.snapshot = function snapshot(name, callback) {
if (bcoin.debugLogs) { if (bcoin.debugLogs) {
mem = process.memoryUsage(); 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.rss),
utils.mb(mem.heapUsed), utils.mb(mem.heapUsed),
utils.mb(mem.heapTotal), utils.mb(mem.heapTotal),
@ -184,3 +188,6 @@ exports.snapshot = function snapshot(name, callback) {
snapshot = new Snapshot(name); snapshot = new Snapshot(name);
snapshot.save(callback); snapshot.save(callback);
}; };
return exports;
};

View File

@ -1,6 +1,7 @@
/** /**
* constants.js - bitcoin constants for bcoin * constants.js - bitcoin constants for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,11 +1,13 @@
/** /**
* framer.js - packet framer for bcoin * framer.js - packet framer for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../../bcoin'); module.exports = function(bcoin) {
var network = require('./network');
var network = bcoin.protocol.network;
var constants = require('./constants'); var constants = require('./constants');
var utils = require('../utils'); var utils = require('../utils');
var assert = utils.assert; var assert = utils.assert;
@ -937,4 +939,5 @@ Framer.tx.virtualSize = function txVirtualSize(tx) {
* Expose * Expose
*/ */
module.exports = Framer; return Framer;
};

View File

@ -1,12 +1,17 @@
/** /**
* protocol/index.js - bitcoin protocol for bcoin * protocol/index.js - bitcoin protocol for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var protocol = exports; module.exports = function(bcoin) {
bcoin.protocol = {};
protocol.constants = require('./constants'); bcoin.protocol.constants = require('./constants');
protocol.framer = require('./framer'); bcoin.protocol.network = require('./network').get(bcoin.networkType);
protocol.parser = require('./parser'); bcoin.protocol.framer = require('./framer')(bcoin);
protocol.network = require('./network'); bcoin.protocol.parser = require('./parser')(bcoin);
return bcoin.protocol;
};

View File

@ -1,11 +1,13 @@
/** /**
* network.js - bitcoin networks for bcoin * network.js - bitcoin networks for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bn = require('bn.js'); var bn = require('bn.js');
var utils = require('../utils'); var utils = require('../utils');
var assert = utils.assert;
/** /**
* Network * Network
@ -14,13 +16,13 @@ var utils = require('../utils');
var network = exports; var network = exports;
var main, testnet, regtest, segnet3, segnet4; 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.types = ['main', 'testnet', 'regtest', 'segnet3', 'segnet4'];
network.get = function get(type) {
assert(network[type], 'Network not found.');
return utils.merge({}, network, network[type]);
};
/** /**
* Main * Main
*/ */
@ -145,7 +147,7 @@ main.deployments = {
timeout: 1491004800 // April 1st, 2017 timeout: 1491004800 // April 1st, 2017
} }
// bip109: { // bip109: {
// bit: 28, // bit: 4,
// startTime: 1453939200, // Jan 28th, 2016 // startTime: 1453939200, // Jan 28th, 2016
// timeout: 1514764800 // Jan 1st, 2018 // timeout: 1514764800 // Jan 1st, 2018
// } // }
@ -494,7 +496,7 @@ segnet4.deployments = utils.merge({}, main.deployments, {
timeout: 999999999999 timeout: 999999999999
} }
// bip109: { // bip109: {
// bit: 28, // bit: 4,
// startTime: 1453939200, // Jan 28th, 2016 // startTime: 1453939200, // Jan 28th, 2016
// timeout: 1514764800 // Jan 1st, 2018 // timeout: 1514764800 // Jan 1st, 2018
// } // }
@ -514,6 +516,10 @@ segnet4.genesis = {
segnet4.genesisBlock = '0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a7d719856ffff011e000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000'; segnet4.genesisBlock = '0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a7d719856ffff011e000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4d04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73ffffffff0100f2052a01000000434104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac00000000';
/**
* Global
*/
network.xprivkeys = { network.xprivkeys = {
'76066276': 'main', '76066276': 'main',
'70615956': 'testnet', '70615956': 'testnet',

View File

@ -1,15 +1,17 @@
/** /**
* parser.js - packet parser for bcoin * parser.js - packet parser for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../../bcoin');
var utils = require('../utils'); var utils = require('../utils');
var assert = utils.assert; var assert = utils.assert;
var constants = require('./constants'); var constants = require('./constants');
var network = require('./network'); var network = bcoin.protocol.network;
var BufferReader = require('../reader'); var BufferReader = require('../reader');
/** /**
@ -256,7 +258,7 @@ Parser.prototype.parsePayload = function parsePayload(cmd, p) {
case 'utxos': case 'utxos':
return Parser.parseUTXOs(p); return Parser.parseUTXOs(p);
default: default:
utils.debug('Unknown packet: %s', cmd); bcoin.debug('Unknown packet: %s', cmd);
return p; return p;
} }
}; };
@ -1010,4 +1012,5 @@ Parser.parseAlert = function parseAlert(p) {
* Expose * Expose
*/ */
module.exports = Parser; return Parser;
};

View File

@ -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;

View File

@ -1,6 +1,7 @@
/** /**
* reader.js - buffer reader for bcoin * reader.js - buffer reader for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */

View File

@ -1,10 +1,12 @@
/** /**
* script.js - script interpreter for bcoin * script.js - script interpreter for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var utils = require('./utils'); 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); return this.interpret(stack, flags, tx, index, version);
} catch (e) { } catch (e) {
if (e.type === 'ScriptError') { if (e.type === 'ScriptError') {
utils.debug('Script error: %s.', e.message); bcoin.debug('Script error: %s.', e.message);
} else { } else {
utils.debug('Script interpreter threw:'); bcoin.debug('Script interpreter threw:');
utils.debug(e.stack + ''); bcoin.debug(e.stack + '');
} }
return false; return false;
} }
@ -2017,7 +2019,7 @@ Script.isValidKey = function isValidKey(key, flags) {
if (flags & constants.flags.VERIFY_STRICTENC) { if (flags & constants.flags.VERIFY_STRICTENC) {
if (!Script.isKeyEncoding(key)) { if (!Script.isKeyEncoding(key)) {
utils.debug('Script failed key encoding test.'); bcoin.debug('Script failed key encoding test.');
return false; return false;
} }
} }
@ -2060,21 +2062,21 @@ Script.isValidSignature = function isValidSignature(sig, flags) {
|| (flags & constants.flags.VERIFY_LOW_S) || (flags & constants.flags.VERIFY_LOW_S)
|| (flags & constants.flags.VERIFY_STRICTENC)) { || (flags & constants.flags.VERIFY_STRICTENC)) {
if (!Script.isSignatureEncoding(sig)) { 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; return false;
} }
} }
if (flags & constants.flags.VERIFY_LOW_S) { if (flags & constants.flags.VERIFY_LOW_S) {
if (!Script.isLowDER(sig)) { if (!Script.isLowDER(sig)) {
utils.debug('Script does not have a low DER.'); bcoin.debug('Script does not have a low DER.');
return false; return false;
} }
} }
if (flags & constants.flags.VERIFY_STRICTENC) { if (flags & constants.flags.VERIFY_STRICTENC) {
if (!Script.isHashType(sig)) { 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; return false;
} }
} }
@ -2527,12 +2529,12 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) {
// Failure on version=0 (bad program data length) // Failure on version=0 (bad program data length)
if (!program.type) { if (!program.type) {
utils.debug('Malformed witness program.'); bcoin.debug('Malformed witness program.');
return false; return false;
} }
if (program.version > 0) { 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 // Anyone can spend (we can return true here
// if we want to always relay these transactions). // if we want to always relay these transactions).
// Otherwise, if we want to act like an "old" // Otherwise, if we want to act like an "old"
@ -2822,4 +2824,5 @@ utils.inherits(ScriptError, Error);
Script.witness = Witness; Script.witness = Witness;
Script.stack = Stack; Script.stack = Stack;
Script.error = ScriptError; Script.error = ScriptError;
module.exports = Script; return Script;
};

View File

@ -1,10 +1,12 @@
/** /**
* spvnode.js - spv node for bcoin * spvnode.js - spv node for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -109,7 +111,7 @@ SPVNode.prototype._init = function _init() {
self.loaded = true; self.loaded = true;
self.emit('open'); self.emit('open');
utils.debug('Node is loaded.'); bcoin.debug('Node is loaded.');
} }
options = utils.merge({ options = utils.merge({
@ -191,7 +193,7 @@ SPVNode.prototype.createWallet = function createWallet(options, callback) {
assert(wallet); assert(wallet);
utils.debug('Loaded wallet with id=%s address=%s', bcoin.debug('Loaded wallet with id=%s address=%s',
wallet.id, wallet.getAddress()); wallet.id, wallet.getAddress());
self.pool.addWallet(wallet, function(err) { self.pool.addWallet(wallet, function(err) {
@ -211,4 +213,5 @@ SPVNode.prototype.getWallet = function getWallet(id, passphrase, callback) {
* Expose * Expose
*/ */
module.exports = SPVNode; return SPVNode;
};

View File

@ -1,12 +1,14 @@
/** /**
* tx.js - transaction object for bcoin * tx.js - transaction object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
@ -410,7 +412,7 @@ TX.prototype.verify = function verify(index, force, flags) {
continue; continue;
if (!input.coin) { 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; return false;
} }
@ -1402,4 +1404,5 @@ TX.isTX = function isTX(obj) {
* Expose * Expose
*/ */
module.exports = TX; return TX;
};

View File

@ -1,11 +1,13 @@
/** /**
* txdb.js - persistent transaction pool * txdb.js - persistent transaction pool
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = bcoin.utils.assert; var assert = bcoin.utils.assert;
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
@ -1666,4 +1668,5 @@ TXPool.prototype.zap = function zap(address, now, age, callback, force) {
* Expose * Expose
*/ */
module.exports = TXPool; return TXPool;
};

View File

@ -1,6 +1,7 @@
/** /**
* utils.js - utils for bcoin * utils.js - utils for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
@ -27,9 +28,6 @@ utils.nop = function() {};
utils.gc = !utils.isBrowser && typeof gc === 'function' ? gc : utils.nop; 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) { utils.slice = function slice(buf, start, end) {
var clone; var clone;
@ -713,9 +711,6 @@ utils.print = function print() {
return process.stdout.write(utils.format(args, true)); return process.stdout.write(utils.format(args, true));
}; };
utils.debug = utils.nop;
utils.ensurePrefix = utils.nop;
utils.merge = function merge(target) { utils.merge = function merge(target) {
var args = Array.prototype.slice.call(arguments, 1); var args = Array.prototype.slice.call(arguments, 1);
args.forEach(function(obj) { args.forEach(function(obj) {

View File

@ -1,10 +1,12 @@
/** /**
* wallet.js - wallet object for bcoin * wallet.js - wallet object for bcoin
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
@ -132,7 +134,7 @@ Wallet.prototype._init = function _init() {
this.provider.setID(this.id); this.provider.setID(this.id);
this.on('error', function(err) { 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) { this.provider.on('error', function(err) {
@ -1275,4 +1277,5 @@ Wallet.isWallet = function isWallet(obj) {
* Expose * Expose
*/ */
module.exports = Wallet; return Wallet;
};

View File

@ -1,12 +1,14 @@
/** /**
* walletdb.js - storage for wallets * walletdb.js - storage for wallets
* Copyright (c) 2014-2015, Fedor Indutny (MIT License) * Copyright (c) 2014-2015, Fedor Indutny (MIT License)
* Copyright (c) 2014-2016, Christopher Jeffrey (MIT License).
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
module.exports = function(bcoin) {
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var bcoin = require('../bcoin');
var utils = require('./utils'); var utils = require('./utils');
var assert = utils.assert; var assert = utils.assert;
var DUMMY = new Buffer([0]); var DUMMY = new Buffer([0]);
@ -794,4 +796,8 @@ Provider.prototype.zap = function zap(wallet, address) {
* Expose * Expose
*/ */
module.exports = WalletDB; WalletDB.Provider = Provider;
return WalletDB;
};

View File

@ -4,7 +4,8 @@
* https://github.com/indutny/bcoin * https://github.com/indutny/bcoin
*/ */
var bcoin = require('../bcoin'); module.exports = function(bcoin) {
var bn = require('bn.js'); var bn = require('bn.js');
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var utils = require('./utils'); var utils = require('./utils');
@ -12,7 +13,7 @@ var assert = utils.assert;
var BufferWriter = require('./writer'); var BufferWriter = require('./writer');
var BufferReader = require('./reader'); var BufferReader = require('./reader');
var cp = require('child_process'); var cp = require('child_process');
var workers = exports; var workers = {};
var HEADER_SIZE = 12; var HEADER_SIZE = 12;
@ -20,35 +21,36 @@ var HEADER_SIZE = 12;
* Master * Master
*/ */
workers.MAX_WORKERS = +process.env.BCOIN_WORKERS || 6; workers.MAX_WORKERS = bcoin.maxWorkers || 6;
workers.TIMEOUT = 10000; workers.TIMEOUT = bcoin.workerTimeout || 10000;
workers.children = {}; workers.children = {};
workers.uid = 0; workers.uid = 0;
workers.spawn = function spawn(index) { workers.spawn = function spawn(index) {
var child; var child;
utils.debug('Spawning worker process: %d', index); bcoin.debug('Spawning worker process: %d', index);
child = cp.spawn(process.argv[0], [__filename], { child = cp.spawn(process.argv[0], [__filename], {
stdio: ['pipe', 'pipe', 'inherit'], stdio: ['pipe', 'pipe', 'inherit'],
env: utils.merge({}, process.env, { 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) { 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) { 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) if (workers.children[index] === child)
delete workers.children[index]; delete workers.children[index];
}); });
child.on('close', function() { child.on('close', function() {
utils.debug('Worker %d closed', index); bcoin.debug('Worker %d closed', index);
if (workers.children[index] === child) if (workers.children[index] === child)
delete workers.children[index]; delete workers.children[index];
}); });
@ -141,7 +143,6 @@ workers.listen = function listen() {
return console.error.apply(console.error, arguments); return console.error.apply(console.error, arguments);
}; };
utils.debug = bcoin.debug;
utils.print = bcoin.debug; utils.print = bcoin.debug;
process.stdin.on('data', parser(function(id, body) { process.stdin.on('data', parser(function(id, body) {
@ -150,7 +151,7 @@ workers.listen = function listen() {
try { try {
res = workers[body.name].apply(workers[body.name], body.items); res = workers[body.name].apply(workers[body.name], body.items);
} catch (e) { } catch (e) {
utils.debug(e.stack + ''); bcoin.debug(e.stack + '');
return process.stdout.write(createPacket(id, null, [{ return process.stdout.write(createPacket(id, null, [{
message: e.message, message: e.message,
stack: e.stack + '' stack: e.stack + ''
@ -182,7 +183,7 @@ workers.mine = function mine(attempt) {
dsha256: utils.dsha256 dsha256: utils.dsha256
}); });
attempt.on('status', function(stat) { attempt.on('status', function(stat) {
utils.debug( bcoin.debug(
'hashrate=%dkhs hashes=%d target=%d height=%d best=%s', 'hashrate=%dkhs hashes=%d target=%d height=%d best=%s',
stat.hashrate / 1000 | 0, stat.hashrate / 1000 | 0,
stat.hashes, stat.hashes,
@ -377,7 +378,7 @@ function parser(onPacket) {
buf = []; buf = [];
waiting = HEADER_SIZE; waiting = HEADER_SIZE;
read = 0; read = 0;
utils.debug('Bad magic number: %d', header.magic); bcoin.debug('Bad magic number: %d', header.magic);
return; return;
} }
@ -394,7 +395,7 @@ function parser(onPacket) {
try { try {
packet = parseBody(packet); packet = parseBody(packet);
} catch (e) { } catch (e) {
utils.debug(e.stack + ''); bcoin.debug(e.stack + '');
return; return;
} }
@ -410,5 +411,10 @@ function parser(onPacket) {
}; };
} }
if (process.env.BCOIN_WORKER_ID) return workers;
workers.listen(); };
if (process.env.BCOIN_WORKER_ID) {
var env = require('./env')(JSON.parse(process.env.BCOIN_WORKER_OPTIONS));
env.workers.listen();
}

View File

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
describe('Block', function() { describe('Block', function() {
var parser = bcoin.protocol.parser; var parser = bcoin.protocol.parser;

View File

@ -1,5 +1,5 @@
var assert = require('assert'); var assert = require('assert');
var bcoin = require('../'); var bcoin = require('../')();
describe('Bloom', function() { describe('Bloom', function() {
it('should do proper murmur3', function() { it('should do proper murmur3', function() {

View File

@ -1,6 +1,6 @@
// var assert = require('assert'); // var assert = require('assert');
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;

View File

@ -1,5 +1,5 @@
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;

View File

@ -1,5 +1,5 @@
var assert = require('assert'); var assert = require('assert');
var bcoin = require('../'); var bcoin = require('../')();
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var utils = bcoin.utils; var utils = bcoin.utils;

View File

@ -1,5 +1,5 @@
var assert = require('assert'); var assert = require('assert');
var bcoin = require('../'); var bcoin = require('../')();
var Script = bcoin.script; var Script = bcoin.script;
var Stack = bcoin.script.stack; var Stack = bcoin.script.stack;
var opcodes = bcoin.protocol.constants.opcodes; var opcodes = bcoin.protocol.constants.opcodes;

View File

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
describe('TX', function() { describe('TX', function() {
var parser = bcoin.protocol.parser; var parser = bcoin.protocol.parser;

View File

@ -1,6 +1,6 @@
var assert = require('assert'); var assert = require('assert');
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
var utils = bcoin.utils; var utils = bcoin.utils;
describe('Utils', function() { describe('Utils', function() {

View File

@ -1,5 +1,5 @@
var bn = require('bn.js'); var bn = require('bn.js');
var bcoin = require('../'); var bcoin = require('../')();
var constants = bcoin.protocol.constants; var constants = bcoin.protocol.constants;
var utils = bcoin.utils; var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;