refactor: rename constants.

This commit is contained in:
Christopher Jeffrey 2016-04-17 08:45:22 -07:00
parent ad11d33038
commit 0a621238ba
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
24 changed files with 347 additions and 317 deletions

View File

@ -336,8 +336,8 @@ Block.prototype._verify = function _verify(ret) {
return false; return false;
// Size can't be bigger than MAX_BLOCK_SIZE // Size can't be bigger than MAX_BLOCK_SIZE
if (this.txs.length > constants.block.maxSize if (this.txs.length > constants.block.MAX_SIZE
|| this.getVirtualSize() > constants.block.maxSize) { || this.getVirtualSize() > constants.block.MAX_SIZE) {
ret.reason = 'bad-blk-length'; ret.reason = 'bad-blk-length';
ret.score = 100; ret.score = 100;
return false; return false;

View File

@ -510,7 +510,7 @@ Chain.prototype._verify = function _verify(block, prev, callback) {
// not have a signature. See: // not have a signature. See:
// 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192 // 6a26d2ecb67f27d1fa5524763b49029d7106e91e3cc05743073461a719776192
// 9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6 // 9c08a4d78931342b37fd5f72900fb9983087e6f46c4a097d8a1f52c74e28eaf6
if (block.ts < constants.block.bip16time) if (block.ts < constants.block.BIP16_TIME)
flags &= ~constants.flags.VERIFY_P2SH; flags &= ~constants.flags.VERIFY_P2SH;
// Only allow version 2 blocks (coinbase height) // 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 // Check for block sigops limits
// Start counting P2SH sigops once block // Start counting P2SH sigops once block
// timestamps reach March 31st, 2012. // timestamps reach March 31st, 2012.
if (block.ts >= constants.block.bip16time) if (block.ts >= constants.block.BIP16_TIME)
sigops += tx.getSigops(true); sigops += tx.getSigops(true);
else else
sigops += tx.getSigops(); sigops += tx.getSigops();
if (sigops > constants.block.maxSigops) { if (sigops > constants.block.MAX_SIGOPS) {
return callback(new VerifyError(block, return callback(new VerifyError(block,
'invalid', 'invalid',
'bad-blk-sigops', 'bad-blk-sigops',
@ -1980,7 +1980,7 @@ Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) {
Chain.prototype.getCurrentTarget = function getCurrentTarget(callback) { Chain.prototype.getCurrentTarget = function getCurrentTarget(callback) {
if (!this.tip) 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); 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) { Chain.prototype.getTargetAsync = function getTargetAsync(last, block, callback) {
var self = this; var self = this;
if ((last.height + 1) % network.powDiffInterval !== 0) { if ((last.height + 1) % network.pow.diffInterval !== 0) {
if (!network.powAllowMinDifficultyBlocks) if (!network.pow.allowMinDifficultyBlocks)
return utils.asyncify(callback)(null, this.getTarget(last, block)); 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) if (err)
return callback(err); return callback(err);
@ -2019,7 +2019,7 @@ Chain.prototype.getTargetAsync = function getTargetAsync(last, block, callback)
*/ */
Chain.prototype.getTarget = function getTarget(last, block, ancestors) { 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; var ts, first, i;
// Genesis // Genesis
@ -2030,16 +2030,16 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) {
ancestors = last.ancestors; ancestors = last.ancestors;
// Do not retarget // Do not retarget
if ((last.height + 1) % network.powDiffInterval !== 0) { if ((last.height + 1) % network.pow.diffInterval !== 0) {
if (network.powAllowMinDifficultyBlocks) { if (network.pow.allowMinDifficultyBlocks) {
// Special behavior for testnet: // Special behavior for testnet:
ts = block ? (block.ts || block) : utils.now(); ts = block ? (block.ts || block) : utils.now();
if (ts > last.ts + network.powTargetSpacing * 2) if (ts > last.ts + network.pow.targetSpacing * 2)
return powLimit; return powLimit;
i = 1; i = 1;
while (ancestors[i] while (ancestors[i]
&& last.height % network.powDiffInterval !== 0 && last.height % network.pow.diffInterval !== 0
&& last.bits === powLimit) { && last.bits === powLimit) {
last = ancestors[i++]; last = ancestors[i++];
} }
@ -2048,7 +2048,7 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) {
} }
// Back 2 weeks // Back 2 weeks
first = ancestors[network.powDiffInterval - 1]; first = ancestors[network.pow.diffInterval - 1];
assert(first); assert(first);
@ -2064,10 +2064,10 @@ Chain.prototype.getTarget = function getTarget(last, block, ancestors) {
*/ */
Chain.prototype.retarget = function retarget(last, first) { Chain.prototype.retarget = function retarget(last, first) {
var powTargetTimespan = new bn(network.powTargetTimespan); var powTargetTimespan = new bn(network.pow.targetTimespan);
var actualTimespan, target; var actualTimespan, target;
if (network.powNoRetargeting) if (network.pow.noRetargeting)
return last.bits; return last.bits;
actualTimespan = new bn(last.ts - first.ts); actualTimespan = new bn(last.ts - first.ts);
@ -2082,8 +2082,8 @@ Chain.prototype.retarget = function retarget(last, first) {
target.imul(actualTimespan); target.imul(actualTimespan);
target = target.div(powTargetTimespan); target = target.div(powTargetTimespan);
if (target.cmp(network.powLimit) > 0) if (target.cmp(network.pow.limit) > 0)
target = network.powLimit.clone(); target = network.pow.limit.clone();
return utils.toCompact(target); 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) { Chain.prototype.getLocks = function getLocks(tx, flags, entry, callback) {
var self = this; var self = this;
var mask = constants.sequenceLocktimeMask; var mask = constants.sequence.MASK;
var granularity = constants.sequenceLocktimeGranularity; var granularity = constants.sequence.GRANULARITY;
var disableFlag = constants.sequenceLocktimeDisableFlag; var disableFlag = constants.sequence.DISABLE_FLAG;
var typeFlag = constants.sequenceLocktimeTypeFlag; var typeFlag = constants.sequence.TYPE_FLAG;
var hasFlag = flags & constants.flags.VERIFY_SEQUENCE; var hasFlag = flags & constants.flags.VERIFY_SEQUENCE;
var minHeight = -1; var minHeight = -1;
var minTime = -1; var minTime = -1;

View File

@ -101,9 +101,9 @@ ChainBlock.prototype.isGenesis = function isGenesis() {
ChainBlock.prototype.ensureAncestors = function ensureAncestors(callback) { ChainBlock.prototype.ensureAncestors = function ensureAncestors(callback) {
var majorityWindow = network.block.majorityWindow; var majorityWindow = network.block.majorityWindow;
var medianTimespan = constants.block.medianTimespan; var medianTimespan = constants.block.MEDIAN_TIMESPAN;
var powDiffInterval = network.powDiffInterval; var powDiffInterval = network.pow.diffInterval;
var allowMinDiff = network.powAllowMinDifficultyBlocks; var allowMinDiff = network.pow.allowMinDifficultyBlocks;
var max = Math.max(majorityWindow, medianTimespan); var max = Math.max(majorityWindow, medianTimespan);
if ((this.height + 1) % powDiffInterval === 0 || allowMinDiff) if ((this.height + 1) % powDiffInterval === 0 || allowMinDiff)
max = Math.max(max, powDiffInterval); max = Math.max(max, powDiffInterval);
@ -288,7 +288,7 @@ ChainBlock.prototype.getNext = function getNext(callback) {
ChainBlock.prototype.getMedianTime = function getMedianTime(ancestors) { ChainBlock.prototype.getMedianTime = function getMedianTime(ancestors) {
var entry = this; var entry = this;
var median = []; var median = [];
var timeSpan = constants.block.medianTimespan; var timeSpan = constants.block.MEDIAN_TIMESPAN;
var i; var i;
if (!ancestors) if (!ancestors)
@ -358,7 +358,7 @@ ChainBlock.prototype.isSuperMajority = function isSuperMajority(version, require
ChainBlock.prototype.getMedianTimeAsync = function getMedianTimeAsync(callback) { ChainBlock.prototype.getMedianTimeAsync = function getMedianTimeAsync(callback) {
var self = this; var self = this;
return this.getAncestors(constants.block.medianTimespan, function(err, ancestors) { return this.getAncestors(constants.block.MEDIAN_TIMESPAN, function(err, ancestors) {
if (err) if (err)
return callback(err); return callback(err);

View File

@ -60,8 +60,8 @@ function ChainDB(chain, options) {
// Need to cache up to the retarget interval // Need to cache up to the retarget interval
// if we're going to be checking the damn // if we're going to be checking the damn
// target all the time. // target all the time.
if (network.powAllowMinDifficultyBlocks) if (network.pow.allowMinDifficultyBlocks)
this._cacheWindow = network.powDiffInterval + 1; this._cacheWindow = network.pow.diffInterval + 1;
else else
this._cacheWindow = network.block.majorityWindow + 1; this._cacheWindow = network.block.majorityWindow + 1;

View File

@ -343,9 +343,9 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) {
if (cached) if (cached)
return cached; return cached;
hardened = index >= constants.hd.hardened ? true : hardened; hardened = index >= constants.hd.HARDENED ? true : hardened;
if (index < constants.hd.hardened && hardened) if (index < constants.hd.HARDENED && hardened)
index += constants.hd.hardened; index += constants.hd.HARDENED;
p = new BufferWriter(); p = new BufferWriter();
@ -371,7 +371,7 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) {
if (!this.fingerPrint) { if (!this.fingerPrint) {
this.fingerPrint = utils.ripesha(this.publicKey) this.fingerPrint = utils.ripesha(this.publicKey)
.slice(0, constants.hd.parentFingerPrintSize); .slice(0, constants.hd.PARENT_FINGERPRINT_SIZE);
} }
child = new HDPrivateKey({ child = new HDPrivateKey({
@ -456,7 +456,7 @@ HDPrivateKey.prototype.derivePurpose45 = function derivePurpose45() {
HDPrivateKey.prototype.isPurpose45 = function isPurpose45() { HDPrivateKey.prototype.isPurpose45 = function isPurpose45() {
if (this.depth !== 1) if (this.depth !== 1)
return false; 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() { HDPrivateKey.prototype.isAccount44 = function isAccount44() {
if (this.childIndex < constants.hd.hardened) if (this.childIndex < constants.hd.HARDENED)
return false; return false;
return this.depth === 3; return this.depth === 3;
}; };
@ -495,10 +495,10 @@ HDPrivateKey._getIndexes = function _getIndexes(path) {
var indexes = []; var indexes = [];
var i, step, hardened, index; var i, step, hardened, index;
if (~constants.hd.pathRoots.indexOf(path)) if (~constants.hd.PATH_ROOTS.indexOf(path))
return indexes; return indexes;
if (!~constants.hd.pathRoots.indexOf(root)) if (!~constants.hd.PATH_ROOTS.indexOf(root))
return null; return null;
for (i = 0; i < steps.length; i++) { for (i = 0; i < steps.length; i++) {
@ -514,7 +514,7 @@ HDPrivateKey._getIndexes = function _getIndexes(path) {
index = +step; index = +step;
if (hardened) if (hardened)
index += constants.hd.hardened; index += constants.hd.HARDENED;
indexes.push(index); indexes.push(index);
} }
@ -538,9 +538,9 @@ HDPrivateKey.isValidPath = function isValidPath(path, hardened) {
} }
if (typeof path === 'number') { if (typeof path === 'number') {
if (path < constants.hd.hardened && hardened) if (path < constants.hd.HARDENED && hardened)
path += constants.hd.hardened; path += constants.hd.HARDENED;
return path >= 0 && path < constants.hd.maxIndex; return path >= 0 && path < constants.hd.MAX_INDEX;
} }
return false; return false;
@ -579,8 +579,8 @@ HDPrivateKey._fromSeed = function _fromSeed(seed, networkType) {
var data = seed.createSeed(); var data = seed.createSeed();
var hash; var hash;
if (data.length < constants.hd.minEntropy if (data.length < constants.hd.MIN_ENTROPY
|| data.length > constants.hd.maxEntropy) { || data.length > constants.hd.MAX_ENTROPY) {
throw new Error('Entropy not in range.'); throw new Error('Entropy not in range.');
} }
@ -965,7 +965,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) {
if (cached) if (cached)
return cached; return cached;
if (index >= constants.hd.hardened || hardened) if (index >= constants.hd.HARDENED || hardened)
throw new Error('Invalid index.'); throw new Error('Invalid index.');
if (index < 0) if (index < 0)
@ -986,7 +986,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) {
if (!this.fingerPrint) { if (!this.fingerPrint) {
this.fingerPrint = utils.ripesha(this.publicKey) this.fingerPrint = utils.ripesha(this.publicKey)
.slice(0, constants.hd.parentFingerPrintSize); .slice(0, constants.hd.PARENT_FINGERPRINT_SIZE);
} }
child = new HDPublicKey({ child = new HDPublicKey({
@ -1058,7 +1058,7 @@ HDPublicKey.isValidPath = function isValidPath(arg) {
} }
if (typeof arg === 'number') if (typeof arg === 'number')
return arg >= 0 && arg < constants.hd.hardened; return arg >= 0 && arg < constants.hd.HARDENED;
return false; return false;
}; };

View File

@ -67,7 +67,7 @@ HTTPServer.prototype._init = function _init() {
} }
res.setHeader('X-Bcoin-Network', network.type); res.setHeader('X-Bcoin-Network', network.type);
res.setHeader('X-Bcoin-Version', constants.userAgent); res.setHeader('X-Bcoin-Version', constants.USER_AGENT);
next(); next();
}); });
@ -182,7 +182,7 @@ HTTPServer.prototype._init = function _init() {
this.get('/', function(req, res, next, send) { this.get('/', function(req, res, next, send) {
send(200, { send(200, {
version: constants.userAgent, version: constants.USER_AGENT,
network: network.type network: network.type
}); });
}); });
@ -603,7 +603,7 @@ HTTPServer.prototype._initIO = function _initIO() {
self.emit('websocket', socket); self.emit('websocket', socket);
socket.emit('version', { socket.emit('version', {
version: constants.userAgent, version: constants.USER_AGENT,
network: network.type network: network.type
}); });
}); });

View File

@ -181,7 +181,7 @@ Input.prototype.isFinal = function isFinal() {
*/ */
Input.prototype.isCoinbase = function isCoinbase() { Input.prototype.isCoinbase = function isCoinbase() {
return this.prevout.hash === constants.nullHash; return this.prevout.hash === constants.NULL_HASH;
}; };
/** /**

View File

@ -753,7 +753,7 @@ Mempool.prototype.verify = function verify(tx, callback) {
0)); 0));
} }
if (tx.getSigops(true) > constants.tx.maxSigops) { if (tx.getSigops(true) > constants.tx.MAX_SIGOPS) {
return callback(new VerifyError(tx, return callback(new VerifyError(tx,
'nonstandard', 'nonstandard',
'bad-txns-too-many-sigops', 'bad-txns-too-many-sigops',
@ -1292,10 +1292,10 @@ Mempool.prototype.checkLocks = function checkLocks(tx, flags, callback) {
var tip = this.chain.tip; var tip = this.chain.tip;
var index = new bcoin.chainblock(this.chain, { var index = new bcoin.chainblock(this.chain, {
hash: utils.toHex(constants.zeroHash), hash: utils.toHex(constants.ZERO_HASH),
version: tip.version, version: tip.version,
prevBlock: tip.hash, prevBlock: tip.hash,
merkleRoot: utils.toHex(constants.zeroHash), merkleRoot: utils.toHex(constants.ZERO_HASH),
ts: utils.now(), ts: utils.now(),
bits: 0, bits: 0,
nonce: 0, nonce: 0,

View File

@ -336,7 +336,7 @@ function MinerBlock(options) {
this.coinbase.addInput({ this.coinbase.addInput({
prevout: { prevout: {
hash: constants.nullHash, hash: constants.NULL_HASH,
index: 0xffffffff index: 0xffffffff
}, },
coin: null, coin: null,
@ -369,7 +369,7 @@ function MinerBlock(options) {
this.block = new bcoin.block({ this.block = new bcoin.block({
version: options.version, version: options.version,
prevBlock: this.tip.hash, prevBlock: this.tip.hash,
merkleRoot: constants.nullHash, merkleRoot: constants.NULL_HASH,
ts: Math.max(utils.now(), this.tip.ts + 1), ts: Math.max(utils.now(), this.tip.ts + 1),
bits: options.target, bits: options.target,
nonce: 0, nonce: 0,
@ -444,7 +444,7 @@ MinerBlock.prototype.addTX = function addTX(tx) {
var size = this.block.getVirtualSize(true) + tx.getVirtualSize(); var size = this.block.getVirtualSize(true) + tx.getVirtualSize();
// Deliver me from the block size debate, please // Deliver me from the block size debate, please
if (size > constants.block.maxSize) if (size > constants.block.MAX_SIZE)
return false; return false;
if (this.block.hasTX(tx)) if (this.block.hasTX(tx))

View File

@ -137,8 +137,8 @@ MTX.prototype.witnessHash = function witnessHash(enc) {
if (this.isCoinbase()) { if (this.isCoinbase()) {
return enc === 'hex' return enc === 'hex'
? utils.toHex(constants.zeroHash) ? utils.toHex(constants.ZERO_HASH)
: utils.slice(constants.zeroHash); : utils.slice(constants.ZERO_HASH);
} }
if (!this.hasWitness()) if (!this.hasWitness())
@ -459,7 +459,7 @@ MTX.prototype.createSignature = function createSignature(index, prev, key, type,
type = 'all'; type = 'all';
if (typeof type === 'string') if (typeof type === 'string')
type = constants.hashType[type]; type = constants.hashType[type.toUpperCase()];
// Get the hash of the current tx, minus the other // Get the hash of the current tx, minus the other
// inputs, plus the sighash type. // inputs, plus the sighash type.
@ -1109,7 +1109,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) {
continue; continue;
if (network.height !== -1 && coin.coinbase) { 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; continue;
} }
@ -1135,7 +1135,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) {
// Transfer `total` funds maximum. // Transfer `total` funds maximum.
addCoins(); addCoins();
} else { } else {
fee = new bn(constants.tx.minFee); fee = new bn(constants.tx.MIN_FEE);
// Transfer `total` funds maximum. // Transfer `total` funds maximum.
addCoins(); addCoins();
@ -1146,7 +1146,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) {
address: options.changeAddress, address: options.changeAddress,
// In case we don't have a change address, // In case we don't have a change address,
// use a fake p2pkh output to gauge size. // 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) value: new bn(0)
}); });
@ -1187,7 +1187,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) {
// Attempt to subtract fee. // Attempt to subtract fee.
if (options.subtractFee != null) { if (options.subtractFee != null) {
minValue = fee.addn(constants.tx.dustThreshold); minValue = fee.addn(constants.tx.DUST_THRESHOLD);
if (typeof options.subtractFee === 'number') { if (typeof options.subtractFee === 'number') {
i = options.subtractFee; i = options.subtractFee;
@ -1241,7 +1241,7 @@ MTX.prototype.fill = function fill(coins, options) {
for (i = 0; i < result.coins.length; i++) for (i = 0; i < result.coins.length; i++)
this.addInput(result.coins[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. // Do nothing. Change is added to fee.
assert(this.getFee().cmp(result.fee.add(result.change)) === 0); assert(this.getFee().cmp(result.fee.add(result.change)) === 0);
this.changeIndex = -1; this.changeIndex = -1;

View File

@ -318,20 +318,20 @@ Peer.prototype.broadcast = function broadcast(items) {
var entry, packetType; var entry, packetType;
if (typeof type === 'string') if (typeof type === 'string')
type = constants.inv[type]; type = constants.inv[type.toUpperCase()];
// INV does not set the witness // INV does not set the witness
// mask (only GETDATA does this). // mask (only GETDATA does this).
type &= ~constants.invWitnessMask; type &= ~constants.WITNESS_MASK;
if (type === constants.inv.block) if (type === constants.inv.BLOCK)
packetType = 'block'; packetType = 'block';
else if (type === constants.inv.tx) else if (type === constants.inv.TX)
packetType = 'tx'; packetType = 'tx';
else else
assert(false, 'Bad type.'); assert(false, 'Bad type.');
if (self.filter && type === constants.inv.tx) { if (self.filter && type === constants.inv.TX) {
if (!item.isWatched(self.filter)) if (!item.isWatched(self.filter))
return; return;
} }
@ -395,7 +395,7 @@ Peer.prototype.updateWatch = function updateWatch() {
filter: this.bloom.toBuffer(), filter: this.bloom.toBuffer(),
n: this.bloom.n, n: this.bloom.n,
tweak: this.bloom.tweak, tweak: this.bloom.tweak,
update: 'none' update: constants.filterFlags.NONE
})); }));
} }
}; };
@ -924,7 +924,7 @@ Peer.prototype._handleGetBlocks = function _handleGetBlocks(payload) {
if (!hash) if (!hash)
return done(); return done();
blocks.push({ type: constants.inv.block, hash: hash }); blocks.push({ type: constants.inv.BLOCK, hash: hash });
if (hash === payload.stop) if (hash === payload.stop)
return done(); return done();
@ -941,7 +941,7 @@ Peer.prototype._handleGetBlocks = function _handleGetBlocks(payload) {
}; };
Peer.prototype._handleVersion = function handleVersion(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._error('Peer doesn\'t support required protocol version.');
this.setMisbehavior(100); this.setMisbehavior(100);
return; return;
@ -1011,7 +1011,7 @@ Peer.prototype._handleMempool = function _handleMempool() {
return self.emit('error', err); return self.emit('error', err);
for (i = 0; i < hashes.length; i++) for (i = 0; i < hashes.length; i++)
items.push({ type: constants.inv.tx, hash: hashes[i] }); items.push({ type: constants.inv.TX, hash: hashes[i] });
bcoin.debug('Sending mempool snapshot to %s.', self.host); bcoin.debug('Sending mempool snapshot to %s.', self.host);
@ -1033,7 +1033,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
hash = utils.toHex(item.hash); hash = utils.toHex(item.hash);
entry = this._broadcast.map[hash]; entry = this._broadcast.map[hash];
isWitness = item.type & constants.invWitnessMask; isWitness = item.type & constants.WITNESS_MASK;
value = null; value = null;
if (!entry) { if (!entry) {
@ -1041,7 +1041,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
continue; continue;
} }
if ((item.type & ~constants.invWitnessMask) !== entry.type) { if ((item.type & ~constants.WITNESS_MASK) !== entry.type) {
bcoin.debug( bcoin.debug(
'Peer %s requested an existing item with the wrong type.', 'Peer %s requested an existing item with the wrong type.',
this.host); this.host);
@ -1067,14 +1067,14 @@ Peer.prototype._handleGetData = function handleGetData(items) {
return; return;
utils.forEachSerial(check, function(item, next) { utils.forEachSerial(check, function(item, next) {
var isWitness = item.type & constants.invWitnessMask; var isWitness = item.type & constants.WITNESS_MASK;
var type = item.type & ~constants.invWitnessMask; var type = item.type & ~constants.WITNESS_MASK;
var hash = utils.toHex(item.hash); var hash = utils.toHex(item.hash);
var i, tx, data; var i, tx, data;
if (type === constants.inv.tx) { if (type === constants.inv.TX) {
if (!self.mempool) { if (!self.mempool) {
notfound.push({ type: constants.inv.tx, hash: hash }); notfound.push({ type: constants.inv.TX, hash: hash });
return next(); return next();
} }
return self.mempool.getTX(hash, function(err, tx) { return self.mempool.getTX(hash, function(err, tx) {
@ -1082,7 +1082,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
return next(err); return next(err);
if (!tx) { if (!tx) {
notfound.push({ type: constants.inv.tx, hash: hash }); notfound.push({ type: constants.inv.TX, hash: hash });
return next(); 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) { if (self.chain.db.options.spv) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return next(); return next();
} }
if (self.chain.db.options.prune) { if (self.chain.db.options.prune) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return; return;
} }
return self.chain.db.getBlock(hash, function(err, block) { return self.chain.db.getBlock(hash, function(err, block) {
@ -1111,7 +1111,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
return next(err); return next(err);
if (!block) { if (!block) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return next(); return next();
} }
@ -1124,7 +1124,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
if (hash === self.hashContinue) { if (hash === self.hashContinue) {
self._write(self.framer.inv([{ self._write(self.framer.inv([{
type: constants.inv.block, type: constants.inv.BLOCK,
hash: self.chain.tip.hash hash: self.chain.tip.hash
}])); }]));
self.hashContinue = null; 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) { if (self.chain.db.options.spv) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return next(); return next();
} }
if (self.chain.db.options.prune) { if (self.chain.db.options.prune) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return; return;
} }
return self.chain.db.getBlock(hash, function(err, block) { return self.chain.db.getBlock(hash, function(err, block) {
@ -1148,7 +1148,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
return next(err); return next(err);
if (!block) { if (!block) {
notfound.push({ type: constants.inv.block, hash: hash }); notfound.push({ type: constants.inv.BLOCK, hash: hash });
return next(); return next();
} }
@ -1169,7 +1169,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
if (hash === self.hashContinue) { if (hash === self.hashContinue) {
self._write(self.framer.inv([{ self._write(self.framer.inv([{
type: constants.inv.block, type: constants.inv.BLOCK,
hash: self.chain.tip.hash hash: self.chain.tip.hash
}])); }]));
self.hashContinue = null; self.hashContinue = null;
@ -1295,9 +1295,9 @@ Peer.prototype._handleInv = function handleInv(items) {
for (i = 0; i < items.length; i++) { for (i = 0; i < items.length; i++) {
item = items[i]; item = items[i];
if (item.type === constants.inv.tx) if (item.type === constants.inv.TX)
txs.push(item.hash); txs.push(item.hash);
else if (item.type === constants.inv.block) else if (item.type === constants.inv.BLOCK)
blocks.push(item.hash); blocks.push(item.hash);
} }

View File

@ -151,19 +151,19 @@ function Pool(options) {
versionHeight: 0, versionHeight: 0,
bestHash: null, bestHash: null,
type: !options.spv type: !options.spv
? constants.inv.block ? constants.inv.BLOCK
: constants.inv.filteredblock : constants.inv.FILTERED_BLOCK
}; };
this.tx = { this.tx = {
state: {}, state: {},
count: 0, count: 0,
type: constants.inv.tx type: constants.inv.TX
}; };
if (this.options.witness) { if (this.options.witness) {
this.block.type |= constants.invWitnessMask; this.block.type |= constants.WITNESS_MASK;
this.tx.type |= constants.invWitnessMask; this.tx.type |= constants.WITNESS_MASK;
} }
this.request = { this.request = {
@ -2162,7 +2162,7 @@ Pool.prototype.removeSeed = function removeSeed(seed) {
Pool.prototype.setMisbehavior = function setMisbehavior(peer, score) { Pool.prototype.setMisbehavior = function setMisbehavior(peer, score) {
peer.banScore += score; peer.banScore += score;
if (peer.banScore >= constants.banScore) { if (peer.banScore >= constants.BAN_SCORE) {
this.peers.misbehaving[peer.host] = utils.now(); this.peers.misbehaving[peer.host] = utils.now();
bcoin.debug('Ban threshold exceeded for %s', peer.host); bcoin.debug('Ban threshold exceeded for %s', peer.host);
peer.destroy(); peer.destroy();
@ -2187,7 +2187,7 @@ Pool.prototype.isMisbehaving = function isMisbehaving(host) {
time = this.peers.misbehaving[host]; time = this.peers.misbehaving[host];
if (time) { if (time) {
if (utils.now() > time + constants.banTime) { if (utils.now() > time + constants.BAN_TIME) {
delete this.peers.misbehaving[host]; delete this.peers.misbehaving[host];
peer = this.getPeer(host); peer = this.getPeer(host);
if (peer) if (peer)

View File

@ -18,7 +18,7 @@ var utils = require('../utils');
* @default * @default
*/ */
exports.minVersion = 70001; exports.MIN_VERSION = 70001;
/** /**
* BCoin's protocol version. * BCoin's protocol version.
@ -26,7 +26,7 @@ exports.minVersion = 70001;
* @default * @default
*/ */
exports.version = 70012; exports.VERSION = 70012;
/** /**
* Max message size (~4mb with segwit, formerly 2mb) * Max message size (~4mb with segwit, formerly 2mb)
@ -34,7 +34,7 @@ exports.version = 70012;
* @default * @default
*/ */
exports.maxMessage = 4 * 1000 * 1000; exports.MAX_MESSAGE = 4 * 1000 * 1000;
/** /**
* Service bits. * Service bits.
@ -43,10 +43,10 @@ exports.maxMessage = 4 * 1000 * 1000;
*/ */
exports.services = { exports.services = {
network: (1 << 0), NETWORK: (1 << 0),
getutxo: (1 << 1), GETUTXO: (1 << 1),
bloom: (1 << 2), BLOOM: (1 << 2),
witness: (1 << 3) WITNESS: (1 << 3)
}; };
/** /**
@ -55,8 +55,7 @@ exports.services = {
* @default * @default
*/ */
exports.localServices = exports.services.network exports.LOCAL_SERVICES = exports.services.NETWORK | exports.services.WITNESS;
| exports.services.witness;
/** /**
* Inv types. * Inv types.
@ -65,13 +64,13 @@ exports.localServices = exports.services.network
*/ */
exports.inv = { exports.inv = {
error: 0, ERROR: 0,
tx: 1, TX: 1,
block: 2, BLOCK: 2,
filteredblock: 3, FILTERED_BLOCK: 3,
witnesstx: 1 | (1 << 30), WITNESS_TX: 1 | (1 << 30),
witnessblock: 2 | (1 << 30), WITNESS_BLOCK: 2 | (1 << 30),
witnessfilteredblock: 3 | (1 << 30) WITNESS_FILTERED_BLOCK: 3 | (1 << 30)
}; };
/** /**
@ -93,7 +92,7 @@ exports.invByVal = utils.revMap(exports.inv);
* @default * @default
*/ */
exports.invWitnessMask = 1 << 30; exports.WITNESS_MASK = 1 << 30;
/** /**
* Bloom filter update flags. * Bloom filter update flags.
@ -102,9 +101,9 @@ exports.invWitnessMask = 1 << 30;
*/ */
exports.filterFlags = { exports.filterFlags = {
none: 0, NONE: 0,
all: 1, ALL: 1,
pubkeyOnly: 2 PUBKEY_ONLY: 2
}; };
/** /**
@ -268,7 +267,7 @@ exports.opcodesByVal = utils.revMap(exports.opcodes);
* @default * @default
*/ */
exports.coin = new bn(10000000).muln(10); exports.COIN = new bn(10000000).muln(10);
/** /**
* One bitcoin / 100. * One bitcoin / 100.
@ -276,7 +275,7 @@ exports.coin = new bn(10000000).muln(10);
* @default * @default
*/ */
exports.cent = new bn(1000000); exports.CENT = new bn(1000000);
/** /**
* Maximum amount of money in satoshis (1btc * 21million) * Maximum amount of money in satoshis (1btc * 21million)
@ -284,7 +283,7 @@ exports.cent = new bn(1000000);
* @default * @default
*/ */
exports.maxMoney = new bn(21000000).mul(exports.coin); exports.MAX_MONEY = new bn(21000000).mul(exports.COIN);
/** /**
* Sighash Types. * Sighash Types.
@ -293,10 +292,10 @@ exports.maxMoney = new bn(21000000).mul(exports.coin);
*/ */
exports.hashType = { exports.hashType = {
all: 1, ALL: 1,
none: 2, NONE: 2,
single: 3, SINGLE: 3,
anyonecanpay: 0x80 ANYONECANPAY: 0x80
}; };
/** /**
@ -313,12 +312,12 @@ exports.hashTypeByVal = utils.revMap(exports.hashType);
*/ */
exports.block = { exports.block = {
maxSize: 1000000, MAX_SIZE: 1000000,
maxSigops: 1000000 / 50, MAX_SIGOPS: 1000000 / 50,
maxOrphanTx: 1000000 / 100, MAX_ORPHAN_TX: 1000000 / 100,
medianTimespan: 11, MEDIAN_TIMESPAN: 11,
bip16time: 1333238400, BIP16_TIME: 1333238400,
sighashLimit: 1300000000 SIGHASH_LIMIT: 1300000000
}; };
/** /**
@ -328,16 +327,16 @@ exports.block = {
*/ */
exports.tx = { exports.tx = {
version: 2, MAX_VERSION: 2,
maxSize: 100000, MAX_SIZE: 100000,
minFee: 10000, MIN_FEE: 10000,
bareMultisig: true, BARE_MULTISIG: true,
freeThreshold: exports.coin.muln(144).divn(250), FREE_THRESHOLD: exports.COIN.muln(144).divn(250),
maxSigops: exports.block.maxSigops / 5, MAX_SIGOPS: exports.block.MAX_SIGOPS / 5,
coinbaseMaturity: 100 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. * Script-related constants.
@ -346,14 +345,14 @@ exports.tx.dustThreshold = 182 * exports.tx.minFee / 1000 * 3;
*/ */
exports.script = { exports.script = {
maxSize: 10000, MAX_SIZE: 10000,
maxStack: 1000, MAX_STACK: 1000,
maxPush: 520, MAX_PUSH: 520,
maxOps: 201, MAX_OPS: 201,
maxPubkeysPerMultisig: 20, MAX_MULTISIG_PUBKEYS: 20,
maxScripthashSigops: 15, MAX_SCRIPTHASH_SIGOPS: 15,
maxOpReturnBytes: 83, MAX_OP_RETURN_BYTES: 83,
maxOpReturn: 80 MAX_OP_RETURN: 80
}; };
/** /**
@ -364,19 +363,19 @@ exports.script = {
*/ */
exports.reject = { exports.reject = {
malformed: 0x01, MALFORMED: 0x01,
invalid: 0x10, INVALID: 0x10,
obsolete: 0x11, OBSOLETE: 0x11,
duplicate: 0x12, DUPLICATE: 0x12,
nonstandard: 0x40, NONSTANDARD: 0x40,
dust: 0x41, DUST: 0x41,
insufficientfee: 0x42, INSUFFICIENTFEE: 0x42,
checkpoint: 0x43, CHECKPOINT: 0x43,
// Internal codes (NOT FOR USE ON NETWORK) // Internal codes (NOT FOR USE ON NETWORK)
internal: 0x100, INTERNAL: 0x100,
highfee: 0x100, HIGHFEE: 0x100,
alreadyknown: 0x101, ALREADYKNOWN: 0x101,
conflict: 0x102 CONFLICT: 0x102
}; };
/** /**
@ -393,12 +392,12 @@ exports.rejectByVal = utils.revMap(exports.reject);
*/ */
exports.hd = { exports.hd = {
hardened: 0x80000000, HARDENED: 0x80000000,
maxIndex: 2 * 0x80000000, MAX_INDEX: 2 * 0x80000000,
minEntropy: 128 / 8, MIN_ENTROPY: 128 / 8,
maxEntropy: 512 / 8, MAX_ENTROPY: 512 / 8,
parentFingerPrintSize: 4, PARENT_FINGERPRINT_SIZE: 4,
pathRoots: ['m', 'M', 'm\'', 'M\''] PATH_ROOTS: ['m', 'M', 'm\'', 'M\'']
}; };
/** /**
@ -409,35 +408,37 @@ exports.hd = {
* @default * @default
*/ */
exports.locktimeThreshold = 500000000; exports.LOCKTIME_THRESHOLD = 500000000;
exports.sequence = {};
/** /**
* Highest nSequence bit (disables sequence locktimes). * Highest nSequence bit (disables sequence locktimes).
* @const {Number} * @const {Number}
*/ */
exports.sequenceLocktimeDisableFlag = (1 << 31) >>> 0; exports.sequence.DISABLE_FLAG = (1 << 31) >>> 0;
/** /**
* @const {Number} * @const {Number}
* @default * @default
*/ */
exports.sequenceLocktimeTypeFlag = 1 << 22; exports.sequence.TYPE_FLAG = 1 << 22;
/** /**
* @const {Number} * @const {Number}
* @default * @default
*/ */
exports.sequenceLocktimeGranularity = 9; exports.sequence.GRANULARITY = 9;
/** /**
* @const {Number} * @const {Number}
* @default * @default
*/ */
exports.sequenceLocktimeMask = 0x0000ffff; exports.sequence.MASK = 0x0000ffff;
/** /**
* A hash of all zeroes with a `1` at the * A hash of all zeroes with a `1` at the
@ -446,7 +447,7 @@ exports.sequenceLocktimeMask = 0x0000ffff;
* @default * @default
*/ */
exports.oneHash = new Buffer( exports.ONE_HASH = new Buffer(
'0000000000000000000000000000000000000000000000000000000000000001', '0000000000000000000000000000000000000000000000000000000000000001',
'hex' 'hex'
); );
@ -457,7 +458,7 @@ exports.oneHash = new Buffer(
* @default * @default
*/ */
exports.zeroHash = new Buffer( exports.ZERO_HASH = new Buffer(
'0000000000000000000000000000000000000000000000000000000000000000', '0000000000000000000000000000000000000000000000000000000000000000',
'hex' 'hex'
); );
@ -468,7 +469,7 @@ exports.zeroHash = new Buffer(
* @default * @default
*/ */
exports.nullHash = exports.NULL_HASH =
'0000000000000000000000000000000000000000000000000000000000000000'; '0000000000000000000000000000000000000000000000000000000000000000';
/** /**
@ -477,7 +478,7 @@ exports.nullHash =
* @default * @default
*/ */
exports.userVersion = require('../../../package.json').version; exports.USER_VERSION = require('../../../package.json').version;
/** /**
* BCoin user agent: `/bcoin:{version}/`. * BCoin user agent: `/bcoin:{version}/`.
@ -485,10 +486,23 @@ exports.userVersion = require('../../../package.json').version;
* @default * @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}. * Script and locktime flags. See {@link VerifyFlags}.

View File

@ -19,7 +19,7 @@ var DUMMY = new Buffer([]);
* @exports Framer * @exports Framer
* @constructor * @constructor
* @param {Object} options * @param {Object} options
* @param {String} options.userAgent - User agent string. * @param {String} options.USER_AGENT - User agent string.
* @property {Buffer} agent * @property {Buffer} agent
*/ */
@ -31,7 +31,7 @@ function Framer(options) {
this.options = 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) { Framer.version = function version(options, writer) {
var p = new BufferWriter(writer); var p = new BufferWriter(writer);
var agent = options.agent || constants.userAgent; var agent = options.agent || constants.USER_AGENT;
var remote = options.remote || {}; var remote = options.remote || {};
var local = options.local || {}; var local = options.local || {};
@ -435,10 +435,10 @@ Framer.version = function version(options, writer) {
agent = new Buffer(agent, 'ascii'); agent = new Buffer(agent, 'ascii');
if (local.services == null) if (local.services == null)
local.services = constants.localServices; local.services = constants.LOCAL_SERVICES;
p.write32(constants.version); p.write32(constants.VERSION);
p.writeU64(constants.localServices); p.writeU64(constants.LOCAL_SERVICES);
p.write64(utils.now()); p.write64(utils.now());
Framer.address(remote, false, p); Framer.address(remote, false, p);
Framer.address(local, false, p); Framer.address(local, false, p);
@ -474,7 +474,7 @@ Framer._inv = function _inv(items, writer) {
for (i = 0; i < items.length; i++) { for (i = 0; i < items.length; i++) {
type = items[i].type; type = items[i].type;
if (typeof type === 'string') if (typeof type === 'string')
type = constants.inv[items[i].type]; type = constants.inv[items[i].type.toUpperCase()];
assert(constants.invByVal[type] != null); assert(constants.invByVal[type] != null);
p.writeU32(type); p.writeU32(type);
p.writeHash(items[i].hash); p.writeHash(items[i].hash);
@ -564,7 +564,7 @@ Framer.filterLoad = function filterLoad(data, writer) {
var update = data.update; var update = data.update;
if (typeof update === 'string') if (typeof update === 'string')
update = constants.filterFlags[update]; update = constants.filterFlags[update.toUpperCase()];
assert(update != null, 'Bad filter flag.'); assert(update != null, 'Bad filter flag.');
@ -608,7 +608,7 @@ Framer._getBlocks = function _getBlocks(data, writer, headers) {
var p, i; var p, i;
if (!version) if (!version)
version = constants.version; version = constants.VERSION;
if (!locator) { if (!locator) {
if (headers) if (headers)
@ -618,7 +618,7 @@ Framer._getBlocks = function _getBlocks(data, writer, headers) {
} }
if (!stop) if (!stop)
stop = constants.zeroHash; stop = constants.ZERO_HASH;
p = new BufferWriter(writer); p = new BufferWriter(writer);
@ -1038,10 +1038,16 @@ Framer.blockHeaders = function blockHeaders(block, writer) {
Framer.reject = function reject(details, writer) { Framer.reject = function reject(details, writer) {
var p = new BufferWriter(writer); var p = new BufferWriter(writer);
var ccode = constants.reject[details.ccode] || constants.reject.invalid; var ccode = details.ccode;
if (ccode >= constants.reject.internal) if (typeof ccode === 'string')
ccode = constants.reject.invalid; 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.writeVarString(details.message || '', 'ascii');
p.writeU8(ccode); p.writeU8(ccode);

View File

@ -210,12 +210,14 @@ main.genesis = {
main.magic = 0xd9b4bef9; main.magic = 0xd9b4bef9;
main.pow = {};
/** /**
* Default target. * Default target.
* @const {Buffer} * @const {Buffer}
*/ */
main.powLimit = new bn( main.pow.limit = new bn(
'00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex' 'hex'
); );
@ -226,7 +228,7 @@ main.powLimit = new bn(
* @default * @default
*/ */
main.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks main.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks
/** /**
* Average block time. * Average block time.
@ -234,7 +236,7 @@ main.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks
* @default * @default
*/ */
main.powTargetSpacing = 10 * 60; main.pow.targetSpacing = 10 * 60;
/** /**
* Retarget interval in blocks. * Retarget interval in blocks.
@ -242,21 +244,21 @@ main.powTargetSpacing = 10 * 60;
* @default * @default
*/ */
main.powDiffInterval = main.powTargetTimespan / main.powTargetSpacing | 0; main.pow.diffInterval = main.pow.targetTimespan / main.pow.targetSpacing | 0;
/** /**
* @const {Boolean} * @const {Boolean}
* @default * @default
*/ */
main.powAllowMinDifficultyBlocks = false; main.pow.allowMinDifficultyBlocks = false;
/** /**
* @const {Boolean} * @const {Boolean}
* @default * @default
*/ */
main.powNoRetargeting = false; main.pow.noRetargeting = false;
/** /**
* Block constants. * Block constants.
@ -410,15 +412,17 @@ testnet.genesis = {
testnet.magic = 0x0709110b; testnet.magic = 0x0709110b;
testnet.powLimit = new bn( testnet.pow = {};
testnet.pow.limit = new bn(
'00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex' 'hex'
); );
testnet.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks testnet.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks
testnet.powTargetSpacing = 10 * 60; testnet.pow.targetSpacing = 10 * 60;
testnet.powDiffInterval = testnet.powTargetTimespan / testnet.powTargetSpacing | 0; testnet.pow.diffInterval = testnet.pow.targetTimespan / testnet.pow.targetSpacing | 0;
testnet.powAllowMinDifficultyBlocks = true; testnet.pow.allowMinDifficultyBlocks = true;
testnet.powNoRetargeting = false; testnet.pow.noRetargeting = false;
testnet.block = { testnet.block = {
majorityEnforceUpgrade: 51, majorityEnforceUpgrade: 51,
@ -506,15 +510,17 @@ regtest.genesis = {
regtest.magic = 0xdab5bffa; regtest.magic = 0xdab5bffa;
regtest.powLimit = new bn( regtest.pow = {};
regtest.pow.limit = new bn(
'7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex' 'hex'
); );
regtest.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks regtest.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks
regtest.powTargetSpacing = 10 * 60; regtest.pow.targetSpacing = 10 * 60;
regtest.powDiffInterval = regtest.powTargetTimespan / regtest.powTargetSpacing | 0; regtest.pow.diffInterval = regtest.pow.targetTimespan / regtest.pow.targetSpacing | 0;
regtest.powAllowMinDifficultyBlocks = true; regtest.pow.allowMinDifficultyBlocks = true;
regtest.powNoRetargeting = true; regtest.pow.noRetargeting = true;
regtest.block = { regtest.block = {
majorityEnforceUpgrade: 750, majorityEnforceUpgrade: 750,
@ -615,15 +621,17 @@ segnet3.genesis = {
segnet3.magic = 0xcaea962e; segnet3.magic = 0xcaea962e;
segnet3.powLimit = new bn( segnet3.pow = {};
segnet3.pow.limit = new bn(
'00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex' 'hex'
); );
segnet3.powTargetTimespan = 14 * 24 * 60 * 60; // two weeks segnet3.pow.targetTimespan = 14 * 24 * 60 * 60; // two weeks
segnet3.powTargetSpacing = 10 * 60; segnet3.pow.targetSpacing = 10 * 60;
segnet3.powDiffInterval = segnet3.powTargetTimespan / segnet3.powTargetSpacing | 0; segnet3.pow.diffInterval = segnet3.pow.targetTimespan / segnet3.pow.targetSpacing | 0;
segnet3.powAllowMinDifficultyBlocks = true; segnet3.pow.allowMinDifficultyBlocks = true;
segnet3.powNoRetargeting = false; segnet3.pow.noRetargeting = false;
segnet3.block = { segnet3.block = {
majorityEnforceUpgrade: 7, majorityEnforceUpgrade: 7,
@ -657,7 +665,9 @@ segnet4.port = 28901;
segnet4.segwitHeight = -1; segnet4.segwitHeight = -1;
segnet4.magic = 0xc4a1abdc; segnet4.magic = 0xc4a1abdc;
segnet4.powLimit = new bn( segnet4.pow = utils.merge({}, segnet3.pow);
segnet4.pow.limit = new bn(
// 512x lower min difficulty than mainnet // 512x lower min difficulty than mainnet
'000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', '000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff',
'hex' 'hex'

View File

@ -88,7 +88,7 @@ Parser.prototype.feed = function feed(data) {
*/ */
Parser.prototype.parse = function parse(chunk) { 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)); return this._error('Packet too large: %dmb.', utils.mb(chunk.length));
if (this.packet === null) { if (this.packet === null) {
@ -138,7 +138,7 @@ Parser.prototype.parseHeader = function parseHeader(h) {
cmd = h.toString('ascii', 4, 4 + i); cmd = h.toString('ascii', 4, 4 + i);
this.waiting = utils.readU32(h, 16); 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 this._error('Packet length too large: %dmb', utils.mb(this.waiting));
return { return {
@ -276,9 +276,9 @@ Parser.parseFilterLoad = function parseFilterLoad(p) {
filter = p.readVarBytes(); filter = p.readVarBytes();
n = p.readU32(); n = p.readU32();
tweak = 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 { return {
filter: filter, filter: filter,
@ -553,7 +553,7 @@ Parser.parsePong = function parsePong(p) {
* @property {Number?} port - Port. * @property {Number?} port - Port.
* @property {Boolean?} network - Whether network services are enabled. * @property {Boolean?} network - Whether network services are enabled.
* @property {Boolean?} getutxo - Whether peer supports getutxos. * @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 {Boolean?} witness - Whether peer supports segwit.
* @property {Number} _size * @property {Number} _size
*/ */
@ -607,10 +607,10 @@ Parser.parseVersion = function parseVersion(p) {
return { return {
version: version, version: version,
services: services, services: services,
network: (services & constants.services.network) !== 0, network: (services & constants.services.NETWORK) !== 0,
getutxo: (services & constants.services.getutxo) !== 0, getutxo: (services & constants.services.GETUTXO) !== 0,
bloom: (services & constants.services.bloom) !== 0, bloom: (services & constants.services.BLOOM) !== 0,
witness: (services & constants.services.witness) !== 0, witness: (services & constants.services.WITNESS) !== 0,
ts: ts, ts: ts,
local: recv, local: recv,
remote: from, remote: from,
@ -676,7 +676,7 @@ Parser._parseGetBlocks = function _parseGetBlocks(p) {
stop = p.readHash('hex'); stop = p.readHash('hex');
if (stop === constants.nullHash) if (stop === constants.NULL_HASH)
stop = null; stop = null;
return { return {
@ -1353,10 +1353,10 @@ Parser.parseAddress = function parseAddress(p, full) {
return { return {
ts: ts, ts: ts,
services: services, services: services,
network: (services & constants.services.network) !== 0, network: (services & constants.services.NETWORK) !== 0,
getutxo: (services & constants.services.getutxo) !== 0, getutxo: (services & constants.services.GETUTXO) !== 0,
bloom: (services & constants.services.bloom) !== 0, bloom: (services & constants.services.BLOOM) !== 0,
witness: (services & constants.services.witness) !== 0, witness: (services & constants.services.WITNESS) !== 0,
ipv6: utils.array2ip(ip, 6), ipv6: utils.array2ip(ip, 6),
ipv4: utils.array2ip(ip, 4), ipv4: utils.array2ip(ip, 4),
port: port, port: port,

View File

@ -913,14 +913,14 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version
stack.state.length = 0; stack.state.length = 0;
stack.negate = 0; stack.negate = 0;
if (this.getSize() > constants.script.maxSize) if (this.getSize() > constants.script.MAX_SIZE)
throw new ScriptError('Script too large.'); throw new ScriptError('Script too large.');
for (ip = 0; ip < this.code.length; ip++) { for (ip = 0; ip < this.code.length; ip++) {
op = this.code[ip]; op = this.code[ip];
if (Buffer.isBuffer(op)) { 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); throw new ScriptError('Push data too large.', op, ip);
// Note that minimaldata is not checked // Note that minimaldata is not checked
// on unexecuted branches of code. // on unexecuted branches of code.
@ -932,7 +932,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version
continue; 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); throw new ScriptError('Too many opcodes.', op, ip);
// It's very important to make a distiction // 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(); 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); throw new ScriptError('`n` is out of bounds.', op, ip);
if (stack.length < n + 1) 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(); locktime = locktime.uand(utils.U32).toNumber();
if ((locktime & constants.sequenceLocktimeDisableFlag) !== 0) if ((locktime & constants.sequence.DISABLE_FLAG) !== 0)
break; break;
if (!Script.checkSequence(locktime, tx, index)) if (!Script.checkSequence(locktime, tx, index))
@ -1522,7 +1522,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version
v2 = stack.pop(); v2 = stack.pop();
v1 = stack.pop(); v1 = stack.pop();
stack.push(Buffer.concat([v1, v2])); 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); throw new ScriptError('Push data too large.', op, ip);
break; 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); throw new ScriptError('Stack size too large.', op, ip);
if (stack.state.length !== 0) 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) { Script.checkLocktime = function checkLocktime(locktime, tx, i) {
var threshold = constants.locktimeThreshold; var threshold = constants.LOCKTIME_THRESHOLD;
if (!( if (!(
(tx.locktime < threshold && locktime < threshold) (tx.locktime < threshold && locktime < threshold)
@ -1654,19 +1654,19 @@ Script.checkSequence = function checkSequence(sequence, tx, i) {
if (tx.version < 2) if (tx.version < 2)
return false; return false;
if (txSequence & constants.sequenceLocktimeDisableFlag) if (txSequence & constants.sequence.DISABLE_FLAG)
return false; return false;
locktimeMask = constants.sequenceLocktimeTypeFlag locktimeMask = constants.sequence.TYPE_FLAG
| constants.sequenceLocktimeMask; | constants.sequence.MASK;
txSequenceMasked = txSequence & locktimeMask; txSequenceMasked = txSequence & locktimeMask;
sequenceMasked = sequence & locktimeMask; sequenceMasked = sequence & locktimeMask;
if (!( if (!(
(txSequenceMasked < constants.sequenceLocktimeTypeFlag (txSequenceMasked < constants.sequence.TYPE_FLAG
&& sequenceMasked < constants.sequenceLocktimeTypeFlag) && sequenceMasked < constants.sequence.TYPE_FLAG)
|| (txSequenceMasked >= constants.sequenceLocktimeTypeFlag || (txSequenceMasked >= constants.sequence.TYPE_FLAG
&& sequenceMasked >= constants.sequenceLocktimeTypeFlag) && sequenceMasked >= constants.sequence.TYPE_FLAG)
)) { )) {
return false; return false;
} }
@ -1971,7 +1971,7 @@ Script.createScripthash = function createScripthash(hash) {
Script.createNulldata = function createNulldata(flags) { Script.createNulldata = function createNulldata(flags) {
assert(Buffer.isBuffer(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([ return new Script([
opcodes.OP_RETURN, opcodes.OP_RETURN,
flags flags
@ -2087,7 +2087,7 @@ Script.prototype.isStandard = function isStandard() {
if (m < 1 || m > n) if (m < 1 || m > n)
return false; return false;
} else if (type === 'nulldata') { } else if (type === 'nulldata') {
if (this.getSize() > constants.script.maxOpReturnBytes) if (this.getSize() > constants.script.MAX_OP_RETURN_BYTES)
return false; return false;
} }
@ -2128,7 +2128,7 @@ Script.prototype.isStandardProgram = function isStandardProgram(witness, flags)
} }
for (i = 0; i < witness.items.length; i++) { 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; return false;
} }
@ -2837,7 +2837,7 @@ Script.isZero = function isZero(op) {
*/ */
Script.isData = function isData(data) { 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) if (sig.length === 0)
return false; return false;
type = sig[sig.length - 1] & ~constants.hashType.anyonecanpay; type = sig[sig.length - 1] & ~constants.hashType.ANYONECANPAY;
if (!constants.hashTypeByVal[type]) if (!constants.hashTypeByVal[type])
return false; return false;
@ -3168,7 +3168,7 @@ Script.prototype.getSigops = function getSigops(accurate) {
if (accurate && lastOp >= opcodes.OP_1 && lastOp <= opcodes.OP_16) if (accurate && lastOp >= opcodes.OP_1 && lastOp <= opcodes.OP_16)
total += lastOp - 0x50; total += lastOp - 0x50;
else else
total += constants.script.maxPubkeysPerMultisig; total += constants.script.MAX_MULTISIG_PUBKEYS;
} }
lastOp = op; lastOp = op;
@ -3514,7 +3514,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) {
} }
for (j = 0; j < stack.length; j++) { 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; return false;
} }

View File

@ -202,8 +202,8 @@ TX.prototype.hash = function hash(enc) {
TX.prototype.witnessHash = function witnessHash(enc) { TX.prototype.witnessHash = function witnessHash(enc) {
if (this.isCoinbase()) { if (this.isCoinbase()) {
return enc === 'hex' return enc === 'hex'
? utils.toHex(constants.zeroHash) ? utils.toHex(constants.ZERO_HASH)
: utils.slice(constants.zeroHash); : utils.slice(constants.ZERO_HASH);
} }
if (!this.hasWitness()) if (!this.hasWitness())
@ -359,7 +359,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) {
index = this.inputs.indexOf(index); index = this.inputs.indexOf(index);
if (typeof type === 'string') if (typeof type === 'string')
type = constants.hashType[type]; type = constants.hashType[type.toUpperCase()];
assert(index >= 0 && index < this.inputs.length); assert(index >= 0 && index < this.inputs.length);
assert(prev instanceof Script); assert(prev instanceof Script);
@ -395,7 +395,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) {
// Set our input to previous output's script // Set our input to previous output's script
copy.inputs[index].script = prev; 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. // Drop all outputs. We don't want to sign them.
copy.outputs.length = 0; copy.outputs.length = 0;
@ -404,11 +404,11 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) {
if (i !== index) if (i !== index)
copy.inputs[i].sequence = 0; 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: // Bitcoind used to return 1 as an error code:
// it ended up being treated like a hash. // it ended up being treated like a hash.
if (index >= copy.outputs.length) if (index >= copy.outputs.length)
return utils.slice(constants.oneHash); return utils.slice(constants.ONE_HASH);
// Drop all the outputs after the input index. // Drop all the outputs after the input index.
copy.outputs.length = index + 1; 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. // 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[0] = copy.inputs[index];
copy.inputs.length = 1; copy.inputs.length = 1;
} }
@ -449,12 +449,12 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) {
index = this.inputs.indexOf(index); index = this.inputs.indexOf(index);
if (typeof type === 'string') if (typeof type === 'string')
type = constants.hashType[type]; type = constants.hashType[type.toUpperCase()];
assert(index >= 0 && index < this.inputs.length); assert(index >= 0 && index < this.inputs.length);
assert(prev instanceof Script); assert(prev instanceof Script);
if (!(type & constants.hashType.anyonecanpay)) { if (!(type & constants.hashType.ANYONECANPAY)) {
hashPrevouts = new BufferWriter(); hashPrevouts = new BufferWriter();
for (i = 0; i < this.inputs.length; i++) { for (i = 0; i < this.inputs.length; i++) {
prevout = this.inputs[i].prevout; prevout = this.inputs[i].prevout;
@ -463,31 +463,31 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) {
} }
hashPrevouts = utils.dsha256(hashPrevouts.render()); hashPrevouts = utils.dsha256(hashPrevouts.render());
} else { } else {
hashPrevouts = utils.slice(constants.zeroHash); hashPrevouts = utils.slice(constants.ZERO_HASH);
} }
if (!(type & constants.hashType.anyonecanpay) if (!(type & constants.hashType.ANYONECANPAY)
&& (type & 0x1f) !== constants.hashType.single && (type & 0x1f) !== constants.hashType.SINGLE
&& (type & 0x1f) !== constants.hashType.none) { && (type & 0x1f) !== constants.hashType.NONE) {
hashSequence = new BufferWriter(); hashSequence = new BufferWriter();
for (i = 0; i < this.inputs.length; i++) for (i = 0; i < this.inputs.length; i++)
hashSequence.writeU32(this.inputs[i].sequence); hashSequence.writeU32(this.inputs[i].sequence);
hashSequence = utils.dsha256(hashSequence.render()); hashSequence = utils.dsha256(hashSequence.render());
} else { } else {
hashSequence = utils.slice(constants.zeroHash); hashSequence = utils.slice(constants.ZERO_HASH);
} }
if ((type & 0x1f) !== constants.hashType.single if ((type & 0x1f) !== constants.hashType.SINGLE
&& (type & 0x1f) !== constants.hashType.none) { && (type & 0x1f) !== constants.hashType.NONE) {
hashOutputs = new BufferWriter(); hashOutputs = new BufferWriter();
for (i = 0; i < this.outputs.length; i++) for (i = 0; i < this.outputs.length; i++)
bcoin.protocol.framer.output(this.outputs[i], hashOutputs); bcoin.protocol.framer.output(this.outputs[i], hashOutputs);
hashOutputs = utils.dsha256(hashOutputs.render()); 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 = bcoin.protocol.framer.output(this.outputs[index]);
hashOutputs = utils.dsha256(hashOutputs); hashOutputs = utils.dsha256(hashOutputs);
} else { } else {
hashOutputs = utils.slice(constants.zeroHash); hashOutputs = utils.slice(constants.ZERO_HASH);
} }
p.write32(this.version); p.write32(this.version);
@ -595,7 +595,7 @@ TX.prototype.verifyAsync = function verifyAsync(index, force, flags, callback) {
TX.prototype.isCoinbase = function isCoinbase() { TX.prototype.isCoinbase = function isCoinbase() {
return this.inputs.length === 1 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) { TX.prototype.isFinal = function isFinal(height, ts) {
var threshold = constants.locktimeThreshold; var threshold = constants.LOCKTIME_THRESHOLD;
var i; var i;
if (this.locktime === 0) if (this.locktime === 0)
@ -980,7 +980,7 @@ TX.prototype.isSane = function isSane(ret) {
return false; return false;
} }
if (this.getVirtualSize() > constants.block.maxSize) { if (this.getVirtualSize() > constants.block.MAX_SIZE) {
ret.reason = 'bad-txns-oversize'; ret.reason = 'bad-txns-oversize';
ret.score = 100; ret.score = 100;
return false; return false;
@ -995,7 +995,7 @@ TX.prototype.isSane = function isSane(ret) {
return false; return false;
} }
if (output.value.cmp(constants.maxMoney) > 0) { if (output.value.cmp(constants.MAX_MONEY) > 0) {
ret.reason = 'bad-txns-vout-toolarge'; ret.reason = 'bad-txns-vout-toolarge';
ret.score = 100; ret.score = 100;
return false; return false;
@ -1003,7 +1003,7 @@ TX.prototype.isSane = function isSane(ret) {
total.iadd(output.value); 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.reason = 'bad-txns-txouttotal-toolarge';
ret.score = 100; ret.score = 100;
return false; return false;
@ -1031,7 +1031,7 @@ TX.prototype.isSane = function isSane(ret) {
} else { } else {
for (i = 0; i < this.inputs.length; i++) { for (i = 0; i < this.inputs.length; i++) {
input = this.inputs[i]; input = this.inputs[i];
if (input.prevout.hash === constants.nullHash if (input.prevout.hash === constants.NULL_HASH
&& input.prevout.index === 0xffffffff) { && input.prevout.index === 0xffffffff) {
ret.reason = 'bad-txns-prevout-null'; ret.reason = 'bad-txns-prevout-null';
ret.score = 10; ret.score = 10;
@ -1065,12 +1065,12 @@ TX.prototype.isStandard = function isStandard(flags, ret) {
if (flags == null) if (flags == null)
flags = constants.flags.STANDARD_VERIFY_FLAGS; 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'; ret.reason = 'version';
return false; return false;
} }
if (this.getVirtualSize() > constants.tx.maxSize) { if (this.getVirtualSize() > constants.tx.MAX_SIZE) {
ret.reason = 'tx-size'; ret.reason = 'tx-size';
return false; return false;
} }
@ -1104,12 +1104,12 @@ TX.prototype.isStandard = function isStandard(flags, ret) {
continue; continue;
} }
if (output.script.isMultisig() && !constants.tx.bareMultisig) { if (output.script.isMultisig() && !constants.tx.BARE_MULTISIG) {
ret.reason = 'bare-multisig'; ret.reason = 'bare-multisig';
return false; return false;
} }
if (output.value.cmpn(constants.tx.dustThreshold) < 0) { if (output.value.cmpn(constants.tx.DUST_THRESHOLD) < 0) {
ret.reason = 'dust'; ret.reason = 'dust';
return false; return false;
} }
@ -1132,7 +1132,7 @@ TX.prototype.isStandard = function isStandard(flags, ret) {
*/ */
TX.prototype.hasStandardInputs = function hasStandardInputs(flags) { 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 VERIFY_NONE = constants.flags.VERIFY_NONE;
var i, input, stack, res, redeem; var i, input, stack, res, redeem;
@ -1208,14 +1208,14 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) {
coin = input.coin; coin = input.coin;
if (coin.coinbase) { 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.reason = 'bad-txns-premature-spend-of-coinbase';
ret.score = 0; ret.score = 0;
return false; 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.reason = 'bad-txns-inputvalues-outofrange';
ret.score = 100; ret.score = 100;
return false; return false;
@ -1224,7 +1224,7 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) {
total.iadd(coin.value); 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.reason = 'bad-txns-inputvalues-outofrange';
ret.score = 100; ret.score = 100;
return false; return false;
@ -1246,7 +1246,7 @@ TX.prototype.checkInputs = function checkInputs(spendHeight, ret) {
return false; return false;
} }
if (fee.cmp(constants.maxMoney) > 0) { if (fee.cmp(constants.MAX_MONEY) > 0) {
ret.reason = 'bad-txns-fee-outofrange'; ret.reason = 'bad-txns-fee-outofrange';
ret.score = 100; ret.score = 100;
return false; return false;
@ -1357,7 +1357,7 @@ TX.prototype.isFree = function isFree(height, size) {
priority = this.getPriority(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) if (size == null)
size = this.maxSize(); 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) if (fee.cmpn(0) === 0 && constants.tx.MIN_FEE > 0)
fee = new bn(constants.tx.minFee); fee = new bn(constants.tx.MIN_FEE);
return fee; return fee;
}; };
@ -1397,10 +1397,10 @@ TX.prototype.getMaxFee = function getMaxFee(size) {
if (size == null) if (size == null)
size = this.maxSize(); 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) if (fee.cmpn(0) === 0 && constants.tx.MIN_FEE > 0)
fee = new bn(constants.tx.minFee); fee = new bn(constants.tx.MIN_FEE);
return fee; return fee;
}; };
@ -1486,10 +1486,10 @@ TX.prototype.isWatched = function isWatched(bloom) {
output = this.outputs[i]; output = this.outputs[i];
// Test the output script // Test the output script
if (testScript(output.script.code)) { if (testScript(output.script.code)) {
if (bloom.update === 'all') { if (bloom.update === constants.filterFlags.ALL) {
outpoint = bcoin.protocol.framer.outpoint(this.hash(), i); outpoint = bcoin.protocol.framer.outpoint(this.hash(), i);
bloom.add(outpoint); bloom.add(outpoint);
} else if (bloom.update === 'pubkeyOnly') { } else if (bloom.update === constants.filterFlags.PUBKEY_ONLY) {
if (output.script.isPubkey() || output.script.isMultisig()) { if (output.script.isPubkey() || output.script.isMultisig()) {
outpoint = bcoin.protocol.framer.outpoint(this.hash(), i); outpoint = bcoin.protocol.framer.outpoint(this.hash(), i);
bloom.add(outpoint); bloom.add(outpoint);
@ -1718,7 +1718,7 @@ TX.prototype.toExtended = function toExtended(saveCoins) {
bcoin.protocol.framer.renderTX(this, true, p); bcoin.protocol.framer.renderTX(this, true, p);
p.writeU32(height); p.writeU32(height);
p.writeHash(this.block || constants.zeroHash); p.writeHash(this.block || constants.ZERO_HASH);
p.writeU32(index); p.writeU32(index);
p.writeU32(this.ts); p.writeU32(this.ts);
p.writeU32(this.ps); p.writeU32(this.ps);
@ -1764,7 +1764,7 @@ TX._fromExtended = function _fromExtended(buf, saveCoins) {
tx.ps = p.readU32(); tx.ps = p.readU32();
// tx.changeIndex = p.readU32(); // tx.changeIndex = p.readU32();
if (tx.block === constants.nullHash) if (tx.block === constants.NULL_HASH)
tx.block = null; tx.block = null;
if (tx.height === 0x7fffffff) if (tx.height === 0x7fffffff)

View File

@ -505,7 +505,7 @@ Wallet.prototype.deriveAddress = function deriveAddress(change, index) {
data = { data = {
path: this.createPath(this.cosignerIndex, change, index), path: this.createPath(this.cosignerIndex, change, index),
cosignerIndex: this.copayBIP45 cosignerIndex: this.copayBIP45
? constants.hd.hardened - 1 ? constants.hd.HARDENED - 1
: this.cosignerIndex, : this.cosignerIndex,
change: change, change: change,
index: index index: index
@ -579,7 +579,7 @@ Wallet.prototype.hasAddress = function hasAddress(address) {
Wallet.prototype.createPath = function createPath(cosignerIndex, change, index) { Wallet.prototype.createPath = function createPath(cosignerIndex, change, index) {
if (this.copayBIP45) if (this.copayBIP45)
cosignerIndex = constants.hd.hardened - 1; cosignerIndex = constants.hd.HARDENED - 1;
return 'm' return 'm'
+ (this.derivation === 'bip45' ? '/' + cosignerIndex : '') + (this.derivation === 'bip45' ? '/' + cosignerIndex : '')
@ -608,7 +608,7 @@ Wallet.prototype.parsePath = function parsePath(path) {
parts = path.split('/'); parts = path.split('/');
if (this.derivation === 'bip45' && this.copayBIP45) 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 { return {
path: path, path: path,

View File

@ -26,13 +26,13 @@ function createGenesisBlock(options) {
} }
if (!options.reward) if (!options.reward)
options.reward = new bn(50).mul(constants.coin); options.reward = new bn(50).mul(constants.COIN);
tx = { tx = {
version: 1, version: 1,
inputs: [{ inputs: [{
prevout: { prevout: {
hash: constants.nullHash, hash: constants.NULL_HASH,
index: 0xffffffff index: 0xffffffff
}, },
script: { script: {
@ -58,7 +58,7 @@ function createGenesisBlock(options) {
block = { block = {
version: options.version, version: options.version,
prevBlock: constants.nullHash, prevBlock: constants.NULL_HASH,
merkleRoot: utils.toHex(utils.dsha256(txRaw)), merkleRoot: utils.toHex(utils.dsha256(txRaw)),
ts: options.ts, ts: options.ts,
bits: options.bits, bits: options.bits,

View File

@ -7,7 +7,7 @@ var utils = bcoin.utils;
var assert = utils.assert; var assert = utils.assert;
var opcodes = constants.opcodes; var opcodes = constants.opcodes;
constants.tx.coinbaseMaturity = 0; constants.tx.COINBASE_MATURITY = 0;
describe('Chain', function() { describe('Chain', function() {
var chain, wallet, miner; var chain, wallet, miner;
@ -174,7 +174,7 @@ describe('Chain', function() {
}); });
it('should cleanup', function(cb) { it('should cleanup', function(cb) {
constants.tx.coinbaseMaturity = 100; constants.tx.COINBASE_MATURITY = 100;
cb(); cb();
}); });
}); });

View File

@ -22,7 +22,7 @@ describe('Mempool', function() {
var prev = new bcoin.script([w.publicKey, opcodes.OP_CHECKSIG]); var prev = new bcoin.script([w.publicKey, opcodes.OP_CHECKSIG]);
var dummyInput = { var dummyInput = {
prevout: { prevout: {
hash: constants.oneHash, hash: constants.ONE_HASH,
index: 0 index: 0
}, },
coin: { coin: {
@ -31,7 +31,7 @@ describe('Mempool', function() {
value: new bn(70000), value: new bn(70000),
script: prev, script: prev,
coinbase: false, coinbase: false,
hash: constants.oneHash, hash: constants.ONE_HASH,
index: 0 index: 0
}, },
script: new bcoin.script([]), script: new bcoin.script([]),

View File

@ -27,14 +27,14 @@ describe('Protocol', function() {
} }
packetTest('version', {}, function(payload) { packetTest('version', {}, function(payload) {
assert.equal(payload.version, constants.version); assert.equal(payload.version, constants.VERSION);
assert.equal(payload.agent, agent); assert.equal(payload.agent, agent);
assert.equal(payload.height, 0); assert.equal(payload.height, 0);
assert.equal(payload.relay, false); assert.equal(payload.relay, false);
}); });
packetTest('version', { relay: true, height: 10 }, function(payload) { 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.agent, agent);
assert.equal(payload.height, 10); assert.equal(payload.height, 10);
assert.equal(payload.relay, true); assert.equal(payload.relay, true);
@ -66,7 +66,7 @@ describe('Protocol', function() {
}); });
addr._ipv6 = addr.ipv6; addr._ipv6 = addr.ipv6;
addr.ipv6 = new Buffer(addr.ipv6.replace(/:/g, ''), 'hex'); addr.ipv6 = new Buffer(addr.ipv6.replace(/:/g, ''), 'hex');
addr.services = constants.localServices; addr.services = constants.LOCAL_SERVICES;
}); });
packetTest('addr', peers, function(payload) { packetTest('addr', peers, function(payload) {
@ -74,13 +74,13 @@ describe('Protocol', function() {
assert.equal(payload.length, 2); assert.equal(payload.length, 2);
assert.equal(typeof payload[0].ts, 'number'); 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].ipv6, peers[0]._ipv6);
assert.equal(payload[0].ipv4, peers[0]._ipv4); assert.equal(payload[0].ipv4, peers[0]._ipv4);
assert.equal(payload[0].port, peers[0].port); assert.equal(payload[0].port, peers[0].port);
assert.equal(typeof payload[1].ts, 'number'); 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].ipv6, peers[1]._ipv6);
assert.equal(payload[1].ipv4, peers[1]._ipv4); assert.equal(payload[1].ipv4, peers[1]._ipv4);
assert.equal(payload[1].port, peers[1].port); assert.equal(payload[1].port, peers[1].port);

View File

@ -6,16 +6,16 @@ var assert = utils.assert;
var dummyInput = { var dummyInput = {
prevout: { prevout: {
hash: constants.zeroHash, hash: constants.ZERO_HASH,
index: 0 index: 0
}, },
coin: { coin: {
version: 1, version: 1,
height: 0, height: 0,
value: constants.maxMoney.clone(), value: constants.MAX_MONEY.clone(),
script: new bcoin.script([]), script: new bcoin.script([]),
coinbase: false, coinbase: false,
hash: constants.zeroHash, hash: constants.ZERO_HASH,
index: 0 index: 0
}, },
script: new bcoin.script([]), script: new bcoin.script([]),
@ -336,7 +336,7 @@ describe('Wallet', function() {
tx.addOutput(to, 5460); tx.addOutput(to, 5460);
var cost = tx.getOutputValue(); 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) { w1.getCoins(function(err, coins1) {
assert.noError(err); assert.noError(err);
@ -352,7 +352,7 @@ describe('Wallet', function() {
tx.addInput(coins2[0]); tx.addInput(coins2[0]);
var left = tx.getInputValue().sub(total); 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); tx.outputs[tx.outputs.length - 2].value.iadd(left);
left = new bn(0); left = new bn(0);
} }