diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index 52bc2fee..33869591 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -336,8 +336,8 @@ Block.prototype._verify = function _verify(ret) { return false; // Size can't be bigger than MAX_BLOCK_SIZE - if (this.txs.length > constants.block.maxSize - || this.getVirtualSize() > constants.block.maxSize) { + if (this.txs.length > constants.block.MAX_SIZE + || this.getVirtualSize() > constants.block.MAX_SIZE) { ret.reason = 'bad-blk-length'; ret.score = 100; return false; diff --git a/lib/bcoin/chain.js b/lib/bcoin/chain.js index bcba2823..0b56c2bb 100644 --- a/lib/bcoin/chain.js +++ b/lib/bcoin/chain.js @@ -510,7 +510,7 @@ Chain.prototype._verify = function _verify(block, prev, callback) { // not have a signature. See: // 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192 // 9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6 - if (block.ts < constants.block.bip16time) + if (block.ts < constants.block.BIP16_TIME) flags &= ~constants.flags.VERIFY_P2SH; // Only allow version 2 blocks (coinbase height) @@ -751,12 +751,12 @@ Chain.prototype._checkInputs = function _checkInputs(block, prev, flags, callbac // Check for block sigops limits // Start counting P2SH sigops once block // timestamps reach March 31st, 2012. - if (block.ts >= constants.block.bip16time) + if (block.ts >= constants.block.BIP16_TIME) sigops += tx.getSigops(true); else sigops += tx.getSigops(); - if (sigops > constants.block.maxSigops) { + if (sigops > constants.block.MAX_SIGOPS) { return callback(new VerifyError(block, 'invalid', 'bad-blk-sigops', @@ -1980,7 +1980,7 @@ Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) { Chain.prototype.getCurrentTarget = function getCurrentTarget(callback) { if (!this.tip) - return callback(null, utils.toCompact(network.powLimit)); + return callback(null, utils.toCompact(network.pow.limit)); return this.getTargetAsync(this.tip, null, callback); }; @@ -1995,12 +1995,12 @@ Chain.prototype.getCurrentTarget = function getCurrentTarget(callback) { Chain.prototype.getTargetAsync = function getTargetAsync(last, block, callback) { var self = this; - if ((last.height + 1) % network.powDiffInterval !== 0) { - if (!network.powAllowMinDifficultyBlocks) + if ((last.height + 1) % network.pow.diffInterval !== 0) { + if (!network.pow.allowMinDifficultyBlocks) return utils.asyncify(callback)(null, this.getTarget(last, block)); } - return last.getAncestors(network.powDiffInterval, function(err, ancestors) { + return last.getAncestors(network.pow.diffInterval, function(err, ancestors) { if (err) return callback(err); @@ -2019,7 +2019,7 @@ Chain.prototype.getTargetAsync = function getTargetAsync(last, block, callback) */ Chain.prototype.getTarget = function getTarget(last, block, ancestors) { - var powLimit = utils.toCompact(network.powLimit); + var powLimit = utils.toCompact(network.pow.limit); var ts, first, i; // Genesis @@ -2030,16 +2030,16 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) { ancestors = last.ancestors; // Do not retarget - if ((last.height + 1) % network.powDiffInterval !== 0) { - if (network.powAllowMinDifficultyBlocks) { + if ((last.height + 1) % network.pow.diffInterval !== 0) { + if (network.pow.allowMinDifficultyBlocks) { // Special behavior for testnet: ts = block ? (block.ts || block) : utils.now(); - if (ts > last.ts + network.powTargetSpacing * 2) + if (ts > last.ts + network.pow.targetSpacing * 2) return powLimit; i = 1; while (ancestors[i] - && last.height % network.powDiffInterval !== 0 + && last.height % network.pow.diffInterval !== 0 && last.bits === powLimit) { last = ancestors[i++]; } @@ -2048,7 +2048,7 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) { } // Back 2 weeks - first = ancestors[network.powDiffInterval - 1]; + first = ancestors[network.pow.diffInterval - 1]; assert(first); @@ -2064,10 +2064,10 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) { */ Chain.prototype.retarget = function retarget(last, first) { - var powTargetTimespan = new bn(network.powTargetTimespan); + var powTargetTimespan = new bn(network.pow.targetTimespan); var actualTimespan, target; - if (network.powNoRetargeting) + if (network.pow.noRetargeting) return last.bits; actualTimespan = new bn(last.ts - first.ts); @@ -2082,8 +2082,8 @@ Chain.prototype.retarget = function retarget(last, first) { target.imul(actualTimespan); target = target.div(powTargetTimespan); - if (target.cmp(network.powLimit) > 0) - target = network.powLimit.clone(); + if (target.cmp(network.pow.limit) > 0) + target = network.pow.limit.clone(); return utils.toCompact(target); }; @@ -2410,10 +2410,10 @@ Chain.prototype.checkFinal = function checkFinal(prev, tx, flags, callback, forc Chain.prototype.getLocks = function getLocks(tx, flags, entry, callback) { var self = this; - var mask = constants.sequenceLocktimeMask; - var granularity = constants.sequenceLocktimeGranularity; - var disableFlag = constants.sequenceLocktimeDisableFlag; - var typeFlag = constants.sequenceLocktimeTypeFlag; + var mask = constants.sequence.MASK; + var granularity = constants.sequence.GRANULARITY; + var disableFlag = constants.sequence.DISABLE_FLAG; + var typeFlag = constants.sequence.TYPE_FLAG; var hasFlag = flags & constants.flags.VERIFY_SEQUENCE; var minHeight = -1; var minTime = -1; diff --git a/lib/bcoin/chainblock.js b/lib/bcoin/chainblock.js index 04b6f1c7..c73f44ae 100644 --- a/lib/bcoin/chainblock.js +++ b/lib/bcoin/chainblock.js @@ -101,9 +101,9 @@ ChainBlock.prototype.isGenesis = function isGenesis() { ChainBlock.prototype.ensureAncestors = function ensureAncestors(callback) { var majorityWindow = network.block.majorityWindow; - var medianTimespan = constants.block.medianTimespan; - var powDiffInterval = network.powDiffInterval; - var allowMinDiff = network.powAllowMinDifficultyBlocks; + var medianTimespan = constants.block.MEDIAN_TIMESPAN; + var powDiffInterval = network.pow.diffInterval; + var allowMinDiff = network.pow.allowMinDifficultyBlocks; var max = Math.max(majorityWindow, medianTimespan); if ((this.height + 1) % powDiffInterval === 0 || allowMinDiff) max = Math.max(max, powDiffInterval); @@ -288,7 +288,7 @@ ChainBlock.prototype.getNext = function getNext(callback) { ChainBlock.prototype.getMedianTime = function getMedianTime(ancestors) { var entry = this; var median = []; - var timeSpan = constants.block.medianTimespan; + var timeSpan = constants.block.MEDIAN_TIMESPAN; var i; if (!ancestors) @@ -358,7 +358,7 @@ ChainBlock.prototype.isSuperMajority = function isSuperMajority(version, require ChainBlock.prototype.getMedianTimeAsync = function getMedianTimeAsync(callback) { var self = this; - return this.getAncestors(constants.block.medianTimespan, function(err, ancestors) { + return this.getAncestors(constants.block.MEDIAN_TIMESPAN, function(err, ancestors) { if (err) return callback(err); diff --git a/lib/bcoin/chaindb.js b/lib/bcoin/chaindb.js index 5058f925..1d484961 100644 --- a/lib/bcoin/chaindb.js +++ b/lib/bcoin/chaindb.js @@ -60,8 +60,8 @@ function ChainDB(chain, options) { // Need to cache up to the retarget interval // if we're going to be checking the damn // target all the time. - if (network.powAllowMinDifficultyBlocks) - this._cacheWindow = network.powDiffInterval + 1; + if (network.pow.allowMinDifficultyBlocks) + this._cacheWindow = network.pow.diffInterval + 1; else this._cacheWindow = network.block.majorityWindow + 1; diff --git a/lib/bcoin/hd.js b/lib/bcoin/hd.js index 479c5908..34748d38 100644 --- a/lib/bcoin/hd.js +++ b/lib/bcoin/hd.js @@ -343,9 +343,9 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) { if (cached) return cached; - hardened = index >= constants.hd.hardened ? true : hardened; - if (index < constants.hd.hardened && hardened) - index += constants.hd.hardened; + hardened = index >= constants.hd.HARDENED ? true : hardened; + if (index < constants.hd.HARDENED && hardened) + index += constants.hd.HARDENED; p = new BufferWriter(); @@ -371,7 +371,7 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) { if (!this.fingerPrint) { this.fingerPrint = utils.ripesha(this.publicKey) - .slice(0, constants.hd.parentFingerPrintSize); + .slice(0, constants.hd.PARENT_FINGERPRINT_SIZE); } child = new HDPrivateKey({ @@ -456,7 +456,7 @@ HDPrivateKey.prototype.derivePurpose45 = function derivePurpose45() { HDPrivateKey.prototype.isPurpose45 = function isPurpose45() { if (this.depth !== 1) return false; - return this.childIndex === constants.hd.hardened + 45; + return this.childIndex === constants.hd.HARDENED + 45; }; /** @@ -465,7 +465,7 @@ HDPrivateKey.prototype.isPurpose45 = function isPurpose45() { */ HDPrivateKey.prototype.isAccount44 = function isAccount44() { - if (this.childIndex < constants.hd.hardened) + if (this.childIndex < constants.hd.HARDENED) return false; return this.depth === 3; }; @@ -495,10 +495,10 @@ HDPrivateKey._getIndexes = function _getIndexes(path) { var indexes = []; var i, step, hardened, index; - if (~constants.hd.pathRoots.indexOf(path)) + if (~constants.hd.PATH_ROOTS.indexOf(path)) return indexes; - if (!~constants.hd.pathRoots.indexOf(root)) + if (!~constants.hd.PATH_ROOTS.indexOf(root)) return null; for (i = 0; i < steps.length; i++) { @@ -514,7 +514,7 @@ HDPrivateKey._getIndexes = function _getIndexes(path) { index = +step; if (hardened) - index += constants.hd.hardened; + index += constants.hd.HARDENED; indexes.push(index); } @@ -538,9 +538,9 @@ HDPrivateKey.isValidPath = function isValidPath(path, hardened) { } if (typeof path === 'number') { - if (path < constants.hd.hardened && hardened) - path += constants.hd.hardened; - return path >= 0 && path < constants.hd.maxIndex; + if (path < constants.hd.HARDENED && hardened) + path += constants.hd.HARDENED; + return path >= 0 && path < constants.hd.MAX_INDEX; } return false; @@ -579,8 +579,8 @@ HDPrivateKey._fromSeed = function _fromSeed(seed, networkType) { var data = seed.createSeed(); var hash; - if (data.length < constants.hd.minEntropy - || data.length > constants.hd.maxEntropy) { + if (data.length < constants.hd.MIN_ENTROPY + || data.length > constants.hd.MAX_ENTROPY) { throw new Error('Entropy not in range.'); } @@ -965,7 +965,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) { if (cached) return cached; - if (index >= constants.hd.hardened || hardened) + if (index >= constants.hd.HARDENED || hardened) throw new Error('Invalid index.'); if (index < 0) @@ -986,7 +986,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) { if (!this.fingerPrint) { this.fingerPrint = utils.ripesha(this.publicKey) - .slice(0, constants.hd.parentFingerPrintSize); + .slice(0, constants.hd.PARENT_FINGERPRINT_SIZE); } child = new HDPublicKey({ @@ -1058,7 +1058,7 @@ HDPublicKey.isValidPath = function isValidPath(arg) { } if (typeof arg === 'number') - return arg >= 0 && arg < constants.hd.hardened; + return arg >= 0 && arg < constants.hd.HARDENED; return false; }; diff --git a/lib/bcoin/http/server.js b/lib/bcoin/http/server.js index 1cb20dbd..529ace10 100644 --- a/lib/bcoin/http/server.js +++ b/lib/bcoin/http/server.js @@ -67,7 +67,7 @@ HTTPServer.prototype._init = function _init() { } res.setHeader('X-Bcoin-Network', network.type); - res.setHeader('X-Bcoin-Version', constants.userAgent); + res.setHeader('X-Bcoin-Version', constants.USER_AGENT); next(); }); @@ -182,7 +182,7 @@ HTTPServer.prototype._init = function _init() { this.get('/', function(req, res, next, send) { send(200, { - version: constants.userAgent, + version: constants.USER_AGENT, network: network.type }); }); @@ -603,7 +603,7 @@ HTTPServer.prototype._initIO = function _initIO() { self.emit('websocket', socket); socket.emit('version', { - version: constants.userAgent, + version: constants.USER_AGENT, network: network.type }); }); diff --git a/lib/bcoin/input.js b/lib/bcoin/input.js index 951efbda..2fa961a8 100644 --- a/lib/bcoin/input.js +++ b/lib/bcoin/input.js @@ -181,7 +181,7 @@ Input.prototype.isFinal = function isFinal() { */ Input.prototype.isCoinbase = function isCoinbase() { - return this.prevout.hash === constants.nullHash; + return this.prevout.hash === constants.NULL_HASH; }; /** diff --git a/lib/bcoin/mempool.js b/lib/bcoin/mempool.js index 648cb0f0..1d49ad95 100644 --- a/lib/bcoin/mempool.js +++ b/lib/bcoin/mempool.js @@ -753,7 +753,7 @@ Mempool.prototype.verify = function verify(tx, callback) { 0)); } - if (tx.getSigops(true) > constants.tx.maxSigops) { + if (tx.getSigops(true) > constants.tx.MAX_SIGOPS) { return callback(new VerifyError(tx, 'nonstandard', 'bad-txns-too-many-sigops', @@ -1292,10 +1292,10 @@ Mempool.prototype.checkLocks = function checkLocks(tx, flags, callback) { var tip = this.chain.tip; var index = new bcoin.chainblock(this.chain, { - hash: utils.toHex(constants.zeroHash), + hash: utils.toHex(constants.ZERO_HASH), version: tip.version, prevBlock: tip.hash, - merkleRoot: utils.toHex(constants.zeroHash), + merkleRoot: utils.toHex(constants.ZERO_HASH), ts: utils.now(), bits: 0, nonce: 0, diff --git a/lib/bcoin/miner.js b/lib/bcoin/miner.js index b887ea17..8936a428 100644 --- a/lib/bcoin/miner.js +++ b/lib/bcoin/miner.js @@ -336,7 +336,7 @@ function MinerBlock(options) { this.coinbase.addInput({ prevout: { - hash: constants.nullHash, + hash: constants.NULL_HASH, index: 0xffffffff }, coin: null, @@ -369,7 +369,7 @@ function MinerBlock(options) { this.block = new bcoin.block({ version: options.version, prevBlock: this.tip.hash, - merkleRoot: constants.nullHash, + merkleRoot: constants.NULL_HASH, ts: Math.max(utils.now(), this.tip.ts + 1), bits: options.target, nonce: 0, @@ -444,7 +444,7 @@ MinerBlock.prototype.addTX = function addTX(tx) { var size = this.block.getVirtualSize(true) + tx.getVirtualSize(); // Deliver me from the block size debate, please - if (size > constants.block.maxSize) + if (size > constants.block.MAX_SIZE) return false; if (this.block.hasTX(tx)) diff --git a/lib/bcoin/mtx.js b/lib/bcoin/mtx.js index f3a793ec..36ace670 100644 --- a/lib/bcoin/mtx.js +++ b/lib/bcoin/mtx.js @@ -137,8 +137,8 @@ MTX.prototype.witnessHash = function witnessHash(enc) { if (this.isCoinbase()) { return enc === 'hex' - ? utils.toHex(constants.zeroHash) - : utils.slice(constants.zeroHash); + ? utils.toHex(constants.ZERO_HASH) + : utils.slice(constants.ZERO_HASH); } if (!this.hasWitness()) @@ -459,7 +459,7 @@ MTX.prototype.createSignature = function createSignature(index, prev, key, type, type = 'all'; if (typeof type === 'string') - type = constants.hashType[type]; + type = constants.hashType[type.toUpperCase()]; // Get the hash of the current tx, minus the other // inputs, plus the sighash type. @@ -1109,7 +1109,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { continue; if (network.height !== -1 && coin.coinbase) { - if (network.height + 1 < coin.height + constants.tx.coinbaseMaturity) + if (network.height + 1 < coin.height + constants.tx.COINBASE_MATURITY) continue; } @@ -1135,7 +1135,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { // Transfer `total` funds maximum. addCoins(); } else { - fee = new bn(constants.tx.minFee); + fee = new bn(constants.tx.MIN_FEE); // Transfer `total` funds maximum. addCoins(); @@ -1146,7 +1146,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { address: options.changeAddress, // In case we don't have a change address, // use a fake p2pkh output to gauge size. - keyHash: constants.zeroHash.slice(0, 20), + keyHash: constants.ZERO_HASH.slice(0, 20), value: new bn(0) }); @@ -1187,7 +1187,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { // Attempt to subtract fee. if (options.subtractFee != null) { - minValue = fee.addn(constants.tx.dustThreshold); + minValue = fee.addn(constants.tx.DUST_THRESHOLD); if (typeof options.subtractFee === 'number') { i = options.subtractFee; @@ -1241,7 +1241,7 @@ MTX.prototype.fill = function fill(coins, options) { for (i = 0; i < result.coins.length; i++) this.addInput(result.coins[i]); - if (result.change.cmpn(constants.tx.dustThreshold) < 0) { + if (result.change.cmpn(constants.tx.DUST_THRESHOLD) < 0) { // Do nothing. Change is added to fee. assert(this.getFee().cmp(result.fee.add(result.change)) === 0); this.changeIndex = -1; diff --git a/lib/bcoin/peer.js b/lib/bcoin/peer.js index 93a39e7e..2104f0ac 100644 --- a/lib/bcoin/peer.js +++ b/lib/bcoin/peer.js @@ -318,20 +318,20 @@ Peer.prototype.broadcast = function broadcast(items) { var entry, packetType; if (typeof type === 'string') - type = constants.inv[type]; + type = constants.inv[type.toUpperCase()]; // INV does not set the witness // mask (only GETDATA does this). - type &= ~constants.invWitnessMask; + type &= ~constants.WITNESS_MASK; - if (type === constants.inv.block) + if (type === constants.inv.BLOCK) packetType = 'block'; - else if (type === constants.inv.tx) + else if (type === constants.inv.TX) packetType = 'tx'; else assert(false, 'Bad type.'); - if (self.filter && type === constants.inv.tx) { + if (self.filter && type === constants.inv.TX) { if (!item.isWatched(self.filter)) return; } @@ -395,7 +395,7 @@ Peer.prototype.updateWatch = function updateWatch() { filter: this.bloom.toBuffer(), n: this.bloom.n, tweak: this.bloom.tweak, - update: 'none' + update: constants.filterFlags.NONE })); } }; @@ -924,7 +924,7 @@ Peer.prototype._handleGetBlocks = function _handleGetBlocks(payload) { if (!hash) return done(); - blocks.push({ type: constants.inv.block, hash: hash }); + blocks.push({ type: constants.inv.BLOCK, hash: hash }); if (hash === payload.stop) return done(); @@ -941,7 +941,7 @@ Peer.prototype._handleGetBlocks = function _handleGetBlocks(payload) { }; Peer.prototype._handleVersion = function handleVersion(payload) { - if (payload.version < constants.minVersion) { + if (payload.version < constants.MIN_VERSION) { this._error('Peer doesn\'t support required protocol version.'); this.setMisbehavior(100); return; @@ -1011,7 +1011,7 @@ Peer.prototype._handleMempool = function _handleMempool() { return self.emit('error', err); 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] }); bcoin.debug('Sending mempool snapshot to %s.', self.host); @@ -1033,7 +1033,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { hash = utils.toHex(item.hash); entry = this._broadcast.map[hash]; - isWitness = item.type & constants.invWitnessMask; + isWitness = item.type & constants.WITNESS_MASK; value = null; if (!entry) { @@ -1041,7 +1041,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { continue; } - if ((item.type & ~constants.invWitnessMask) !== entry.type) { + if ((item.type & ~constants.WITNESS_MASK) !== entry.type) { bcoin.debug( 'Peer %s requested an existing item with the wrong type.', this.host); @@ -1067,14 +1067,14 @@ Peer.prototype._handleGetData = function handleGetData(items) { return; utils.forEachSerial(check, function(item, next) { - var isWitness = item.type & constants.invWitnessMask; - var type = item.type & ~constants.invWitnessMask; + var isWitness = item.type & constants.WITNESS_MASK; + var type = item.type & ~constants.WITNESS_MASK; var hash = utils.toHex(item.hash); var i, tx, data; - if (type === constants.inv.tx) { + if (type === constants.inv.TX) { if (!self.mempool) { - notfound.push({ type: constants.inv.tx, hash: hash }); + notfound.push({ type: constants.inv.TX, hash: hash }); return next(); } return self.mempool.getTX(hash, function(err, tx) { @@ -1082,7 +1082,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { return next(err); if (!tx) { - notfound.push({ type: constants.inv.tx, hash: hash }); + notfound.push({ type: constants.inv.TX, hash: hash }); return next(); } @@ -1097,13 +1097,13 @@ Peer.prototype._handleGetData = function handleGetData(items) { }); } - if (type === constants.inv.block) { + if (type === constants.inv.BLOCK) { if (self.chain.db.options.spv) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return next(); } if (self.chain.db.options.prune) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return; } return self.chain.db.getBlock(hash, function(err, block) { @@ -1111,7 +1111,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { return next(err); if (!block) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return next(); } @@ -1124,7 +1124,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { if (hash === self.hashContinue) { self._write(self.framer.inv([{ - type: constants.inv.block, + type: constants.inv.BLOCK, hash: self.chain.tip.hash }])); self.hashContinue = null; @@ -1134,13 +1134,13 @@ Peer.prototype._handleGetData = function handleGetData(items) { }); } - if (type === constants.inv.filteredblock) { + if (type === constants.inv.FILTERED_BLOCK) { if (self.chain.db.options.spv) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return next(); } if (self.chain.db.options.prune) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return; } return self.chain.db.getBlock(hash, function(err, block) { @@ -1148,7 +1148,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { return next(err); if (!block) { - notfound.push({ type: constants.inv.block, hash: hash }); + notfound.push({ type: constants.inv.BLOCK, hash: hash }); return next(); } @@ -1169,7 +1169,7 @@ Peer.prototype._handleGetData = function handleGetData(items) { if (hash === self.hashContinue) { self._write(self.framer.inv([{ - type: constants.inv.block, + type: constants.inv.BLOCK, hash: self.chain.tip.hash }])); self.hashContinue = null; @@ -1295,9 +1295,9 @@ Peer.prototype._handleInv = function handleInv(items) { for (i = 0; i < items.length; i++) { item = items[i]; - if (item.type === constants.inv.tx) + if (item.type === constants.inv.TX) txs.push(item.hash); - else if (item.type === constants.inv.block) + else if (item.type === constants.inv.BLOCK) blocks.push(item.hash); } diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index 019f70a1..d2c57c6d 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -151,19 +151,19 @@ function Pool(options) { versionHeight: 0, bestHash: null, type: !options.spv - ? constants.inv.block - : constants.inv.filteredblock + ? constants.inv.BLOCK + : constants.inv.FILTERED_BLOCK }; this.tx = { state: {}, count: 0, - type: constants.inv.tx + type: constants.inv.TX }; if (this.options.witness) { - this.block.type |= constants.invWitnessMask; - this.tx.type |= constants.invWitnessMask; + this.block.type |= constants.WITNESS_MASK; + this.tx.type |= constants.WITNESS_MASK; } this.request = { @@ -2162,7 +2162,7 @@ Pool.prototype.removeSeed = function removeSeed(seed) { Pool.prototype.setMisbehavior = function setMisbehavior(peer, score) { peer.banScore += score; - if (peer.banScore >= constants.banScore) { + if (peer.banScore >= constants.BAN_SCORE) { this.peers.misbehaving[peer.host] = utils.now(); bcoin.debug('Ban threshold exceeded for %s', peer.host); peer.destroy(); @@ -2187,7 +2187,7 @@ Pool.prototype.isMisbehaving = function isMisbehaving(host) { time = this.peers.misbehaving[host]; if (time) { - if (utils.now() > time + constants.banTime) { + if (utils.now() > time + constants.BAN_TIME) { delete this.peers.misbehaving[host]; peer = this.getPeer(host); if (peer) diff --git a/lib/bcoin/protocol/constants.js b/lib/bcoin/protocol/constants.js index eb843939..fb38d16c 100644 --- a/lib/bcoin/protocol/constants.js +++ b/lib/bcoin/protocol/constants.js @@ -18,7 +18,7 @@ var utils = require('../utils'); * @default */ -exports.minVersion = 70001; +exports.MIN_VERSION = 70001; /** * BCoin's protocol version. @@ -26,7 +26,7 @@ exports.minVersion = 70001; * @default */ -exports.version = 70012; +exports.VERSION = 70012; /** * Max message size (~4mb with segwit, formerly 2mb) @@ -34,7 +34,7 @@ exports.version = 70012; * @default */ -exports.maxMessage = 4 * 1000 * 1000; +exports.MAX_MESSAGE = 4 * 1000 * 1000; /** * Service bits. @@ -43,10 +43,10 @@ exports.maxMessage = 4 * 1000 * 1000; */ exports.services = { - network: (1 << 0), - getutxo: (1 << 1), - bloom: (1 << 2), - witness: (1 << 3) + NETWORK: (1 << 0), + GETUTXO: (1 << 1), + BLOOM: (1 << 2), + WITNESS: (1 << 3) }; /** @@ -55,8 +55,7 @@ exports.services = { * @default */ -exports.localServices = exports.services.network - | exports.services.witness; +exports.LOCAL_SERVICES = exports.services.NETWORK | exports.services.WITNESS; /** * Inv types. @@ -65,13 +64,13 @@ exports.localServices = exports.services.network */ exports.inv = { - error: 0, - tx: 1, - block: 2, - filteredblock: 3, - witnesstx: 1 | (1 << 30), - witnessblock: 2 | (1 << 30), - witnessfilteredblock: 3 | (1 << 30) + ERROR: 0, + TX: 1, + BLOCK: 2, + FILTERED_BLOCK: 3, + WITNESS_TX: 1 | (1 << 30), + WITNESS_BLOCK: 2 | (1 << 30), + WITNESS_FILTERED_BLOCK: 3 | (1 << 30) }; /** @@ -93,7 +92,7 @@ exports.invByVal = utils.revMap(exports.inv); * @default */ -exports.invWitnessMask = 1 << 30; +exports.WITNESS_MASK = 1 << 30; /** * Bloom filter update flags. @@ -102,9 +101,9 @@ exports.invWitnessMask = 1 << 30; */ exports.filterFlags = { - none: 0, - all: 1, - pubkeyOnly: 2 + NONE: 0, + ALL: 1, + PUBKEY_ONLY: 2 }; /** @@ -268,7 +267,7 @@ exports.opcodesByVal = utils.revMap(exports.opcodes); * @default */ -exports.coin = new bn(10000000).muln(10); +exports.COIN = new bn(10000000).muln(10); /** * One bitcoin / 100. @@ -276,7 +275,7 @@ exports.coin = new bn(10000000).muln(10); * @default */ -exports.cent = new bn(1000000); +exports.CENT = new bn(1000000); /** * Maximum amount of money in satoshis (1btc * 21million) @@ -284,7 +283,7 @@ exports.cent = new bn(1000000); * @default */ -exports.maxMoney = new bn(21000000).mul(exports.coin); +exports.MAX_MONEY = new bn(21000000).mul(exports.COIN); /** * Sighash Types. @@ -293,10 +292,10 @@ exports.maxMoney = new bn(21000000).mul(exports.coin); */ exports.hashType = { - all: 1, - none: 2, - single: 3, - anyonecanpay: 0x80 + ALL: 1, + NONE: 2, + SINGLE: 3, + ANYONECANPAY: 0x80 }; /** @@ -313,12 +312,12 @@ exports.hashTypeByVal = utils.revMap(exports.hashType); */ exports.block = { - maxSize: 1000000, - maxSigops: 1000000 / 50, - maxOrphanTx: 1000000 / 100, - medianTimespan: 11, - bip16time: 1333238400, - sighashLimit: 1300000000 + MAX_SIZE: 1000000, + MAX_SIGOPS: 1000000 / 50, + MAX_ORPHAN_TX: 1000000 / 100, + MEDIAN_TIMESPAN: 11, + BIP16_TIME: 1333238400, + SIGHASH_LIMIT: 1300000000 }; /** @@ -328,16 +327,16 @@ exports.block = { */ exports.tx = { - version: 2, - maxSize: 100000, - minFee: 10000, - bareMultisig: true, - freeThreshold: exports.coin.muln(144).divn(250), - maxSigops: exports.block.maxSigops / 5, - coinbaseMaturity: 100 + MAX_VERSION: 2, + MAX_SIZE: 100000, + MIN_FEE: 10000, + BARE_MULTISIG: true, + FREE_THRESHOLD: exports.COIN.muln(144).divn(250), + MAX_SIGOPS: exports.block.MAX_SIGOPS / 5, + COINBASE_MATURITY: 100 }; -exports.tx.dustThreshold = 182 * exports.tx.minFee / 1000 * 3; +exports.tx.DUST_THRESHOLD = 182 * exports.tx.MIN_FEE / 1000 * 3; /** * Script-related constants. @@ -346,14 +345,14 @@ exports.tx.dustThreshold = 182 * exports.tx.minFee / 1000 * 3; */ exports.script = { - maxSize: 10000, - maxStack: 1000, - maxPush: 520, - maxOps: 201, - maxPubkeysPerMultisig: 20, - maxScripthashSigops: 15, - maxOpReturnBytes: 83, - maxOpReturn: 80 + MAX_SIZE: 10000, + MAX_STACK: 1000, + MAX_PUSH: 520, + MAX_OPS: 201, + MAX_MULTISIG_PUBKEYS: 20, + MAX_SCRIPTHASH_SIGOPS: 15, + MAX_OP_RETURN_BYTES: 83, + MAX_OP_RETURN: 80 }; /** @@ -364,19 +363,19 @@ exports.script = { */ exports.reject = { - malformed: 0x01, - invalid: 0x10, - obsolete: 0x11, - duplicate: 0x12, - nonstandard: 0x40, - dust: 0x41, - insufficientfee: 0x42, - checkpoint: 0x43, + MALFORMED: 0x01, + INVALID: 0x10, + OBSOLETE: 0x11, + DUPLICATE: 0x12, + NONSTANDARD: 0x40, + DUST: 0x41, + INSUFFICIENTFEE: 0x42, + CHECKPOINT: 0x43, // Internal codes (NOT FOR USE ON NETWORK) - internal: 0x100, - highfee: 0x100, - alreadyknown: 0x101, - conflict: 0x102 + INTERNAL: 0x100, + HIGHFEE: 0x100, + ALREADYKNOWN: 0x101, + CONFLICT: 0x102 }; /** @@ -393,12 +392,12 @@ exports.rejectByVal = utils.revMap(exports.reject); */ exports.hd = { - hardened: 0x80000000, - maxIndex: 2 * 0x80000000, - minEntropy: 128 / 8, - maxEntropy: 512 / 8, - parentFingerPrintSize: 4, - pathRoots: ['m', 'M', 'm\'', 'M\''] + HARDENED: 0x80000000, + MAX_INDEX: 2 * 0x80000000, + MIN_ENTROPY: 128 / 8, + MAX_ENTROPY: 512 / 8, + PARENT_FINGERPRINT_SIZE: 4, + PATH_ROOTS: ['m', 'M', 'm\'', 'M\''] }; /** @@ -409,35 +408,37 @@ exports.hd = { * @default */ -exports.locktimeThreshold = 500000000; +exports.LOCKTIME_THRESHOLD = 500000000; + +exports.sequence = {}; /** * Highest nSequence bit (disables sequence locktimes). * @const {Number} */ -exports.sequenceLocktimeDisableFlag = (1 << 31) >>> 0; +exports.sequence.DISABLE_FLAG = (1 << 31) >>> 0; /** * @const {Number} * @default */ -exports.sequenceLocktimeTypeFlag = 1 << 22; +exports.sequence.TYPE_FLAG = 1 << 22; /** * @const {Number} * @default */ -exports.sequenceLocktimeGranularity = 9; +exports.sequence.GRANULARITY = 9; /** * @const {Number} * @default */ -exports.sequenceLocktimeMask = 0x0000ffff; +exports.sequence.MASK = 0x0000ffff; /** * A hash of all zeroes with a `1` at the @@ -446,7 +447,7 @@ exports.sequenceLocktimeMask = 0x0000ffff; * @default */ -exports.oneHash = new Buffer( +exports.ONE_HASH = new Buffer( '0000000000000000000000000000000000000000000000000000000000000001', 'hex' ); @@ -457,7 +458,7 @@ exports.oneHash = new Buffer( * @default */ -exports.zeroHash = new Buffer( +exports.ZERO_HASH = new Buffer( '0000000000000000000000000000000000000000000000000000000000000000', 'hex' ); @@ -468,7 +469,7 @@ exports.zeroHash = new Buffer( * @default */ -exports.nullHash = +exports.NULL_HASH = '0000000000000000000000000000000000000000000000000000000000000000'; /** @@ -477,7 +478,7 @@ exports.nullHash = * @default */ -exports.userVersion = require('../../../package.json').version; +exports.USER_VERSION = require('../../../package.json').version; /** * BCoin user agent: `/bcoin:{version}/`. @@ -485,10 +486,23 @@ exports.userVersion = require('../../../package.json').version; * @default */ -exports.userAgent = '/bcoin:' + exports.userVersion + '/'; +exports.USER_AGENT = '/bcoin:' + exports.USER_VERSION + '/'; -exports.banTime = 24 * 60 * 60; -exports.banScore = 100; +/** + * Amount of time to ban misbheaving peers. + * @const {Number} + * @default + */ + +exports.BAN_TIME = 24 * 60 * 60; + +/** + * Ban score threshold before ban is placed in effect. + * @const {Number} + * @default + */ + +exports.BAN_SCORE = 100; /** * Script and locktime flags. See {@link VerifyFlags}. diff --git a/lib/bcoin/protocol/framer.js b/lib/bcoin/protocol/framer.js index 921b6f76..28489a9e 100644 --- a/lib/bcoin/protocol/framer.js +++ b/lib/bcoin/protocol/framer.js @@ -19,7 +19,7 @@ var DUMMY = new Buffer([]); * @exports Framer * @constructor * @param {Object} options - * @param {String} options.userAgent - User agent string. + * @param {String} options.USER_AGENT - User agent string. * @property {Buffer} agent */ @@ -31,7 +31,7 @@ function Framer(options) { this.options = options; - this.agent = new Buffer(options.userAgent || constants.userAgent, 'ascii'); + this.agent = new Buffer(options.USER_AGENT || constants.USER_AGENT, 'ascii'); } /** @@ -427,7 +427,7 @@ Framer.address = function address(data, full, writer) { Framer.version = function version(options, writer) { var p = new BufferWriter(writer); - var agent = options.agent || constants.userAgent; + var agent = options.agent || constants.USER_AGENT; var remote = options.remote || {}; var local = options.local || {}; @@ -435,10 +435,10 @@ Framer.version = function version(options, writer) { agent = new Buffer(agent, 'ascii'); if (local.services == null) - local.services = constants.localServices; + local.services = constants.LOCAL_SERVICES; - p.write32(constants.version); - p.writeU64(constants.localServices); + p.write32(constants.VERSION); + p.writeU64(constants.LOCAL_SERVICES); p.write64(utils.now()); Framer.address(remote, false, p); Framer.address(local, false, p); @@ -474,7 +474,7 @@ Framer._inv = function _inv(items, writer) { for (i = 0; i < items.length; i++) { type = items[i].type; if (typeof type === 'string') - type = constants.inv[items[i].type]; + type = constants.inv[items[i].type.toUpperCase()]; assert(constants.invByVal[type] != null); p.writeU32(type); p.writeHash(items[i].hash); @@ -564,7 +564,7 @@ Framer.filterLoad = function filterLoad(data, writer) { var update = data.update; if (typeof update === 'string') - update = constants.filterFlags[update]; + update = constants.filterFlags[update.toUpperCase()]; assert(update != null, 'Bad filter flag.'); @@ -608,7 +608,7 @@ Framer._getBlocks = function _getBlocks(data, writer, headers) { var p, i; if (!version) - version = constants.version; + version = constants.VERSION; if (!locator) { if (headers) @@ -618,7 +618,7 @@ Framer._getBlocks = function _getBlocks(data, writer, headers) { } if (!stop) - stop = constants.zeroHash; + stop = constants.ZERO_HASH; p = new BufferWriter(writer); @@ -1038,10 +1038,16 @@ Framer.blockHeaders = function blockHeaders(block, writer) { Framer.reject = function reject(details, writer) { var p = new BufferWriter(writer); - var ccode = constants.reject[details.ccode] || constants.reject.invalid; + var ccode = details.ccode; - if (ccode >= constants.reject.internal) - ccode = constants.reject.invalid; + if (typeof ccode === 'string') + ccode = constants.reject[ccode.toUpperCase()] + + if (!ccode) + ccode = constants.reject.INVALID; + + if (ccode >= constants.reject.INTERNAL) + ccode = constants.reject.INVALID; p.writeVarString(details.message || '', 'ascii'); p.writeU8(ccode); diff --git a/lib/bcoin/protocol/network.js b/lib/bcoin/protocol/network.js index ed3d7347..fe32cc8c 100644 --- a/lib/bcoin/protocol/network.js +++ b/lib/bcoin/protocol/network.js @@ -210,12 +210,14 @@ main.genesis = { main.magic = 0xd9b4bef9; +main.pow = {}; + /** * Default target. * @const {Buffer} */ -main.powLimit = new bn( +main.pow.limit = new bn( '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 'hex' ); @@ -226,7 +228,7 @@ main.powLimit = new bn( * @default */ -main.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks +main.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks /** * Average block time. @@ -234,7 +236,7 @@ main.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks * @default */ -main.powTargetSpacing = 10 * 60; +main.pow.targetSpacing = 10 * 60; /** * Retarget interval in blocks. @@ -242,21 +244,21 @@ main.powTargetSpacing = 10 * 60; * @default */ -main.powDiffInterval = main.powTargetTimespan / main.powTargetSpacing | 0; +main.pow.diffInterval = main.pow.targetTimespan / main.pow.targetSpacing | 0; /** * @const {Boolean} * @default */ -main.powAllowMinDifficultyBlocks = false; +main.pow.allowMinDifficultyBlocks = false; /** * @const {Boolean} * @default */ -main.powNoRetargeting = false; +main.pow.noRetargeting = false; /** * Block constants. @@ -410,15 +412,17 @@ testnet.genesis = { testnet.magic = 0x0709110b; -testnet.powLimit = new bn( +testnet.pow = {}; + +testnet.pow.limit = new bn( '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 'hex' ); -testnet.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks -testnet.powTargetSpacing = 10 * 60; -testnet.powDiffInterval = testnet.powTargetTimespan / testnet.powTargetSpacing | 0; -testnet.powAllowMinDifficultyBlocks = true; -testnet.powNoRetargeting = false; +testnet.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks +testnet.pow.targetSpacing = 10 * 60; +testnet.pow.diffInterval = testnet.pow.targetTimespan / testnet.pow.targetSpacing | 0; +testnet.pow.allowMinDifficultyBlocks = true; +testnet.pow.noRetargeting = false; testnet.block = { majorityEnforceUpgrade: 51, @@ -506,15 +510,17 @@ regtest.genesis = { regtest.magic = 0xdab5bffa; -regtest.powLimit = new bn( +regtest.pow = {}; + +regtest.pow.limit = new bn( '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 'hex' ); -regtest.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks -regtest.powTargetSpacing = 10 * 60; -regtest.powDiffInterval = regtest.powTargetTimespan / regtest.powTargetSpacing | 0; -regtest.powAllowMinDifficultyBlocks = true; -regtest.powNoRetargeting = true; +regtest.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks +regtest.pow.targetSpacing = 10 * 60; +regtest.pow.diffInterval = regtest.pow.targetTimespan / regtest.pow.targetSpacing | 0; +regtest.pow.allowMinDifficultyBlocks = true; +regtest.pow.noRetargeting = true; regtest.block = { majorityEnforceUpgrade: 750, @@ -615,15 +621,17 @@ segnet3.genesis = { segnet3.magic = 0xcaea962e; -segnet3.powLimit = new bn( +segnet3.pow = {}; + +segnet3.pow.limit = new bn( '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 'hex' ); -segnet3.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks -segnet3.powTargetSpacing = 10 * 60; -segnet3.powDiffInterval = segnet3.powTargetTimespan / segnet3.powTargetSpacing | 0; -segnet3.powAllowMinDifficultyBlocks = true; -segnet3.powNoRetargeting = false; +segnet3.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks +segnet3.pow.targetSpacing = 10 * 60; +segnet3.pow.diffInterval = segnet3.pow.targetTimespan / segnet3.pow.targetSpacing | 0; +segnet3.pow.allowMinDifficultyBlocks = true; +segnet3.pow.noRetargeting = false; segnet3.block = { majorityEnforceUpgrade: 7, @@ -657,7 +665,9 @@ segnet4.port = 28901; segnet4.segwitHeight = -1; segnet4.magic = 0xc4a1abdc; -segnet4.powLimit = new bn( +segnet4.pow = utils.merge({}, segnet3.pow); + +segnet4.pow.limit = new bn( // 512x lower min difficulty than mainnet '000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 'hex' diff --git a/lib/bcoin/protocol/parser.js b/lib/bcoin/protocol/parser.js index 96d309e4..b841944f 100644 --- a/lib/bcoin/protocol/parser.js +++ b/lib/bcoin/protocol/parser.js @@ -88,7 +88,7 @@ Parser.prototype.feed = function feed(data) { */ Parser.prototype.parse = function parse(chunk) { - if (chunk.length > constants.maxMessage) + if (chunk.length > constants.MAX_MESSAGE) return this._error('Packet too large: %dmb.', utils.mb(chunk.length)); if (this.packet === null) { @@ -138,7 +138,7 @@ Parser.prototype.parseHeader = function parseHeader(h) { cmd = h.toString('ascii', 4, 4 + i); this.waiting = utils.readU32(h, 16); - if (this.waiting > constants.maxMessage) + if (this.waiting > constants.MAX_MESSAGE) return this._error('Packet length too large: %dmb', utils.mb(this.waiting)); return { @@ -276,9 +276,9 @@ Parser.parseFilterLoad = function parseFilterLoad(p) { filter = p.readVarBytes(); n = p.readU32(); tweak = p.readU32(); - update = constants.filterFlagsByVal[p.readU8()]; + update = p.readU8(); - assert(update != null, 'Bad filter flag.'); + assert(constants.filterFlagsByVal[update] != null, 'Bad filter flag.'); return { filter: filter, @@ -553,7 +553,7 @@ Parser.parsePong = function parsePong(p) { * @property {Number?} port - Port. * @property {Boolean?} network - Whether network services are enabled. * @property {Boolean?} getutxo - Whether peer supports getutxos. - * @property {Boolean?} bloom - Whether peer supports serving filteredblocks. + * @property {Boolean?} bloom - Whether peer supports serving FILTERED_BLOCKs. * @property {Boolean?} witness - Whether peer supports segwit. * @property {Number} _size */ @@ -607,10 +607,10 @@ Parser.parseVersion = function parseVersion(p) { return { version: version, services: services, - network: (services & constants.services.network) !== 0, - getutxo: (services & constants.services.getutxo) !== 0, - bloom: (services & constants.services.bloom) !== 0, - witness: (services & constants.services.witness) !== 0, + network: (services & constants.services.NETWORK) !== 0, + getutxo: (services & constants.services.GETUTXO) !== 0, + bloom: (services & constants.services.BLOOM) !== 0, + witness: (services & constants.services.WITNESS) !== 0, ts: ts, local: recv, remote: from, @@ -676,7 +676,7 @@ Parser._parseGetBlocks = function _parseGetBlocks(p) { stop = p.readHash('hex'); - if (stop === constants.nullHash) + if (stop === constants.NULL_HASH) stop = null; return { @@ -1353,10 +1353,10 @@ Parser.parseAddress = function parseAddress(p, full) { return { ts: ts, services: services, - network: (services & constants.services.network) !== 0, - getutxo: (services & constants.services.getutxo) !== 0, - bloom: (services & constants.services.bloom) !== 0, - witness: (services & constants.services.witness) !== 0, + network: (services & constants.services.NETWORK) !== 0, + getutxo: (services & constants.services.GETUTXO) !== 0, + bloom: (services & constants.services.BLOOM) !== 0, + witness: (services & constants.services.WITNESS) !== 0, ipv6: utils.array2ip(ip, 6), ipv4: utils.array2ip(ip, 4), port: port, diff --git a/lib/bcoin/script.js b/lib/bcoin/script.js index 130266e3..8d1b084f 100644 --- a/lib/bcoin/script.js +++ b/lib/bcoin/script.js @@ -913,14 +913,14 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version stack.state.length = 0; stack.negate = 0; - if (this.getSize() > constants.script.maxSize) + if (this.getSize() > constants.script.MAX_SIZE) throw new ScriptError('Script too large.'); for (ip = 0; ip < this.code.length; ip++) { op = this.code[ip]; if (Buffer.isBuffer(op)) { - if (op.length > constants.script.maxPush) + if (op.length > constants.script.MAX_PUSH) throw new ScriptError('Push data too large.', op, ip); // Note that minimaldata is not checked // on unexecuted branches of code. @@ -932,7 +932,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version continue; } - if (op > opcodes.OP_16 && ++opCount > constants.script.maxOps) + if (op > opcodes.OP_16 && ++opCount > constants.script.MAX_OPS) throw new ScriptError('Too many opcodes.', op, ip); // It's very important to make a distiction @@ -1390,7 +1390,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version n = Script.num(stack.pop(), flags).toNumber(); - if (!(n >= 1 && n <= constants.script.maxPubkeysPerMultisig)) + if (!(n >= 1 && n <= constants.script.MAX_MULTISIG_PUBKEYS)) throw new ScriptError('`n` is out of bounds.', op, ip); if (stack.length < n + 1) @@ -1508,7 +1508,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version locktime = locktime.uand(utils.U32).toNumber(); - if ((locktime & constants.sequenceLocktimeDisableFlag) !== 0) + if ((locktime & constants.sequence.DISABLE_FLAG) !== 0) break; if (!Script.checkSequence(locktime, tx, index)) @@ -1522,7 +1522,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version v2 = stack.pop(); v1 = stack.pop(); stack.push(Buffer.concat([v1, v2])); - if (stack.top(-1).length > constants.script.maxPush) + if (stack.top(-1).length > constants.script.MAX_PUSH) throw new ScriptError('Push data too large.', op, ip); break; } @@ -1603,7 +1603,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version } } - if (stack.getSize() > constants.script.maxStack) + if (stack.getSize() > constants.script.MAX_STACK) throw new ScriptError('Stack size too large.', op, ip); if (stack.state.length !== 0) @@ -1621,7 +1621,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version */ Script.checkLocktime = function checkLocktime(locktime, tx, i) { - var threshold = constants.locktimeThreshold; + var threshold = constants.LOCKTIME_THRESHOLD; if (!( (tx.locktime < threshold && locktime < threshold) @@ -1654,19 +1654,19 @@ Script.checkSequence = function checkSequence(sequence, tx, i) { if (tx.version < 2) return false; - if (txSequence & constants.sequenceLocktimeDisableFlag) + if (txSequence & constants.sequence.DISABLE_FLAG) return false; - locktimeMask = constants.sequenceLocktimeTypeFlag - | constants.sequenceLocktimeMask; + locktimeMask = constants.sequence.TYPE_FLAG + | constants.sequence.MASK; txSequenceMasked = txSequence & locktimeMask; sequenceMasked = sequence & locktimeMask; if (!( - (txSequenceMasked < constants.sequenceLocktimeTypeFlag - && sequenceMasked < constants.sequenceLocktimeTypeFlag) - || (txSequenceMasked >= constants.sequenceLocktimeTypeFlag - && sequenceMasked >= constants.sequenceLocktimeTypeFlag) + (txSequenceMasked < constants.sequence.TYPE_FLAG + && sequenceMasked < constants.sequence.TYPE_FLAG) + || (txSequenceMasked >= constants.sequence.TYPE_FLAG + && sequenceMasked >= constants.sequence.TYPE_FLAG) )) { return false; } @@ -1971,7 +1971,7 @@ Script.createScripthash = function createScripthash(hash) { Script.createNulldata = function createNulldata(flags) { assert(Buffer.isBuffer(flags)); - assert(flags.length <= constants.script.maxOpReturn, 'Nulldata too large.'); + assert(flags.length <= constants.script.MAX_OP_RETURN, 'Nulldata too large.'); return new Script([ opcodes.OP_RETURN, flags @@ -2087,7 +2087,7 @@ Script.prototype.isStandard = function isStandard() { if (m < 1 || m > n) return false; } else if (type === 'nulldata') { - if (this.getSize() > constants.script.maxOpReturnBytes) + if (this.getSize() > constants.script.MAX_OP_RETURN_BYTES) return false; } @@ -2128,7 +2128,7 @@ Script.prototype.isStandardProgram = function isStandardProgram(witness, flags) } for (i = 0; i < witness.items.length; i++) { - if (witness.items[i].length > constants.script.maxSize) + if (witness.items[i].length > constants.script.MAX_SIZE) return false; } @@ -2837,7 +2837,7 @@ Script.isZero = function isZero(op) { */ Script.isData = function isData(data) { - return Buffer.isBuffer(data) && data.length <= constants.script.maxOpReturn; + return Buffer.isBuffer(data) && data.length <= constants.script.MAX_OP_RETURN; }; /** @@ -3045,7 +3045,7 @@ Script.isHashType = function isHashType(sig) { if (sig.length === 0) return false; - type = sig[sig.length - 1] & ~constants.hashType.anyonecanpay; + type = sig[sig.length - 1] & ~constants.hashType.ANYONECANPAY; if (!constants.hashTypeByVal[type]) return false; @@ -3168,7 +3168,7 @@ Script.prototype.getSigops = function getSigops(accurate) { if (accurate && lastOp >= opcodes.OP_1 && lastOp <= opcodes.OP_16) total += lastOp - 0x50; else - total += constants.script.maxPubkeysPerMultisig; + total += constants.script.MAX_MULTISIG_PUBKEYS; } lastOp = op; @@ -3514,7 +3514,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) { } for (j = 0; j < stack.length; j++) { - if (stack.get(j).length > constants.script.maxSize) + if (stack.get(j).length > constants.script.MAX_SIZE) return false; } diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 3c381556..bc7ac612 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -202,8 +202,8 @@ TX.prototype.hash = function hash(enc) { TX.prototype.witnessHash = function witnessHash(enc) { if (this.isCoinbase()) { return enc === 'hex' - ? utils.toHex(constants.zeroHash) - : utils.slice(constants.zeroHash); + ? utils.toHex(constants.ZERO_HASH) + : utils.slice(constants.ZERO_HASH); } if (!this.hasWitness()) @@ -359,7 +359,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { index = this.inputs.indexOf(index); if (typeof type === 'string') - type = constants.hashType[type]; + type = constants.hashType[type.toUpperCase()]; assert(index >= 0 && index < this.inputs.length); assert(prev instanceof Script); @@ -395,7 +395,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { // Set our input to previous output's script copy.inputs[index].script = prev; - if ((type & 0x1f) === constants.hashType.none) { + if ((type & 0x1f) === constants.hashType.NONE) { // Drop all outputs. We don't want to sign them. copy.outputs.length = 0; @@ -404,11 +404,11 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { if (i !== index) copy.inputs[i].sequence = 0; } - } else if ((type & 0x1f) === constants.hashType.single) { + } else if ((type & 0x1f) === constants.hashType.SINGLE) { // Bitcoind used to return 1 as an error code: // it ended up being treated like a hash. if (index >= copy.outputs.length) - return utils.slice(constants.oneHash); + return utils.slice(constants.ONE_HASH); // Drop all the outputs after the input index. copy.outputs.length = index + 1; @@ -429,7 +429,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { } // Only sign our input. Allows anyone to add inputs. - if (type & constants.hashType.anyonecanpay) { + if (type & constants.hashType.ANYONECANPAY) { copy.inputs[0] = copy.inputs[index]; copy.inputs.length = 1; } @@ -449,12 +449,12 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { index = this.inputs.indexOf(index); if (typeof type === 'string') - type = constants.hashType[type]; + type = constants.hashType[type.toUpperCase()]; assert(index >= 0 && index < this.inputs.length); assert(prev instanceof Script); - if (!(type & constants.hashType.anyonecanpay)) { + if (!(type & constants.hashType.ANYONECANPAY)) { hashPrevouts = new BufferWriter(); for (i = 0; i < this.inputs.length; i++) { prevout = this.inputs[i].prevout; @@ -463,31 +463,31 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { } hashPrevouts = utils.dsha256(hashPrevouts.render()); } else { - hashPrevouts = utils.slice(constants.zeroHash); + hashPrevouts = utils.slice(constants.ZERO_HASH); } - if (!(type & constants.hashType.anyonecanpay) - && (type & 0x1f) !== constants.hashType.single - && (type & 0x1f) !== constants.hashType.none) { + if (!(type & constants.hashType.ANYONECANPAY) + && (type & 0x1f) !== constants.hashType.SINGLE + && (type & 0x1f) !== constants.hashType.NONE) { hashSequence = new BufferWriter(); for (i = 0; i < this.inputs.length; i++) hashSequence.writeU32(this.inputs[i].sequence); hashSequence = utils.dsha256(hashSequence.render()); } else { - hashSequence = utils.slice(constants.zeroHash); + hashSequence = utils.slice(constants.ZERO_HASH); } - if ((type & 0x1f) !== constants.hashType.single - && (type & 0x1f) !== constants.hashType.none) { + if ((type & 0x1f) !== constants.hashType.SINGLE + && (type & 0x1f) !== constants.hashType.NONE) { hashOutputs = new BufferWriter(); for (i = 0; i < this.outputs.length; i++) bcoin.protocol.framer.output(this.outputs[i], hashOutputs); hashOutputs = utils.dsha256(hashOutputs.render()); - } else if ((type & 0x1f) === constants.hashType.single && index < this.outputs.length) { + } else if ((type & 0x1f) === constants.hashType.SINGLE && index < this.outputs.length) { hashOutputs = bcoin.protocol.framer.output(this.outputs[index]); hashOutputs = utils.dsha256(hashOutputs); } else { - hashOutputs = utils.slice(constants.zeroHash); + hashOutputs = utils.slice(constants.ZERO_HASH); } p.write32(this.version); @@ -595,7 +595,7 @@ TX.prototype.verifyAsync = function verifyAsync(index, force, flags, callback) { TX.prototype.isCoinbase = function isCoinbase() { return this.inputs.length === 1 - && this.inputs[0].prevout.hash === constants.nullHash; + && this.inputs[0].prevout.hash === constants.NULL_HASH; }; /** @@ -855,7 +855,7 @@ TX.prototype.fillCoins = function fillCoins(coins) { */ TX.prototype.isFinal = function isFinal(height, ts) { - var threshold = constants.locktimeThreshold; + var threshold = constants.LOCKTIME_THRESHOLD; var i; if (this.locktime === 0) @@ -980,7 +980,7 @@ TX.prototype.isSane = function isSane(ret) { return false; } - if (this.getVirtualSize() > constants.block.maxSize) { + if (this.getVirtualSize() > constants.block.MAX_SIZE) { ret.reason = 'bad-txns-oversize'; ret.score = 100; return false; @@ -995,7 +995,7 @@ TX.prototype.isSane = function isSane(ret) { return false; } - if (output.value.cmp(constants.maxMoney) > 0) { + if (output.value.cmp(constants.MAX_MONEY) > 0) { ret.reason = 'bad-txns-vout-toolarge'; ret.score = 100; return false; @@ -1003,7 +1003,7 @@ TX.prototype.isSane = function isSane(ret) { total.iadd(output.value); - if (total.cmpn(0) < 0 || total.cmp(constants.maxMoney) > 0) { + if (total.cmpn(0) < 0 || total.cmp(constants.MAX_MONEY) > 0) { ret.reason = 'bad-txns-txouttotal-toolarge'; ret.score = 100; return false; @@ -1031,7 +1031,7 @@ TX.prototype.isSane = function isSane(ret) { } else { for (i = 0; i < this.inputs.length; i++) { input = this.inputs[i]; - if (input.prevout.hash === constants.nullHash + if (input.prevout.hash === constants.NULL_HASH && input.prevout.index === 0xffffffff) { ret.reason = 'bad-txns-prevout-null'; ret.score = 10; @@ -1065,12 +1065,12 @@ TX.prototype.isStandard = function isStandard(flags, ret) { if (flags == null) flags = constants.flags.STANDARD_VERIFY_FLAGS; - if (this.version < 1 || this.version > constants.tx.version) { + if (this.version < 1 || this.version > constants.tx.MAX_VERSION) { ret.reason = 'version'; return false; } - if (this.getVirtualSize() > constants.tx.maxSize) { + if (this.getVirtualSize() > constants.tx.MAX_SIZE) { ret.reason = 'tx-size'; return false; } @@ -1104,12 +1104,12 @@ TX.prototype.isStandard = function isStandard(flags, ret) { continue; } - if (output.script.isMultisig() && !constants.tx.bareMultisig) { + if (output.script.isMultisig() && !constants.tx.BARE_MULTISIG) { ret.reason = 'bare-multisig'; return false; } - if (output.value.cmpn(constants.tx.dustThreshold) < 0) { + if (output.value.cmpn(constants.tx.DUST_THRESHOLD) < 0) { ret.reason = 'dust'; return false; } @@ -1132,7 +1132,7 @@ TX.prototype.isStandard = function isStandard(flags, ret) { */ TX.prototype.hasStandardInputs = function hasStandardInputs(flags) { - var maxSigops = constants.script.maxScripthashSigops; + var maxSigops = constants.script.MAX_SCRIPTHASH_SIGOPS; var VERIFY_NONE = constants.flags.VERIFY_NONE; var i, input, stack, res, redeem; @@ -1208,14 +1208,14 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) { coin = input.coin; if (coin.coinbase) { - if (spendHeight - coin.height < constants.tx.coinbaseMaturity) { + if (spendHeight - coin.height < constants.tx.COINBASE_MATURITY) { ret.reason = 'bad-txns-premature-spend-of-coinbase'; ret.score = 0; return false; } } - if (coin.value.cmpn(0) < 0 || coin.value.cmp(constants.maxMoney) > 0) { + if (coin.value.cmpn(0) < 0 || coin.value.cmp(constants.MAX_MONEY) > 0) { ret.reason = 'bad-txns-inputvalues-outofrange'; ret.score = 100; return false; @@ -1224,7 +1224,7 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) { total.iadd(coin.value); } - if (total.cmpn(0) < 0 || total.cmp(constants.maxMoney) > 0) { + if (total.cmpn(0) < 0 || total.cmp(constants.MAX_MONEY) > 0) { ret.reason = 'bad-txns-inputvalues-outofrange'; ret.score = 100; return false; @@ -1246,7 +1246,7 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) { return false; } - if (fee.cmp(constants.maxMoney) > 0) { + if (fee.cmp(constants.MAX_MONEY) > 0) { ret.reason = 'bad-txns-fee-outofrange'; ret.score = 100; return false; @@ -1357,7 +1357,7 @@ TX.prototype.isFree = function isFree(height, size) { priority = this.getPriority(height, size); - return priority.cmp(constants.tx.freeThreshold) > 0; + return priority.cmp(constants.tx.FREE_THRESHOLD) > 0; }; /** @@ -1374,10 +1374,10 @@ TX.prototype.getMinFee = function getMinFee(size) { if (size == null) size = this.maxSize(); - fee = new bn(constants.tx.minFee).muln(size).divn(1000); + fee = new bn(constants.tx.MIN_FEE).muln(size).divn(1000); - if (fee.cmpn(0) === 0 && constants.tx.minFee > 0) - fee = new bn(constants.tx.minFee); + if (fee.cmpn(0) === 0 && constants.tx.MIN_FEE > 0) + fee = new bn(constants.tx.MIN_FEE); return fee; }; @@ -1397,10 +1397,10 @@ TX.prototype.getMaxFee = function getMaxFee(size) { if (size == null) size = this.maxSize(); - fee = new bn(constants.tx.minFee).muln(Math.ceil(size / 1000)); + fee = new bn(constants.tx.MIN_FEE).muln(Math.ceil(size / 1000)); - if (fee.cmpn(0) === 0 && constants.tx.minFee > 0) - fee = new bn(constants.tx.minFee); + if (fee.cmpn(0) === 0 && constants.tx.MIN_FEE > 0) + fee = new bn(constants.tx.MIN_FEE); return fee; }; @@ -1486,10 +1486,10 @@ TX.prototype.isWatched = function isWatched(bloom) { output = this.outputs[i]; // Test the output script if (testScript(output.script.code)) { - if (bloom.update === 'all') { + if (bloom.update === constants.filterFlags.ALL) { outpoint = bcoin.protocol.framer.outpoint(this.hash(), i); bloom.add(outpoint); - } else if (bloom.update === 'pubkeyOnly') { + } else if (bloom.update === constants.filterFlags.PUBKEY_ONLY) { if (output.script.isPubkey() || output.script.isMultisig()) { outpoint = bcoin.protocol.framer.outpoint(this.hash(), i); bloom.add(outpoint); @@ -1718,7 +1718,7 @@ TX.prototype.toExtended = function toExtended(saveCoins) { bcoin.protocol.framer.renderTX(this, true, p); p.writeU32(height); - p.writeHash(this.block || constants.zeroHash); + p.writeHash(this.block || constants.ZERO_HASH); p.writeU32(index); p.writeU32(this.ts); p.writeU32(this.ps); @@ -1764,7 +1764,7 @@ TX._fromExtended = function _fromExtended(buf, saveCoins) { tx.ps = p.readU32(); // tx.changeIndex = p.readU32(); - if (tx.block === constants.nullHash) + if (tx.block === constants.NULL_HASH) tx.block = null; if (tx.height === 0x7fffffff) diff --git a/lib/bcoin/wallet.js b/lib/bcoin/wallet.js index de9a1aad..9c95eccf 100644 --- a/lib/bcoin/wallet.js +++ b/lib/bcoin/wallet.js @@ -505,7 +505,7 @@ Wallet.prototype.deriveAddress = function deriveAddress(change, index) { data = { path: this.createPath(this.cosignerIndex, change, index), cosignerIndex: this.copayBIP45 - ? constants.hd.hardened - 1 + ? constants.hd.HARDENED - 1 : this.cosignerIndex, change: change, index: index @@ -579,7 +579,7 @@ Wallet.prototype.hasAddress = function hasAddress(address) { Wallet.prototype.createPath = function createPath(cosignerIndex, change, index) { if (this.copayBIP45) - cosignerIndex = constants.hd.hardened - 1; + cosignerIndex = constants.hd.HARDENED - 1; return 'm' + (this.derivation === 'bip45' ? '/' + cosignerIndex : '') @@ -608,7 +608,7 @@ Wallet.prototype.parsePath = function parsePath(path) { parts = path.split('/'); if (this.derivation === 'bip45' && this.copayBIP45) - assert(+parts[parts.length - 3] === constants.hd.hardened - 1); + assert(+parts[parts.length - 3] === constants.hd.HARDENED - 1); return { path: path, diff --git a/scripts/gen.js b/scripts/gen.js index cd65a08b..99b453ce 100644 --- a/scripts/gen.js +++ b/scripts/gen.js @@ -26,13 +26,13 @@ function createGenesisBlock(options) { } if (!options.reward) - options.reward = new bn(50).mul(constants.coin); + options.reward = new bn(50).mul(constants.COIN); tx = { version: 1, inputs: [{ prevout: { - hash: constants.nullHash, + hash: constants.NULL_HASH, index: 0xffffffff }, script: { @@ -58,7 +58,7 @@ function createGenesisBlock(options) { block = { version: options.version, - prevBlock: constants.nullHash, + prevBlock: constants.NULL_HASH, merkleRoot: utils.toHex(utils.dsha256(txRaw)), ts: options.ts, bits: options.bits, diff --git a/test/chain-test.js b/test/chain-test.js index d2ea8dd0..7c824be4 100644 --- a/test/chain-test.js +++ b/test/chain-test.js @@ -7,7 +7,7 @@ var utils = bcoin.utils; var assert = utils.assert; var opcodes = constants.opcodes; -constants.tx.coinbaseMaturity = 0; +constants.tx.COINBASE_MATURITY = 0; describe('Chain', function() { var chain, wallet, miner; @@ -174,7 +174,7 @@ describe('Chain', function() { }); it('should cleanup', function(cb) { - constants.tx.coinbaseMaturity = 100; + constants.tx.COINBASE_MATURITY = 100; cb(); }); }); diff --git a/test/mempool-test.js b/test/mempool-test.js index 279b6441..d540c190 100644 --- a/test/mempool-test.js +++ b/test/mempool-test.js @@ -22,7 +22,7 @@ describe('Mempool', function() { var prev = new bcoin.script([w.publicKey, opcodes.OP_CHECKSIG]); var dummyInput = { prevout: { - hash: constants.oneHash, + hash: constants.ONE_HASH, index: 0 }, coin: { @@ -31,7 +31,7 @@ describe('Mempool', function() { value: new bn(70000), script: prev, coinbase: false, - hash: constants.oneHash, + hash: constants.ONE_HASH, index: 0 }, script: new bcoin.script([]), diff --git a/test/protocol-test.js b/test/protocol-test.js index 9210eabd..2857f7ce 100644 --- a/test/protocol-test.js +++ b/test/protocol-test.js @@ -27,14 +27,14 @@ describe('Protocol', function() { } packetTest('version', {}, function(payload) { - assert.equal(payload.version, constants.version); + assert.equal(payload.version, constants.VERSION); assert.equal(payload.agent, agent); assert.equal(payload.height, 0); assert.equal(payload.relay, false); }); packetTest('version', { relay: true, height: 10 }, function(payload) { - assert.equal(payload.version, constants.version); + assert.equal(payload.version, constants.VERSION); assert.equal(payload.agent, agent); assert.equal(payload.height, 10); assert.equal(payload.relay, true); @@ -66,7 +66,7 @@ describe('Protocol', function() { }); addr._ipv6 = addr.ipv6; addr.ipv6 = new Buffer(addr.ipv6.replace(/:/g, ''), 'hex'); - addr.services = constants.localServices; + addr.services = constants.LOCAL_SERVICES; }); packetTest('addr', peers, function(payload) { @@ -74,13 +74,13 @@ describe('Protocol', function() { assert.equal(payload.length, 2); assert.equal(typeof payload[0].ts, 'number'); - assert.equal(payload[0].services, constants.localServices); + assert.equal(payload[0].services, constants.LOCAL_SERVICES); assert.equal(payload[0].ipv6, peers[0]._ipv6); assert.equal(payload[0].ipv4, peers[0]._ipv4); assert.equal(payload[0].port, peers[0].port); assert.equal(typeof payload[1].ts, 'number'); - assert.equal(payload[1].services, constants.localServices); + assert.equal(payload[1].services, constants.LOCAL_SERVICES); assert.equal(payload[1].ipv6, peers[1]._ipv6); assert.equal(payload[1].ipv4, peers[1]._ipv4); assert.equal(payload[1].port, peers[1].port); diff --git a/test/wallet-test.js b/test/wallet-test.js index d1ad3f0e..e631e5a7 100644 --- a/test/wallet-test.js +++ b/test/wallet-test.js @@ -6,16 +6,16 @@ var assert = utils.assert; var dummyInput = { prevout: { - hash: constants.zeroHash, + hash: constants.ZERO_HASH, index: 0 }, coin: { version: 1, height: 0, - value: constants.maxMoney.clone(), + value: constants.MAX_MONEY.clone(), script: new bcoin.script([]), coinbase: false, - hash: constants.zeroHash, + hash: constants.ZERO_HASH, index: 0 }, script: new bcoin.script([]), @@ -336,7 +336,7 @@ describe('Wallet', function() { tx.addOutput(to, 5460); var cost = tx.getOutputValue(); - var total = cost.add(new bn(constants.tx.minFee)); + var total = cost.add(new bn(constants.tx.MIN_FEE)); w1.getCoins(function(err, coins1) { assert.noError(err); @@ -352,7 +352,7 @@ describe('Wallet', function() { tx.addInput(coins2[0]); var left = tx.getInputValue().sub(total); - if (left.cmpn(constants.tx.dustThreshold) < 0) { + if (left.cmpn(constants.tx.DUST_THRESHOLD) < 0) { tx.outputs[tx.outputs.length - 2].value.iadd(left); left = new bn(0); }