diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 00000000..51cb648c --- /dev/null +++ b/.jshintrc @@ -0,0 +1,41 @@ +{ + "bitwise": false, + "curly": false, + "eqeqeq": true, + "freeze": true, + "latedef": "nofunc", + "maxparams": 7, + "noarg": true, + "shadow": "inner", + "undef": true, + "unused": true, + + "boss": true, + "expr": true, + "eqnull": true, + "evil": true, + "loopfunc": true, + "proto": true, + "supernew": true, + + "-W018": true, + "-W064": true, + "-W086": true, + "+W032": true, + + "browser": false, + "browserify": false, + "node": true, + "nonstandard": true, + "typed": true, + "worker": false, + + "camelcase": false, + "indent": 2, + "maxlen": 110, + "newcap": true, + "quotmark": "single", + + "laxbreak": true, + "laxcomma": true +} diff --git a/lib/bcoin.js b/lib/bcoin.js index 354cca9c..2f328386 100644 --- a/lib/bcoin.js +++ b/lib/bcoin.js @@ -5,14 +5,15 @@ */ var bcoin = exports; -var assert = require('assert'); +var utils = require('./bcoin/utils'); +var assert = utils.assert; bcoin.isBrowser = (typeof process !== 'undefined' && process.browser) || typeof window !== 'undefined'; bcoin.prefix = process.env.BCOIN_PREFIX || process.env.HOME + '/.bcoin'; -bcoin.debug = +process.env.BCOIN_DEBUG === 1; +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; @@ -47,6 +48,26 @@ bcoin.rimraf = function rimraf(file) { bcoin.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.fs) { + if (!bcoin._debug) { + bcoin.ensurePrefix(); + bcoin._debug = bcoin.fs.createWriteStream( + bcoin.prefix + '/debug.log', { flags: 'a' }); + } + msg = utils.format(args, false); + bcoin._debug.write(process.pid + ': ' + msg); + } +}; + bcoin.bn = require('bn.js'); bcoin.elliptic = require('elliptic'); @@ -58,8 +79,7 @@ if (!bcoin.isBrowser) { try { bcoin.secp256k1 = require('secp' + '256k1'); } catch (e) { - utils.debug('Warning: secp256k1 not found.' - + ' Full block validation will be slow.'); + ; } } else { bcoin.hash = require('hash.js'); @@ -71,7 +91,8 @@ bcoin.ecdsa.signature = require('elliptic/lib/elliptic/ec/signature'); assert(!bcoin.ecdsa.keypair); bcoin.ecdsa.keypair = require('elliptic/lib/elliptic/ec/key'); -bcoin.utils = require('./bcoin/utils'); +bcoin.utils = utils; +bcoin.utils.debug = bcoin.debug; bcoin.profiler = require('./bcoin/profiler'); bcoin.ec = require('./bcoin/ec'); bcoin.lru = require('./bcoin/lru'); diff --git a/lib/bcoin/abstractblock.js b/lib/bcoin/abstractblock.js index 416860b3..83399b0b 100644 --- a/lib/bcoin/abstractblock.js +++ b/lib/bcoin/abstractblock.js @@ -5,7 +5,6 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -16,8 +15,6 @@ var network = bcoin.protocol.network; */ function AbstractBlock(data) { - var self = this; - if (!(this instanceof AbstractBlock)) return new AbstractBlock(data); diff --git a/lib/bcoin/address.js b/lib/bcoin/address.js index 23c6f18e..9f848a9e 100644 --- a/lib/bcoin/address.js +++ b/lib/bcoin/address.js @@ -5,8 +5,6 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); -var EventEmitter = require('events').EventEmitter; var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -23,8 +21,6 @@ function Address(options) { if (options instanceof Address) return options; - EventEmitter.call(this); - if (!options) options = {}; @@ -59,8 +55,6 @@ function Address(options) { }, this); } -utils.inherits(Address, EventEmitter); - Address.prototype.getID = function getID() { return this.getKeyAddress(); }; diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index a5e5fecd..43a1b74a 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -366,9 +366,9 @@ Block.prototype.toCompact = function toCompact() { }; Block.fromCompact = function fromCompact(buf) { - var tx, txCount, i; var off = 0; var hashes = []; + var i; var version = utils.read32(buf, 0); var prevBlock = buf.slice(4, 36); diff --git a/lib/bcoin/bn.js b/lib/bcoin/bn.js deleted file mode 100644 index 7acb5700..00000000 --- a/lib/bcoin/bn.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * bn.js - signed big numbers for bcoin - * Copyright (c) 2014-2015, Fedor Indutny (MIT License) - * https://github.com/indutny/bcoin - */ - -var bn = require('bn.js'); - -/** - * Signed Big Numbers - */ - -function bn2(number, signed, base, endian) { - if (!(this instanceof bn2)) - return new bn2(number, signed, base, endian); - - if (typeof signed !== 'boolean') { - endian = base; - base = signed; - signed = null; - } - - this.__signed = !!signed; - - return bn.call(this, number, base, endian); -} - -bn2.prototype.__proto__ = bn.prototype; - -bn2.prototype._initArray = function _initArray(number, base, endian) { - var i = 0; - var ret; - - if (!this.__signed) - return bn.prototype._initArray.apply(this, arguments); - - if (endian === 'le') - i = number.length - 1; - - // If we are signed, do (~num + 1) to get - // the positive counterpart and set bn's - // negative flag. - if (number[i] & 0x80) { - if (isNegZero(number, endian)) { - ret = this._initNumber(0, 10, endian); - } else { - ret = bn.prototype._initArray.apply(this, arguments); - this.inotn(64).iaddn(1).ineg(); - } - } else { - ret = bn.prototype._initArray.apply(this, arguments); - } - - return ret; -}; - -bn2.prototype.toArray = function toArray(endian, length) { - var self = this; - - if (!this.__signed) - return bn.prototype.toArray.apply(self, arguments); - - // Convert the number to the - // negative byte representation. - if (self.isNeg()) { - if (self.cmpn(0) === 0) - self = new bn(0); - else - self = self.neg().notn(64).addn(1); - } - - return bn.prototype.toArray.apply(self, arguments); -}; - -bn2.signed = function signed(number, base, endian) { - return new bn2(number, true, base, endian); -}; - -function isNegZero(number, endian) { - var i = 0; - - if (endian === 'le') - i = number.length - 1; - - if (number[i] & 0x80) { - number = number.slice(); - number[i] &= ~0x80; - return new bn(number, endian).cmpn(0) === 0; - } - - return false; -} - -/** - * Expose - */ - -module.exports = bn2; diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index 2fa0c393..999fa805 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -28,9 +28,6 @@ function Chain(node, options) { this.options = options; - if (this.options.debug) - bcoin.debug = this.options.debug; - this.node = node; this.loading = false; this.mempool = node.mempool; @@ -68,7 +65,7 @@ Chain.prototype._init = function _init() { // Hook into events for debugging this.on('block', function(block, entry, peer) { - var host = peer ? peer.host : 'unknown'; + // var host = peer ? peer.host : 'unknown'; // utils.debug('Block %s (%d) added to chain (%s)', // utils.revHex(entry.hash), entry.height, host); }); @@ -287,7 +284,7 @@ Chain.prototype._preload = function _preload(callback) { stream.on('data', function(data) { var blocks = []; var need = 80 - buf.size; - var i, lastEntry; + var lastEntry; while (data.length >= need) { buf.data.push(data.slice(0, need)); @@ -405,8 +402,8 @@ Chain.prototype._verifyContext = function _verifyContext(block, prev, callback) Chain.prototype._verify = function _verify(block, prev, callback) { var self = this; var flags = constants.flags.MANDATORY_VERIFY_FLAGS; - var height, ts, i, tx, cb, coinbaseHeight; - var locktimeMedian, segwit, check; + var height, ts, i, tx, coinbaseHeight; + var medianTime, locktimeMedian, segwit; function done(err, result) { prev.free(); @@ -591,7 +588,6 @@ Chain.prototype._checkDuplicates = function _checkDuplicates(block, prev, callba }; Chain.prototype._checkInputs = function _checkInputs(block, prev, flags, callback) { - var self = this; var height = prev.height + 1; var scriptCheck = true; @@ -609,7 +605,7 @@ Chain.prototype._checkInputs = function _checkInputs(block, prev, flags, callbac } this.db.fillBlock(block, function(err) { - var i, j, input, hash; + var i, j, input, tx, hash; var sigops = 0; if (err) @@ -683,7 +679,7 @@ Chain.prototype._checkInputs = function _checkInputs(block, prev, flags, callbac }; Chain.prototype._checkReward = function _checkReward(block) { - var claimed, actual; + var i, claimed, actual; claimed = block.txs[0].getOutputValue(); actual = bcoin.block.reward(block.height); @@ -750,7 +746,7 @@ Chain.prototype._findFork = function _findFork(fork, longer, callback) { })(); }; -Chain.prototype._reorganize = function _reorganize(entry, callback) { +Chain.prototype._reorganize = function _reorganize(entry, block, callback) { var self = this; return this._findFork(this.tip, entry, function(err, fork) { @@ -859,7 +855,7 @@ Chain.prototype._setBestChain = function _setBestChain(entry, block, callback) { } else if (entry.prevBlock === this.tip.hash) { done(); } else { - self._reorganize(entry, done); + self._reorganize(entry, block, done); } function done(err) { @@ -880,7 +876,6 @@ Chain.prototype._setBestChain = function _setBestChain(entry, block, callback) { Chain.prototype.reset = function reset(height, callback, force) { var self = this; - var chainHeight; var unlock = this._lock(reset, [height, callback], force); if (!unlock) @@ -956,7 +951,7 @@ Chain.prototype.add = function add(initial, peer, callback, force) { (function next(block) { var hash = block.hash('hex'); var prevHash = block.prevBlock; - var height, checkpoint, prev, orphan; + var height, checkpoint, orphan; // We already have this block. self.db.has(hash, function(err, existing) { @@ -1223,7 +1218,7 @@ Chain.prototype.pruneOrphans = function pruneOrphans(peer) { var self = this; var best, last; - best = Object.keys(this.orphan.map).reduce(function(best, prevBlock, i) { + best = Object.keys(this.orphan.map).reduce(function(best, prevBlock) { var orphan = self.orphan.map[prevBlock]; var height = orphan.getCoinbaseHeight(); @@ -1446,7 +1441,7 @@ Chain.prototype.getHashRange = function getHashRange(start, end, callback, force return done(err); self.byTime(end, function(err, end) { - var hashes, i; + var hashes; if (err) return done(err); @@ -1562,7 +1557,6 @@ Chain.prototype.getLocator = function getLocator(start, callback, force) { }; Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) { - var self = this; var root; if (Buffer.isBuffer(hash)) @@ -1595,8 +1589,8 @@ Chain.prototype.getCurrentTarget = function getCurrentTarget(callback) { Chain.prototype.getTargetAsync = function getTarget(last, block, callback) { var self = this; var powLimit = utils.toCompact(network.powLimit); - var ts, first; var i = 0; + var ts; callback = utils.asyncify(callback); @@ -1837,6 +1831,7 @@ Chain.prototype.getState = function getState(prev, block, id, callback) { }; Chain.prototype.computeBlockVersion = function computeBlockVersion(prev, callback) { + var self = this; var version = 0; utils.forEachSerial(Object.keys(network.deployments), function(id, next) { diff --git a/lib/bcoin/chainblock.js b/lib/bcoin/chainblock.js index e76589b5..1ac1f1ee 100644 --- a/lib/bcoin/chainblock.js +++ b/lib/bcoin/chainblock.js @@ -12,7 +12,6 @@ var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; /** * ChainBlock @@ -83,7 +82,6 @@ ChainBlock.prototype.alloc = function alloc(max, callback) { }; ChainBlock.prototype.getAncestors = function getAncestors(max, callback) { - var self = this; var entry = this; var ancestors = this.ancestors.slice(); diff --git a/lib/bcoin/chaindb.js b/lib/bcoin/chaindb.js index 17f260d6..95d0df10 100644 --- a/lib/bcoin/chaindb.js +++ b/lib/bcoin/chaindb.js @@ -7,7 +7,6 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../bcoin'); -var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; @@ -210,7 +209,6 @@ ChainDB.prototype.getHash = function getHash(height, callback) { }; ChainDB.prototype.dump = function dump(callback) { - var self = this; var records = {}; var iter = this.db.db.iterator({ @@ -325,7 +323,7 @@ ChainDB.prototype._getEntry = function _getEntry(hash, callback) { }); }; -ChainDB.prototype.get = function get(height, callback, force) { +ChainDB.prototype.get = function get(height, callback) { var self = this; callback = utils.asyncify(callback); @@ -500,10 +498,10 @@ ChainDB.prototype.reset = function reset(block, callback) { (function next(err, tip) { if (err) - return done(err); + return callback(err); if (!tip) - return done(); + return callback(); batch = self.batch(); @@ -557,7 +555,7 @@ ChainDB.prototype.saveBlock = function saveBlock(block, batch, callback) { // batch.put('b/b/' + block.hash('hex'), block.toCompact()); - // block.txs.forEach(function(tx, i) { + // block.txs.forEach(function(tx) { // batch.put('t/t/' + tx.hash('hex'), tx.toExtended()); // }); @@ -579,7 +577,7 @@ ChainDB.prototype.removeBlock = function removeBlock(hash, batch, callback) { batch.del('b/b/' + block.hash('hex')); - block.txs.forEach(function(tx, i) { + block.txs.forEach(function(tx) { batch.del('t/t/' + tx.hash('hex')); }); @@ -604,7 +602,7 @@ ChainDB.prototype.connectBlock = function connectBlock(block, batch, callback) { if (!block) return callback(); - block.txs.forEach(function(tx, i) { + block.txs.forEach(function(tx) { var hash = tx.hash('hex'); var uniq = {}; @@ -676,12 +674,12 @@ ChainDB.prototype.disconnectBlock = function disconnectBlock(hash, batch, callba if (typeof hash === 'string') assert(block.hash('hex') === hash); - block.txs.forEach(function(tx, i) { + block.txs.forEach(function(tx) { var hash = tx.hash('hex'); var uniq = {}; tx.inputs.forEach(function(input) { - var coin, address; + var address; if (input.isCoinbase()) return; @@ -906,7 +904,6 @@ ChainDB.prototype.getCoinsByAddress = function getCoinsByAddress(addresses, opti }; ChainDB.prototype.getCoin = function getCoin(hash, index, callback) { - var self = this; var id = 'u/t/' + hash + '/' + index; var coin; @@ -984,6 +981,9 @@ ChainDB.prototype.getTXByAddress = function getTXByAddress(addresses, options, c }); })(); }, function(err) { + if (err) + return callback(err); + utils.forEach(hashes, function(hash, next) { self.getTX(hash, function(err, tx) { if (err) @@ -1101,8 +1101,6 @@ ChainDB.prototype._getTXBlock = function _getTXBlock(hash, callback) { }; ChainDB.prototype.fillBlock = function fillBlock(block, callback) { - var self = this; - return this.fillCoin(block.txs, function(err) { var coins, i, tx, hash, j, input, id; @@ -1133,8 +1131,6 @@ ChainDB.prototype.fillBlock = function fillBlock(block, callback) { }; ChainDB.prototype.fillTXBlock = function fillTXBlock(block, callback) { - var self = this; - return this.fillTX(block.txs, function(err) { var coins, i, tx, hash, j, input, id; @@ -1264,7 +1260,6 @@ ChainDB.prototype.isSpentTX = function isSpentTX(hash, callback) { }; ChainDB.prototype._pruneBlock = function _pruneBlock(block, batch, callback) { - var self = this; var futureHeight; if (this.options.spv) @@ -1281,7 +1276,7 @@ ChainDB.prototype._pruneBlock = function _pruneBlock(block, batch, callback) { batch.put('b/q/' + futureHeight, block.hash()); - block.txs.forEach(function(tx, i) { + block.txs.forEach(function(tx) { tx.inputs.forEach(function(input) { if (input.isCoinbase()) return; @@ -1343,7 +1338,6 @@ ChainDB.prototype._pruneQueue = function _pruneQueue(block, batch, callback) { }; ChainDB.prototype._pruneCoinQueue = function _pruneQueue(block, batch, callback) { - var self = this; var iter = this.db.db.iterator({ gte: 'u/q/' + pad32(block.height), lte: 'u/q/' + pad32(block.height) + '~', diff --git a/lib/bcoin/compactblock.js b/lib/bcoin/compactblock.js index 377a32a5..d167bf2f 100644 --- a/lib/bcoin/compactblock.js +++ b/lib/bcoin/compactblock.js @@ -16,8 +16,6 @@ var network = bcoin.protocol.network; */ function CompactBlock(data) { - var self = this; - if (!(this instanceof CompactBlock)) return new CompactBlock(data); diff --git a/lib/bcoin/datastore.js b/lib/bcoin/datastore.js index 2a3fc206..9c2d8a4a 100644 --- a/lib/bcoin/datastore.js +++ b/lib/bcoin/datastore.js @@ -6,7 +6,6 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../bcoin'); -var levelup = require('levelup'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; @@ -23,6 +22,8 @@ var NULL_CHUNK = new Buffer([0xff, 0xff, 0xff, 0xff]); */ function DataStore(db, options) { + var self = this; + if (!(this instanceof DataStore)) return new DataStore(db, options); @@ -196,7 +197,6 @@ DataStore.prototype.getLastIndex = function getLastIndex(callback) { }; DataStore.prototype.close = function close(callback) { - var self = this; return callback(); }; @@ -603,7 +603,7 @@ DataStore.prototype.read = function read(fd, offset, size, callback) { callback = utils.ensure(callback); - assert(!(offset < 0 || offset == null)) + assert(!(offset < 0 || offset == null)); data = new Buffer(size); diff --git a/lib/bcoin/ec.js b/lib/bcoin/ec.js index a0b39dcf..f69d0c5e 100644 --- a/lib/bcoin/ec.js +++ b/lib/bcoin/ec.js @@ -6,7 +6,6 @@ var bcoin = require('../bcoin'); var elliptic = require('elliptic'); -var bn = require('bn.js'); var utils = bcoin.utils; var assert = utils.assert; var ec = exports; diff --git a/lib/bcoin/fullnode.js b/lib/bcoin/fullnode.js index e6b14402..da1da99e 100644 --- a/lib/bcoin/fullnode.js +++ b/lib/bcoin/fullnode.js @@ -10,7 +10,6 @@ var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; /** * Fullnode @@ -202,7 +201,6 @@ Fullnode.prototype.getFullBlock = function getFullBlock(hash, callback) { }; Fullnode.prototype.getCoin = function getCoin(hash, index, callback) { - var self = this; var coin; callback = utils.asyncify(callback); @@ -246,7 +244,6 @@ Fullnode.prototype.getCoinByAddress = function getCoinByAddress(addresses, callb }; Fullnode.prototype.getTX = function getTX(hash, callback) { - var self = this; var tx; callback = utils.asyncify(callback); @@ -267,8 +264,6 @@ Fullnode.prototype.getTX = function getTX(hash, callback) { }; Fullnode.prototype.isSpent = function isSpent(hash, index, callback) { - var self = this; - callback = utils.asyncify(callback); if (this.mempool.isSpent(hash, index)) @@ -278,7 +273,6 @@ Fullnode.prototype.isSpent = function isSpent(hash, index, callback) { }; Fullnode.prototype.getTXByAddress = function getTXByAddress(addresses, callback) { - var self = this; var mempool; callback = utils.asyncify(callback); diff --git a/lib/bcoin/hd.js b/lib/bcoin/hd.js index d6395802..8986b694 100644 --- a/lib/bcoin/hd.js +++ b/lib/bcoin/hd.js @@ -52,14 +52,11 @@ var bcoin = require('../bcoin'); var bn = require('bn.js'); -var elliptic = require('elliptic'); var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; -var EventEmitter = require('events').EventEmitter; - var english = require('../../etc/english.json'); /** @@ -81,7 +78,7 @@ function HDSeed(options) { assert(this.bits % 8 === 0); } -HDSeed.prototype.createSeed = function createSeed(passphrase) { +HDSeed.prototype.createSeed = function createSeed() { if (this.seed) return this.seed; @@ -411,7 +408,7 @@ HDPrivateKey.prototype.scan45 = function scan45(options, txByAddress, callback) if (chainConstant === 0) cosigners[cosignerIndex] = { addressDepth: addressIndex - gap }; else - cosigners[cosginerIndex].changeDepth = addressIndex - gap; + cosigners[cosignerIndex].changeDepth = addressIndex - gap; if (total === 0) { if (chainConstant === 0) @@ -426,7 +423,7 @@ HDPrivateKey.prototype.scan45 = function scan45(options, txByAddress, callback) })(0); }; -HDPrivateKey.prototype.derivePurpose45 = function derivePurpose45(options) { +HDPrivateKey.prototype.derivePurpose45 = function derivePurpose45() { var child; if (this instanceof HDPublicKey) { @@ -476,13 +473,13 @@ HDPrivateKey.prototype.deriveCosignerAddress = function deriveCosignerAddress(co }); }; -HDPrivateKey.prototype.isPurpose45 = function isPurpose45(options) { +HDPrivateKey.prototype.isPurpose45 = function isPurpose45() { if (utils.readU8(this.depth) !== 1) return false; return utils.readU32BE(this.childIndex) === constants.hd.hardened + 45; }; -HDPrivateKey.prototype.isAccount44 = function isAccount44(options) { +HDPrivateKey.prototype.isAccount44 = function isAccount44() { if (utils.readU32BE(this.childIndex) < constants.hd.hardened) return false; return utils.readU8(this.depth) === 3; @@ -827,14 +824,14 @@ HDPrivateKey.isValidPath = function isValidPath(path, hardened) { }; HDPrivateKey.prototype.derivePath = function derivePath(path) { - var indexes, child; + var indexes; if (!HDPrivateKey.isValidPath(path)) throw new Error('invalid path'); indexes = HDPrivateKey._getIndexes(path); - return indexes.reduce(function(prev, index, i) { + return indexes.reduce(function(prev, index) { return prev.derive(index); }, this); }; diff --git a/lib/bcoin/headers.js b/lib/bcoin/headers.js index 5f868bea..14b9ad52 100644 --- a/lib/bcoin/headers.js +++ b/lib/bcoin/headers.js @@ -5,7 +5,6 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -23,7 +22,7 @@ function Headers(data) { bcoin.abstractblock.call(this, data); - this.type = 'headers' + this.type = 'headers'; if (!this._raw) this._raw = this.render(); diff --git a/lib/bcoin/http/client.js b/lib/bcoin/http/client.js index 311d0750..c63c804a 100644 --- a/lib/bcoin/http/client.js +++ b/lib/bcoin/http/client.js @@ -82,11 +82,11 @@ Client.prototype.unlistenWallet = function unlistenWallet(id) { this.socket.leave(id); }; -Client.prototype.listenAll = function listenAll(id) { +Client.prototype.listenAll = function listenAll() { this.listenWallet('!all'); }; -Client.prototype.unlistenAll = function unlistenAll(id) { +Client.prototype.unlistenAll = function unlistenAll() { this.unlistenWallet('!all'); }; @@ -206,6 +206,7 @@ Client.prototype.getWalletBalance = function getBalance(id, callback) { }; Client.prototype.getWalletLast = function getLast(id, limit, callback) { + var options = { limit: limit }; return this._get('/wallet/' + id + '/tx/last', options, function(err, body) { if (err) return callback(err); @@ -262,8 +263,6 @@ Client.prototype.getWalletCoin = function getCoin(id, hash, index, callback) { }; Client.prototype.syncWallet = function syncWallet(id, options, callback) { - var self = this; - var body = { receiveDepth: options.receiveDepth, changeDepth: options.changeDepth @@ -356,7 +355,7 @@ Client.prototype.broadcast = function broadcast(tx, callback) { callback = utils.ensure(callback); - return this._post('/broadcast', body, function(err, body) { + return this._post('/broadcast', body, function(err) { if (err) return callback(err); return callback(); diff --git a/lib/bcoin/http/http.js b/lib/bcoin/http/http.js index 88afe252..0392cf82 100644 --- a/lib/bcoin/http/http.js +++ b/lib/bcoin/http/http.js @@ -13,8 +13,6 @@ var utils = bcoin.utils; */ function HTTPServer(options) { - var self = this; - if (!(this instanceof HTTPServer)) return new HTTPServer(options); @@ -50,6 +48,8 @@ HTTPServer.prototype._init = function _init() { this.server.on('connection', function(socket) { socket.on('error', function(err) { + self.emit('error', err); + try { socket.destroy(); } catch (e) { diff --git a/lib/bcoin/http/provider.js b/lib/bcoin/http/provider.js index e4dd5793..a20ea168 100644 --- a/lib/bcoin/http/provider.js +++ b/lib/bcoin/http/provider.js @@ -7,7 +7,6 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../bcoin'); -var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; @@ -112,6 +111,7 @@ Provider.prototype.fillCoin = function fillCoin(tx, callback) { }; Provider.prototype.sync = function sync(wallet, address) { + var self = this; return this.client.syncWallet(this.id, wallet, function(err) { if (err) self.emit('error', err); @@ -122,4 +122,4 @@ Provider.prototype.sync = function sync(wallet, address) { * Expose */ -module.exports = WalletDB; +module.exports = Provider; diff --git a/lib/bcoin/http/request.js b/lib/bcoin/http/request.js index 99b5f8ff..891ce4dc 100644 --- a/lib/bcoin/http/request.js +++ b/lib/bcoin/http/request.js @@ -5,6 +5,7 @@ */ var Stream = require('stream').Stream; +var assert = require('assert'); // Spoof by default var USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)' @@ -15,7 +16,6 @@ var USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)' */ function request(options, callback, stream) { - var StringDecoder = require('string_decoder').StringDecoder; var qs = require('querystring'); var url = require('url'); @@ -25,7 +25,7 @@ function request(options, callback, stream) { var json = options.json; var form = options.form; var type = options.type; - var http, req, stream, opt; + var http, req, opt; if (callback) return request._buffer(options, callback); @@ -203,6 +203,8 @@ function request(options, callback, stream) { } request._buffer = function(options, callback) { + var qs = require('querystring'); + var StringDecoder = require('string_decoder').StringDecoder; var stream = request(options); var total = 0; var called = false; diff --git a/lib/bcoin/http/server.js b/lib/bcoin/http/server.js index 80b7cdbb..0520dffd 100644 --- a/lib/bcoin/http/server.js +++ b/lib/bcoin/http/server.js @@ -17,8 +17,6 @@ var assert = utils.assert; */ function NodeServer(node, options) { - var self = this; - if (!options) options = {}; @@ -254,9 +252,6 @@ NodeServer.prototype._init = function _init() { if (err) return next(err); - if (!json) - return send(404); - send(200, { success: true }); }); }); @@ -267,7 +262,7 @@ NodeServer.prototype._init = function _init() { if (err) return next(err); - if (!coins.length) + if (!balance) return send(404); send(200, { balance: utils.btc(balance) }); @@ -380,6 +375,8 @@ NodeServer.prototype._init = function _init() { }; NodeServer.prototype._initIO = function _initIO() { + var self = this; + if (!this.server.io) return; diff --git a/lib/bcoin/input.js b/lib/bcoin/input.js index f7956ba6..8f551f07 100644 --- a/lib/bcoin/input.js +++ b/lib/bcoin/input.js @@ -4,7 +4,6 @@ * https://github.com/indutny/bcoin */ -var bn = require('bn.js'); var bcoin = require('../bcoin'); var utils = bcoin.utils; var assert = utils.assert; @@ -70,7 +69,7 @@ Input.prototype.getType = function getType() { }; Input.prototype.getRedeem = function getRedeem() { - var type; + var type, redeem; if (this.isCoinbase()) return; @@ -137,7 +136,7 @@ Input.prototype.isFinal = function isFinal() { }; Input.prototype.getLocktime = function getLocktime() { - var output, redeem, lock, type; + var output, redeem; assert(this.output); diff --git a/lib/bcoin/keypair.js b/lib/bcoin/keypair.js index efa51da7..81951dd7 100644 --- a/lib/bcoin/keypair.js +++ b/lib/bcoin/keypair.js @@ -5,7 +5,6 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -91,7 +90,6 @@ KeyPair.prototype.toSecret = function toSecret() { KeyPair.toSecret = function toSecret(privateKey, compressed) { var buf = new Buffer(1 + privateKey.length + (compressed ? 1 : 0) + 4); var off = 0; - var chk; off += utils.writeU8(buf, network.prefixes.privkey, 0); off += utils.copy(privateKey, buf, off); diff --git a/lib/bcoin/lru.js b/lib/bcoin/lru.js index 0938b5ff..d44f0fd3 100644 --- a/lib/bcoin/lru.js +++ b/lib/bcoin/lru.js @@ -218,7 +218,7 @@ LRU.prototype._removeList = function removeList(item) { if (item === this.head) this.head = item.next; - if (item == this.tail) + if (item === this.tail) this.tail = item.prev || this.head; if (!this.head) diff --git a/lib/bcoin/mempool.js b/lib/bcoin/mempool.js index d2617c32..2541a3e8 100644 --- a/lib/bcoin/mempool.js +++ b/lib/bcoin/mempool.js @@ -12,7 +12,6 @@ var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; /** * Mempool @@ -171,7 +170,7 @@ Mempool.prototype.fillTX = function fillTX(tx) { return total === tx.inputs.length; }; -Mempool.prototype.getAll = function getAll(hash) { +Mempool.prototype.getAll = function getAll() { return Object.keys(this.txs).map(function(key) { return this.txs[key]; }, this); @@ -215,7 +214,7 @@ Mempool.prototype.addTX = function addTX(tx, peer, callback) { this._lockTX(tx); this.chain.fillCoin(tx, function(err) { - var i, input, dup, height, ts, priority; + var i, input, output, dup, height, ts, priority; self._unlockTX(tx); @@ -402,7 +401,7 @@ Mempool.prototype._unlockTX = function _unlockTX(tx) { Mempool.prototype.remove = Mempool.prototype.removeTX = function removeTX(hash, callback) { var self = this; - var tx, input, id; + var tx, input, id, i; callback = utils.asyncify(callback); diff --git a/lib/bcoin/merkleblock.js b/lib/bcoin/merkleblock.js index 161e14ce..3878bff4 100644 --- a/lib/bcoin/merkleblock.js +++ b/lib/bcoin/merkleblock.js @@ -5,7 +5,6 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; @@ -21,7 +20,7 @@ function MerkleBlock(data) { bcoin.abstractblock.call(this, data); - this.type = 'merkleblock' + this.type = 'merkleblock'; this.hashes = (data.hashes || []).map(function(hash) { return utils.toHex(hash); @@ -51,7 +50,6 @@ MerkleBlock.prototype.hasTX = function hasTX(hash) { MerkleBlock.prototype._verifyPartial = function _verifyPartial() { var height = 0; var tx = []; - var i = 0; var j = 0; var hashes = this.hashes; var flags = this.flags; diff --git a/lib/bcoin/miner.js b/lib/bcoin/miner.js index f137a1b9..2500faa0 100644 --- a/lib/bcoin/miner.js +++ b/lib/bcoin/miner.js @@ -199,7 +199,7 @@ Miner.prototype.addTX = function addTX(tx) { this.updateMerkle(); }; -Miner.prototype.createBlock = function createBlock(tx) { +Miner.prototype.createBlock = function createBlock() { var ts, target, coinbase, headers, block; ts = Math.max(utils.now(), this.last.ts + 1); @@ -292,7 +292,7 @@ Miner.prototype.iterate = function iterate() { var self = this; this.timeout = setTimeout(function() { - var hash; + var hash, res; // Try to find a block: do one iteration of extraNonce if (!self.findNonce()) diff --git a/lib/bcoin/mtx.js b/lib/bcoin/mtx.js index 1e554a71..b3230578 100644 --- a/lib/bcoin/mtx.js +++ b/lib/bcoin/mtx.js @@ -72,7 +72,7 @@ MTX.prototype.hash = function hash(enc) { }; MTX.prototype.witnessHash = function witnessHash(enc) { - var raw, hash; + var hash; if (this.isCoinbase()) { return enc === 'hex' @@ -121,7 +121,7 @@ MTX.prototype.getVirtualSize = function getVirtualSize() { }; MTX.prototype.addInput = function addInput(options, index) { - var input, i; + var input; if (options instanceof MTX) options = bcoin.coin(options, index); @@ -776,7 +776,6 @@ MTX.prototype.maxSize = function maxSize(maxM, maxN) { }; MTX.prototype.selectCoins = function selectCoins(unspent, options) { - var self = this; var tx = this.clone(); var outputValue = tx.getOutputValue(); var totalkb = 1; @@ -803,7 +802,7 @@ MTX.prototype.selectCoins = function selectCoins(unspent, options) { }); } else if (options.selection === 'random' || options.selection === 'all') { // Random unspents - unspent = unspent.slice().sort(function(a, b) { + unspent = unspent.slice().sort(function() { return Math.random() > 0.5 ? 1 : -1; }); } diff --git a/lib/bcoin/node.js b/lib/bcoin/node.js index ec24b4d4..9cf245de 100644 --- a/lib/bcoin/node.js +++ b/lib/bcoin/node.js @@ -6,12 +6,10 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../bcoin'); -var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; /** * Node @@ -29,7 +27,7 @@ function Node(options) { this.options = options; if (this.options.debug != null) - bcoin.debug = this.options.debug; + bcoin.debugLogs = this.options.debug; if (this.options.debugFile != null) bcoin.debugFile = this.options.debugFile; diff --git a/lib/bcoin/output.js b/lib/bcoin/output.js index 8d0f8a87..d57b8074 100644 --- a/lib/bcoin/output.js +++ b/lib/bcoin/output.js @@ -38,7 +38,7 @@ function Output(options, tx) { // For safety: do not allow usage of // Numbers, do not allow negative values. assert(typeof value !== 'number'); - assert(!this.value.isNeg()) + assert(!this.value.isNeg()); assert(this.value.bitLength() <= 63); assert(!(this.value.toArray('be', 8)[0] & 0x80)); } diff --git a/lib/bcoin/peer.js b/lib/bcoin/peer.js index da908426..deaf5f5e 100644 --- a/lib/bcoin/peer.js +++ b/lib/bcoin/peer.js @@ -18,8 +18,6 @@ var network = bcoin.protocol.network; */ function Peer(pool, options) { - var self = this; - if (!(this instanceof Peer)) return new Peer(pool, options); @@ -181,7 +179,7 @@ Peer.prototype._init = function init() { Peer.prototype.createSocket = function createSocket(port, host) { var self = this; - var net, socket; + var socket; assert(port != null); assert(host); @@ -299,8 +297,6 @@ Peer.prototype.destroy = function destroy() { }; Peer.prototype._write = function write(chunk) { - var self = this; - if (this.destroyed) return; @@ -597,17 +593,17 @@ Peer.prototype._handleGetAddr = function handleGetAddr() { }; Peer.prototype._handleInv = function handleInv(items) { - var req, i, block, hash; + var blocks, txs; this.emit('inv', items); // Always request advertised TXs - var txs = items.filter(function(item) { + txs = items.filter(function(item) { return item.type === 'tx'; }); // Emit new blocks to schedule them between multiple peers - var blocks = items.filter(function(item) { + blocks = items.filter(function(item) { return item.type === 'block'; }, this).map(function(item) { return item.hash; diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index b4047f1a..3526a0e5 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -18,7 +18,6 @@ var constants = bcoin.protocol.constants; function Pool(node, options) { var self = this; - var Chain; if (!(this instanceof Pool)) return new Pool(node, options); @@ -201,8 +200,6 @@ Pool.prototype._init = function _init() { }); this.chain.on('orphan', function(block, data, peer) { - var host = peer ? peer.host : 'unknown'; - if (!peer) return; @@ -231,8 +228,6 @@ Pool.prototype._init = function _init() { }; Pool.prototype.getBlocks = function getBlocks(peer, top, stop, callback) { - var self = this; - callback = utils.ensure(callback); this.chain.getLocator(top, function(err, locator) { @@ -283,8 +278,6 @@ Pool.prototype.resolveOrphan = function resolveOrphan(peer, top, orphan, callbac }; Pool.prototype.getHeaders = function getHeaders(peer, top, stop, callback) { - var self = this; - callback = utils.ensure(callback); this.chain.getLocator(top, function(err, locator) { @@ -566,7 +559,7 @@ Pool.prototype._handleHeaders = function _handleHeaders(headers, peer, callback) this._startInterval(); utils.forEachSerial(headers, function(header, next) { - hash = header.hash('hex'); + var hash = header.hash('hex'); if (last && header.prevBlock !== last) return next(new Error('Bad header chain.')); @@ -754,9 +747,6 @@ Pool.prototype._handleBlock = function _handleBlock(block, peer, callback) { }; Pool.prototype._load = function _load() { - var self = this; - var next; - if (!this.syncing) return; @@ -904,6 +894,7 @@ Pool.prototype._handleTX = function _handleTX(tx, peer, callback) { }; Pool.prototype._addLeech = function _addLeech(socket) { + var self = this; var peer; if (this.destroyed) @@ -927,8 +918,6 @@ Pool.prototype._addLeech = function _addLeech(socket) { }); peer.once('ack', function() { - var i; - if (self.destroyed) return; @@ -1201,7 +1190,7 @@ Pool.prototype.unwatch = function unwatch(id) { // See "Filter matching algorithm": // https://github.com/bitcoin/bips/blob/master/bip-0037.mediawiki Pool.prototype.isWatched = function(tx, bloom) { - var i, input, output; + var i, prev, input, output; if (!bloom) bloom = this.bloom; @@ -1314,7 +1303,6 @@ Pool.prototype.unwatchWallet = function unwatchWallet(wallet) { Pool.prototype.searchWallet = function(wallet, callback) { var self = this; - var wallet; assert(!this.loading); @@ -1560,7 +1548,7 @@ Pool.prototype._sendRequests = function _sendRequests(peer) { }; Pool.prototype.fulfill = function fulfill(hash) { - var hash; + var item; if (Buffer.isBuffer(hash)) hash = utils.toHex(hash); @@ -1848,7 +1836,7 @@ Pool.prototype.addSeed = function addSeed(seed) { this.seeds.push({ host: seed.host, - port: seed.port + port: seed.port || bcoin.protocol.network.port }); this.hosts[seed.host] = true; @@ -1857,6 +1845,8 @@ Pool.prototype.addSeed = function addSeed(seed) { }; Pool.prototype.removeSeed = function removeSeed(seed) { + var i; + seed = utils.parseHost(seed); if (this.hosts[seed.host] == null) diff --git a/lib/bcoin/profiler.js b/lib/bcoin/profiler.js index 54033592..f74befc6 100644 --- a/lib/bcoin/profiler.js +++ b/lib/bcoin/profiler.js @@ -168,7 +168,7 @@ exports.snapshot = function snapshot(name, callback) { name = null; } - if (bcoin.debug) { + if (bcoin.debugLogs) { mem = process.memoryUsage(); utils.debug('Memory: rss=%dmb, js-heap=%d/%dmb native-heap=%dmb', utils.mb(mem.rss), diff --git a/lib/bcoin/protocol/constants.js b/lib/bcoin/protocol/constants.js index 7b5b8bcc..00a7f28f 100644 --- a/lib/bcoin/protocol/constants.js +++ b/lib/bcoin/protocol/constants.js @@ -4,9 +4,7 @@ * https://github.com/indutny/bcoin */ -var bcoin = require('../../bcoin'); var bn = require('bn.js'); -var utils = bcoin.utils; exports.minVersion = 70001; exports.version = 70002; diff --git a/lib/bcoin/protocol/framer.js b/lib/bcoin/protocol/framer.js index 987fbe66..226567a1 100644 --- a/lib/bcoin/protocol/framer.js +++ b/lib/bcoin/protocol/framer.js @@ -192,7 +192,6 @@ Framer.address = function address(data, full, writer) { Framer.version = function version(options, writer) { var p = new BufferWriter(writer); - var i, remote, local; if (!options.agent) options.agent = new Buffer(constants.userAgent, 'ascii'); @@ -231,8 +230,7 @@ Framer.verack = function verack() { Framer._inv = function _inv(items, writer) { var p = new BufferWriter(writer); - var i, hash; - var off = 0; + var i; assert(items.length <= 50000); @@ -430,6 +428,7 @@ Framer.btx = function _tx(tx) { Framer.tx = function _tx(tx, writer) { var p = new BufferWriter(writer); + var i; p.write32(tx.version); @@ -482,6 +481,7 @@ Framer.output = function _output(output, writer) { Framer.witnessTX = function _witnessTX(tx, writer) { var p = new BufferWriter(writer); var witnessSize = 0; + var i; p.write32(tx.version); p.writeU8(0); @@ -518,11 +518,12 @@ Framer.witnessBlockSize = function witnessBlockSize(block) { }; Framer.witnessTXSize = function witnessTXSize(tx) { - return Framer.witnessTXSize(block, new BufferWriter())._witnessSize; + return Framer.witnessTXSize(tx, new BufferWriter())._witnessSize; }; Framer.witness = function _witness(witness, writer) { var p = new BufferWriter(writer); + var i; p.writeUIntv(witness.items.length); @@ -545,6 +546,7 @@ Framer.witnessBlock = function _witnessBlock(block, writer) { Framer.renderTX = function renderTX(tx, useWitness, writer) { var p = new BufferWriter(writer); + var witnessSize; if (tx._raw) { if (!useWitness && bcoin.protocol.parser.isWitnessTX(tx._raw)) { @@ -573,7 +575,7 @@ Framer.renderTX = function renderTX(tx, useWitness, writer) { Framer._block = function _block(block, useWitness, writer) { var p = new BufferWriter(writer); var witnessSize = 0; - var i, tx; + var i; p.write32(block.version); p.writeHash(block.prevBlock); @@ -598,6 +600,7 @@ Framer._block = function _block(block, useWitness, writer) { Framer.merkleBlock = function _merkleBlock(block, writer) { var p = new BufferWriter(writer); + var i; p.write32(block.version); p.writeHash(block.prevBlock); @@ -622,7 +625,6 @@ Framer.merkleBlock = function _merkleBlock(block, writer) { Framer.headers = function _headers(block, writer) { var p = new BufferWriter(writer); - var i; p.write32(block.version); p.writeHash(block.prevBlock); @@ -642,7 +644,7 @@ Framer.reject = function reject(details, writer) { var p = new BufferWriter(writer); p.writeVarString(details.message || '', 'ascii'); - p.writeU8(ccode, off); + p.writeU8(detals.ccode || constants.reject.malformed); p.writeVarString(details.reason || '', 'ascii'); if (details.data) p.writeBytes(details.data); @@ -694,7 +696,7 @@ function BufferWriter(options) { BufferWriter.prototype.render = function render() { var data = new Buffer(this.written); var off = 0; - var i; + var i, item; for (i = 0; i < this.data.length; i++) { item = this.data[i]; diff --git a/lib/bcoin/protocol/parser.js b/lib/bcoin/protocol/parser.js index ba98ac38..ee6e7669 100644 --- a/lib/bcoin/protocol/parser.js +++ b/lib/bcoin/protocol/parser.js @@ -5,7 +5,6 @@ */ var EventEmitter = require('events').EventEmitter; -var bn = require('bn.js'); var bcoin = require('../../bcoin'); var utils = bcoin.utils; @@ -355,7 +354,7 @@ Parser.parseBlock = function parseBlock(p) { Parser.parseBlockCompact = function parseBlockCompact(p) { var height = -1; var version, prevBlock, merkleRoot, ts, bits, nonce; - var i, totalTX, tx; + var totalTX; var inCount, input, raw; p = new BufferReader(p); @@ -601,7 +600,7 @@ Parser.parseWitnessTX = function parseWitnessTX(p) { Parser.parseWitness = function parseWitness(p) { var witness = []; - var chunkCount, item, i; + var chunkCount, i; p = new BufferReader(p); p.start(); diff --git a/lib/bcoin/script2.js b/lib/bcoin/script2.js index 173f2069..8d251b95 100644 --- a/lib/bcoin/script2.js +++ b/lib/bcoin/script2.js @@ -141,7 +141,7 @@ Stack.prototype.__defineSetter__('length', function(value) { return this.items.length = value; }); -Stack.prototype.getRedeem = function getRedeem(item) { +Stack.prototype.getRedeem = function getRedeem() { var redeem = Script.getRedeem(this.items); if (!redeem) return; @@ -175,7 +175,7 @@ Stack.prototype.splice = function splice(i, remove, insert) { return this.items.splice(i, remove, insert); }; -Stack.prototype.pop = function pop(item) { +Stack.prototype.pop = function pop() { return this.items.pop(); }; @@ -262,15 +262,17 @@ Stack.prototype.over = function over() { this.push(this.top(-2)); }; -Stack.prototype.pick = function pick() { - return this._pickroll('pick'); +Stack.prototype.pick = function pick(flags) { + return this._pickroll('pick', flags); }; -Stack.prototype.roll = function roll() { - return this._pickroll('roll'); +Stack.prototype.roll = function roll(flags) { + return this._pickroll('roll', flags); }; -Stack.prototype._pickroll = function pickroll(op) { +Stack.prototype._pickroll = function pickroll(op, flags) { + var val, n; + if (this.length < 2) throw new Error('Bad stack length.'); @@ -470,16 +472,16 @@ Script.prototype._next = function _next(to, code, ip) { return -1; }; -Script.prototype.execute = function execute(stack, tx, index, flags, version, recurse) { +Script.prototype.execute = function execute(stack, tx, index, flags, version) { try { - return this._execute(stack, tx, index, flags, version, recurse); + return this._execute(stack, tx, index, flags, version); } catch (e) { utils.debug('Script error: %s.', e.message); return false; } }; -Script.prototype._execute = function _execute(stack, tx, index, flags, version, recurse) { +Script.prototype._execute = function _execute(stack, tx, index, flags, version) { var code = this.code.slice(); var ip = 0; var lastSep = -1; @@ -622,11 +624,11 @@ Script.prototype._execute = function _execute(stack, tx, index, flags, version, break; } case 'pick': { - stack.pick(); + stack.pick(flags); break; } case 'roll': { - stack.roll(); + stack.roll(flags); break; } case 'rot': { @@ -1051,7 +1053,7 @@ Script.checkLocktime = function checkLocktime(locktime, tx, i) { if (locktime > tx.locktime) return false; - if (tx.inputs[index].sequence === 0xffffffff) + if (tx.inputs[i].sequence === 0xffffffff) return false; return true; @@ -1202,7 +1204,7 @@ Script.checkPush = function checkPush(value, flags) { if (!value.pushdata) return true; - op = value.pushdata.opcode + op = value.pushdata.opcode; if (!op) op = value.pushdata.len; @@ -1431,7 +1433,7 @@ Script.prototype.getAddress = function getAddress() { return bcoin.address.compileData(this.code[0], 'pubkeyhash'); if (this.isPubkeyhash()) - return bcoin.address.compileHash(this.code[2], 'pubkeyhash') + return bcoin.address.compileHash(this.code[2], 'pubkeyhash'); // Convert bare multisig to scripthash address if (this.isMultisig()) @@ -1745,7 +1747,7 @@ Script.isMultisigInput = function isMultisigInput(code, keys, isWitness) { return false; if (isWitness) { - if (!script.isDummy(code[0])) + if (!Script.isDummy(code[0])) return false; } else { if (code[0] !== 0) @@ -2065,6 +2067,8 @@ Script.isSignatureEncoding = function isSignatureEncoding(sig) { }; Script.isHashType = function isHashType(sig) { + var type; + if (!Buffer.isBuffer(sig)) return false; @@ -2349,7 +2353,7 @@ Script.verify = function verify(input, witness, output, tx, i, flags) { }; Script.verifyProgram = function verifyProgram(witness, output, tx, i, flags) { - var program, witnessScript, redeem, stack, j; + var program, witnessScript, redeem, stack, j, res; assert((flags & constants.flags.VERIFY_WITNESS) !== 0); assert(output.isWitnessProgram()); diff --git a/lib/bcoin/spvnode.js b/lib/bcoin/spvnode.js index bc816a02..cffa44da 100644 --- a/lib/bcoin/spvnode.js +++ b/lib/bcoin/spvnode.js @@ -5,12 +5,10 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; /** * SPVNode diff --git a/lib/bcoin/tx-pool.js b/lib/bcoin/tx-pool.js index e036703d..ff7fceaa 100644 --- a/lib/bcoin/tx-pool.js +++ b/lib/bcoin/tx-pool.js @@ -15,8 +15,6 @@ var EventEmitter = require('events').EventEmitter; */ function TXPool(wallet, txs) { - var self = this; - if (!(this instanceof TXPool)) return new TXPool(wallet, txs); @@ -59,7 +57,7 @@ TXPool.prototype.populate = function populate(txs) { TXPool.prototype.add = function add(tx, noWrite) { var hash = tx.hash('hex'); var updated = false; - var i, j, input, output, coin, unspent, index, orphan; + var i, j, input, output, coin, unspent, orphan; var key, orphans, some; this._wallet.fillPrevout(tx); @@ -245,7 +243,7 @@ TXPool.prototype._removeTX = function _removeTX(tx, noWrite) { }; TXPool.prototype.removeTX = function removeTX(hash) { - var tx, input, prev, updated; + var tx, input, updated, i, key; if (hash.hash) hash = hash('hex'); @@ -266,6 +264,7 @@ TXPool.prototype.removeTX = function removeTX(hash) { this._removeInput(input); + key = input.prevout.hash + '/' + input.prevout.index; this._unspent[key] = input.output; updated = true; } @@ -301,7 +300,7 @@ TXPool.prototype.unconfirm = function unconfirm(hash) { if (this._unspent[key]) this._unspent[key].height = -1; }, this); - this._storeTX(hash, tx, noWrite); + this._storeTX(hash, tx); this._lastTs = Math.max(tx.ts, this._lastTs); this._lastHeight = Math.max(tx.height, this._lastHeight); this.emit('update', this._lastTs, this._lastHeight, tx); diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 0fc48ad1..230c2307 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -214,7 +214,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, s, type) { if (typeof type === 'string') type = constants.hashType[type]; - assert(index >= 0 && index < copy.inputs.length) + assert(index >= 0 && index < copy.inputs.length); assert(s instanceof bcoin.script); // Disable this for now. We allow null hash types @@ -290,7 +290,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, s, type) { if (typeof type === 'string') type = constants.hashType[type]; - assert(index >= 0 && index < this.inputs.length) + assert(index >= 0 && index < this.inputs.length); assert(s instanceof bcoin.script); if (!(type & constants.hashType.anyonecanpay)) { @@ -446,8 +446,6 @@ TX.prototype.getOutputValue = function getOutputValue() { }; TX.prototype.getFunds = function getFunds(side) { - var acc = new bn(0); - if (side === 'in' || side === 'input') return this.getInputValue(); @@ -585,7 +583,7 @@ TX.prototype.fillPrevout = function fillPrevout(txs, unspent) { txs = [txs]; unspent = null; } else if (txs instanceof bcoin.coin) { - unspent = [tx]; + unspent = [txs]; txs = null; } else if (txs instanceof bcoin.txpool) { unspent = txs._unspent; @@ -901,7 +899,7 @@ TX.prototype.getHeight = function getHeight() { }; TX.prototype.getConfirmations = function getConfirmations(height) { - var top, height; + var top; if (height == null) { if (!this.chain) @@ -928,14 +926,18 @@ TX.prototype.getValue = function getValue() { }; TX.prototype.hasType = function hasType(type) { - for (var i = 0; i < this.inputs.length; i++) { - if (this.inputs[i].getInputType() === type) + var i; + + for (i = 0; i < this.inputs.length; i++) { + if (this.inputs[i].getType() === type) return true; } - for (var i = 0; i < this.outputs.length; i++) { + + for (i = 0; i < this.outputs.length; i++) { if (this.outputs[i].getType() === type) return true; } + return false; }; diff --git a/lib/bcoin/txdb.js b/lib/bcoin/txdb.js index 9b633f84..1c189bb8 100644 --- a/lib/bcoin/txdb.js +++ b/lib/bcoin/txdb.js @@ -17,8 +17,6 @@ var pad32 = utils.pad32; */ function TXPool(prefix, db, options) { - var self = this; - if (!(this instanceof TXPool)) return new TXPool(prefix, db, options); @@ -74,7 +72,6 @@ TXPool.prototype._lock = function _lock(func, args, force) { }; TXPool.prototype.getMap = function getMap(tx, callback) { - var self = this; var input = tx.getInputAddresses(); var output = tx.getOutputAddresses(); var addresses = utils.uniqs(input.concat(output)); @@ -180,7 +177,6 @@ TXPool.prototype.mapAddresses = function mapAddresses(address, callback) { TXPool.prototype._addOrphan = function add(key, hash, index, callback) { var prefix = this.prefix + '/'; - var self = this; var orphans; this.db.get(prefix + 'o/' + key, function(err, buf) { @@ -225,7 +221,7 @@ TXPool.prototype._getOrphans = function _getOrphans(key, callback) { utils.forEach(orphans, function(orphan, next) { self.getTX(orphan.hash, function(err, tx) { if (err) - return done(err); + return next(err); orphan.tx = tx; @@ -414,7 +410,7 @@ TXPool.prototype._add = function add(tx, map, callback, force) { return finish(); // Add input to orphan - utils.forEachSerial(orphans, function(orphan, next, j) { + utils.forEachSerial(orphans, function(orphan, next) { if (some) return next(); @@ -655,7 +651,7 @@ TXPool.prototype._remove = function remove(tx, map, callback) { this.fillTX(tx, function(err) { if (err) - return next(err); + return callback(err); tx.inputs.forEach(function(input) { var address = input.getAddress(); @@ -781,9 +777,6 @@ TXPool.prototype._unconfirm = function unconfirm(tx, map, callback) { if (!coin) return next(); - if (!address || !map[address].length) - return next(); - coin.height = tx.height; batch.put(prefix + 'u/t/' + hash + '/' + i, coin.toExtended()); @@ -997,7 +990,6 @@ TXPool.prototype.getCoinIDs = function getCoinIDs(address, callback) { TXPool.prototype.getHeightRangeHashes = function getHeightRangeHashes(address, options, callback) { var prefix = this.prefix + '/'; - var self = this; var txs = []; var iter; @@ -1050,7 +1042,6 @@ TXPool.prototype.getHeightHashes = function getHeightHashes(height, callback) { TXPool.prototype.getRangeHashes = function getRangeHashes(address, options, callback) { var prefix = this.prefix + '/'; - var self = this; var txs = []; var iter; @@ -1187,6 +1178,7 @@ TXPool.prototype.getLastTime = function getLastTime(address, callback) { }; TXPool.prototype.getPendingByAddress = function getPendingByAddress(address, callback) { + var self = this; var txs = []; return this.getPendingHashes(address, function(err, hashes) { diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index bee43892..6b90097d 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -6,14 +6,26 @@ var utils = exports; -var bcoin = require('../bcoin'); var bn = require('bn.js'); var util = require('util'); +var crypto, hash; + +utils.isBrowser = + (typeof process !== 'undefined' && process.browser) + || typeof window !== 'undefined'; + +if (!utils.isBrowser) { + crypto = require('cry' + 'pto'); +} else { + hash = require('hash.js'); +} /** * Utils */ +utils.nop = function() {}; + utils.slice = function slice(buf, start, end) { var clone; @@ -190,10 +202,10 @@ utils.isBase58 = function isBase58(msg) { utils.ripemd160 = function ripemd160(data, enc) { var result; - if (!bcoin.crypto) - return new Buffer(bcoin.hash.ripemd160().update(data, enc).digest()); + if (!crypto) + return new Buffer(hash.ripemd160().update(data, enc).digest()); - result = bcoin.crypto.createHash('ripemd160').update(data, enc).digest(); + result = crypto.createHash('ripemd160').update(data, enc).digest(); return result; }; @@ -201,10 +213,10 @@ utils.ripemd160 = function ripemd160(data, enc) { utils.sha1 = function sha1(data, enc) { var result; - if (!bcoin.crypto) - return new Buffer(bcoin.hash.sha1().update(data, enc).digest()); + if (!crypto) + return new Buffer(hash.sha1().update(data, enc).digest()); - result = bcoin.crypto.createHash('sha1').update(data, enc).digest(); + result = crypto.createHash('sha1').update(data, enc).digest(); return result; }; @@ -220,10 +232,10 @@ utils.checksum = function checksum(data, enc) { utils.sha256 = function sha256(data, enc) { var result; - if (!bcoin.crypto) - return new Buffer(bcoin.hash.sha256().update(data, enc).digest()); + if (!crypto) + return new Buffer(hash.sha256().update(data, enc).digest()); - result = bcoin.crypto.createHash('sha256').update(data, enc).digest(); + result = crypto.createHash('sha256').update(data, enc).digest(); return result; }; @@ -235,12 +247,12 @@ utils.dsha256 = function dsha256(data, enc) { utils.sha512hmac = function sha512hmac(data, salt) { var hmac, result; - if (!bcoin.crypto) { - hmac = bcoin.hash.hmac(hash.sha512, salt); + if (!crypto) { + hmac = hash.hmac(hash.sha512, salt); return new Buffer(hmac.update(data).digest()); } - hmac = bcoin.crypto.createHmac('sha512', salt); + hmac = crypto.createHmac('sha512', salt); result = hmac.update(data).digest(); return result; @@ -251,7 +263,7 @@ utils.salt = 'bcoin:'; utils.encrypt = function encrypt(data, passphrase) { var cipher, out; - if (!bcoin.crypto) + if (!crypto) return data; if (data[0] === ':') @@ -260,7 +272,7 @@ utils.encrypt = function encrypt(data, passphrase) { if (!passphrase) throw new Error('No passphrase.'); - cipher = bcoin.crypto.createCipher('aes-256-cbc', passphrase); + cipher = crypto.createCipher('aes-256-cbc', passphrase); out = ''; out += cipher.update(utils.salt + data, 'utf8', 'hex'); @@ -272,7 +284,7 @@ utils.encrypt = function encrypt(data, passphrase) { utils.decrypt = function decrypt(data, passphrase) { var decipher, out; - if (!bcoin.crypto) + if (!crypto) return data; if (data[0] !== ':') @@ -283,7 +295,7 @@ utils.decrypt = function decrypt(data, passphrase) { data = data.substring(1); - decipher = bcoin.crypto.createDecipher('aes-256-cbc', passphrase); + decipher = crypto.createDecipher('aes-256-cbc', passphrase); out = ''; out += decipher.update(data, 'hex', 'utf8'); @@ -427,8 +439,6 @@ utils.asyncify = function asyncify(callback) { return asyncifyFn; }; -utils.nop = function() {}; - utils.ensure = function ensure(callback) { if (!callback) return utils.nop; @@ -586,7 +596,7 @@ utils.parseHost = function parseHost(addr) { return { host: parts[0].replace(/[\[\]]/g, ''), - port: +parts[1] || bcoin.protocol.network.port + port: +parts[1] || 0 }; }; @@ -782,25 +792,7 @@ utils.print = function print() { return process.stdout.write(utils.format(args, true)); }; -utils.debug = function debug() { - var args = Array.prototype.slice.call(arguments); - var msg; - - if (bcoin.debug) { - msg = utils.format(args, true); - process.stdout.write(msg); - } - - if (bcoin.debugFile && bcoin.fs) { - if (!bcoin._debug) { - bcoin.ensurePrefix(); - bcoin._debug = bcoin.fs.createWriteStream( - bcoin.prefix + '/debug.log', { flags: 'a' }); - } - msg = utils.format(args, false); - bcoin._debug.write(process.pid + ': ' + msg); - } -}; +utils.debug = utils.nop; utils.merge = function merge(target) { var args = Array.prototype.slice.call(arguments, 1); @@ -1419,6 +1411,7 @@ utils.sizeIntv = function sizeIntv(num) { utils.cmp = function(a, b) { var len = Math.min(a.length, b.length); + var i; for (i = 0; i < len; i++) { if (a[i] < b[i]) @@ -1480,7 +1473,7 @@ utils.forRange = function forRange(from, to, iter, callback) { utils.forEach = function forEach(arr, iter, callback) { var pending = arr.length; - var i, error; + var error; callback = utils.asyncify(callback); @@ -1550,7 +1543,7 @@ utils.forEachSerial = function forEachSerial(arr, iter, callback) { utils.every = function every(arr, iter, callback) { var pending = arr.length; var result = true; - var i, error; + var error; callback = utils.asyncify(callback); diff --git a/lib/bcoin/wallet.js b/lib/bcoin/wallet.js index 9a740b9e..9f66116d 100644 --- a/lib/bcoin/wallet.js +++ b/lib/bcoin/wallet.js @@ -5,22 +5,17 @@ */ var bcoin = require('../bcoin'); -var bn = require('bn.js'); var EventEmitter = require('events').EventEmitter; var utils = bcoin.utils; var assert = utils.assert; var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; -var fs = bcoin.fs; /** * Wallet */ function Wallet(options) { - var self = this; - var key, receiving; - if (!(this instanceof Wallet)) return new Wallet(options); @@ -102,8 +97,7 @@ utils.inherits(Wallet, EventEmitter); Wallet.prototype._init = function _init() { var self = this; - var options = this.options; - var addr, i; + var i; assert(!this._initialized); this._initialized = true; @@ -169,7 +163,7 @@ Wallet.prototype.destroy = function destroy() { }; Wallet.prototype.addKey = function addKey(key) { - var has, i; + var has; if (key instanceof bcoin.wallet) { assert(key.derivation === this.derivation); @@ -245,7 +239,9 @@ Wallet.prototype.removeKey = function removeKey(key) { this.keys.splice(index, 1); }; -Wallet.prototype._finalizeKeys = function _finalizeKeys(key) { +Wallet.prototype._finalizeKeys = function _finalizeKeys() { + var i; + assert(!this._keysFinalized); this._keysFinalized = true; diff --git a/lib/bcoin/walletdb.js b/lib/bcoin/walletdb.js index bc73e000..e5bc0d1f 100644 --- a/lib/bcoin/walletdb.js +++ b/lib/bcoin/walletdb.js @@ -7,12 +7,10 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../bcoin'); -var bn = require('bn.js'); var constants = bcoin.protocol.constants; var network = bcoin.protocol.network; var utils = bcoin.utils; var assert = utils.assert; -var fs = bcoin.fs; var DUMMY = new Buffer([]); /** @@ -20,8 +18,6 @@ var DUMMY = new Buffer([]); */ function WalletDB(node, options) { - var self = this; - if (!(this instanceof WalletDB)) return new WalletDB(node, options); @@ -46,7 +42,6 @@ utils.inherits(WalletDB, EventEmitter); WalletDB._db = {}; WalletDB.prototype.dump = function dump(callback) { - var self = this; var records = {}; var iter = this.db.db.iterator({ @@ -280,7 +275,6 @@ WalletDB.prototype.removeJSON = function removeJSON(id, callback) { }; WalletDB.prototype._getDB = function _getDB(id, callback) { - var self = this; var key; callback = utils.ensure(callback); @@ -371,9 +365,6 @@ WalletDB.prototype.get = function get(id, passphrase, callback) { }; WalletDB.prototype.save = function save(options, callback) { - var self = this; - var passphrase = options.passphrase; - callback = utils.ensure(callback); if (options instanceof bcoin.wallet) @@ -383,8 +374,6 @@ WalletDB.prototype.save = function save(options, callback) { }; WalletDB.prototype.remove = function remove(id, callback) { - var self = this; - callback = utils.ensure(callback); if (id instanceof bcoin.wallet) { @@ -397,7 +386,6 @@ WalletDB.prototype.remove = function remove(id, callback) { WalletDB.prototype.create = function create(options, callback) { var self = this; - var passphrase = options.passphrase; callback = utils.ensure(callback); @@ -494,43 +482,36 @@ WalletDB.prototype.getCoin = function getCoin(hash, index, callback) { }; WalletDB.prototype.getAll = function getAll(id, callback) { - var self = this; id = id.id || id; return this.tx.getAllByAddress(id, callback); }; WalletDB.prototype.getCoins = function getCoins(id, callback) { - var self = this; id = id.id || id; return this.tx.getCoinsByAddress(id, callback); }; WalletDB.prototype.getPending = function getPending(id, callback) { - var self = this; id = id.id || id; return this.tx.getPendingByAddress(id, callback); }; WalletDB.prototype.getBalance = function getBalance(id, callback) { - var self = this; id = id.id || id; return this.tx.getBalanceByAddress(id, callback); }; WalletDB.prototype.getLastTime = function getLastTime(id, callback) { - var self = this; id = id.id || id; return this.tx.getLastTime(id, callback); }; WalletDB.prototype.getLast = function getLast(id, limit, callback) { - var self = this; id = id.id || id; return this.tx.getLast(id, limit, callback); }; WalletDB.prototype.getRange = function getRange(id, options, callback) { - var self = this; id = id.id || id; return this.tx.getRange(id, options, callback); };