clean up utils.

This commit is contained in:
Christopher Jeffrey 2016-04-18 00:36:03 -07:00
parent a62d249d8e
commit 69ddca52a8
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
32 changed files with 104 additions and 186 deletions

View File

@ -37,8 +37,8 @@ function AbstractBlock(data) {
this.type = null; this.type = null;
this.version = data.version; this.version = data.version;
this.prevBlock = utils.toHex(data.prevBlock); this.prevBlock = data.prevBlock;
this.merkleRoot = utils.toHex(data.merkleRoot); this.merkleRoot = data.merkleRoot;
this.ts = data.ts; this.ts = data.ts;
this.bits = data.bits; this.bits = data.bits;
this.nonce = data.nonce; this.nonce = data.nonce;
@ -64,7 +64,7 @@ AbstractBlock.prototype.hash = function hash(enc) {
if (!this._hash) if (!this._hash)
this._hash = utils.dsha256(this.abbr()); this._hash = utils.dsha256(this.abbr());
return enc === 'hex' ? utils.toHex(this._hash) : this._hash; return enc === 'hex' ? this._hash.toString('hex') : this._hash;
}; };
/** /**

View File

@ -239,7 +239,7 @@ Block.prototype.getMerkleRoot = function getMerkleRoot(enc) {
return; return;
return enc === 'hex' return enc === 'hex'
? utils.toHex(root) ? root.toString('hex')
: root; : root;
}; };
@ -269,7 +269,7 @@ Block.prototype.getCommitmentHash = function getCommitmentHash(enc) {
commitmentHash = utils.dsha256(Buffer.concat([witnessRoot, witnessNonce])); commitmentHash = utils.dsha256(Buffer.concat([witnessRoot, witnessNonce]));
return enc === 'hex' return enc === 'hex'
? utils.toHex(commitmentHash) ? commitmentHash.toString('hex')
: commitmentHash; : commitmentHash;
}; };
@ -311,7 +311,7 @@ Block.prototype.__defineGetter__('commitmentHash', function() {
} }
if (commitmentHash) if (commitmentHash)
this._commitmentHash = utils.toHex(commitmentHash); this._commitmentHash = commitmentHash.toString('hex');
return this._commitmentHash; return this._commitmentHash;
}); });
@ -571,7 +571,7 @@ Block.prototype.toRaw = function toRaw(enc) {
var data = this.render(); var data = this.render();
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -302,7 +302,7 @@ Chain.prototype._preload = function _preload(callback) {
function parseHeader(buf) { function parseHeader(buf) {
var headers = bcoin.protocol.parser.parseBlockHeaders(buf); var headers = bcoin.protocol.parser.parseBlockHeaders(buf);
headers.hash = utils.toHex(utils.dsha256(buf.slice(0, 80))); headers.hash = utils.dsha256(buf.slice(0, 80)).toString('hex');
return headers; return headers;
} }
@ -904,11 +904,6 @@ Chain.prototype._checkInputs = function _checkInputs(block, prev, flags, callbac
}; };
Chain.prototype._getCachedHeight = function _getCachedHeight(hash) { Chain.prototype._getCachedHeight = function _getCachedHeight(hash) {
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
if (this.db.hasCache(hash)) if (this.db.hasCache(hash))
return this.db.getCache(hash).height; return this.db.getCache(hash).height;
@ -1755,11 +1750,6 @@ Chain.prototype.hasBlock = function hasBlock(hash, callback) {
if (typeof hash === 'number') if (typeof hash === 'number')
return this.db.has(hash, callback); return this.db.has(hash, callback);
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
return this.db.has(hash, callback); return this.db.has(hash, callback);
}; };
@ -1780,11 +1770,6 @@ Chain.prototype.hasOrphan = function hasOrphan(hash) {
*/ */
Chain.prototype.hasPending = function hasPending(hash) { Chain.prototype.hasPending = function hasPending(hash) {
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
return this.locker.hasPending(hash); return this.locker.hasPending(hash);
}; };
@ -1797,12 +1782,6 @@ Chain.prototype.hasPending = function hasPending(hash) {
Chain.prototype.getEntry = function getEntry(hash, callback) { Chain.prototype.getEntry = function getEntry(hash, callback) {
if (typeof hash === 'number') if (typeof hash === 'number')
return this.db.get(hash, callback); return this.db.get(hash, callback);
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
return this.db.get(hash, callback); return this.db.get(hash, callback);
}; };
@ -1813,11 +1792,6 @@ Chain.prototype.getEntry = function getEntry(hash, callback) {
*/ */
Chain.prototype.getOrphan = function getOrphan(hash) { Chain.prototype.getOrphan = function getOrphan(hash) {
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
return this.orphan.bmap[hash] || null; return this.orphan.bmap[hash] || null;
}; };
@ -1935,13 +1909,6 @@ Chain.prototype.getLocator = function getLocator(start, callback, force) {
callback = utils.wrap(callback, unlock); callback = utils.wrap(callback, unlock);
if (start) {
if (Buffer.isBuffer(start))
start = utils.toHex(start);
else if (start.hash)
start = start.hash('hex');
}
function build(err, top) { function build(err, top) {
if (err) if (err)
return callback(err); return callback(err);
@ -2016,11 +1983,6 @@ Chain.prototype.getLocator = function getLocator(start, callback, force) {
Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) { Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) {
var root; var root;
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex');
assert(hash); assert(hash);
while (this.orphan.bmap[hash]) { while (this.orphan.bmap[hash]) {

View File

@ -449,7 +449,7 @@ ChainBlock.fromRaw = function fromRaw(chain, buf) {
var hash = utils.dsha256(buf.slice(0, 80)); var hash = utils.dsha256(buf.slice(0, 80));
return new ChainBlock(chain, { return new ChainBlock(chain, {
hash: utils.toHex(hash), hash: hash.toString('hex'),
version: p.readU32(), // Technically signed version: p.readU32(), // Technically signed
prevBlock: p.readHash('hex'), prevBlock: p.readHash('hex'),
merkleRoot: p.readHash('hex'), merkleRoot: p.readHash('hex'),

View File

@ -259,7 +259,7 @@ ChainDB.prototype.getHash = function getHash(height, callback) {
if (hash == null) if (hash == null)
return callback(null, null); return callback(null, null);
return callback(null, utils.toHex(hash)); return callback(null, hash.toString('hex'));
}); });
}; };
@ -494,7 +494,7 @@ ChainDB.prototype.getTip = function getTip(callback) {
if (!hash) if (!hash)
return callback(); return callback();
return self.get(utils.toHex(hash), callback); return self.get(hash.toString('hex'), callback);
}); });
}; };
@ -590,7 +590,7 @@ ChainDB.prototype.getNextHash = function getNextHash(hash, callback) {
if (!nextHash) if (!nextHash)
return callback(); return callback();
return callback(null, utils.toHex(nextHash)); return callback(null, nextHash.toString('hex'));
}); });
}; };
@ -1584,7 +1584,7 @@ ChainDB.prototype._pruneQueue = function _pruneQueue(block, batch, callback) {
if (!hash) if (!hash)
return callback(); return callback();
hash = utils.toHex(hash); hash = hash.toString('hex');
self.db.get('b/b/' + hash, function(err, compact) { self.db.get('b/b/' + hash, function(err, compact) {
if (err && err.type !== 'NotFoundError') if (err && err.type !== 'NotFoundError')

View File

@ -63,9 +63,7 @@ function Coin(tx, index) {
this.index = options.index; this.index = options.index;
} }
if (Buffer.isBuffer(this.hash)) assert(!this.hash || typeof this.hash === 'string');
this.hash = utils.toHex(this.hash);
assert(typeof this.version === 'number'); assert(typeof this.version === 'number');
assert(utils.isFinite(this.height)); assert(utils.isFinite(this.height));
assert(bn.isBN(this.value)); assert(bn.isBN(this.value));
@ -149,7 +147,7 @@ Coin.prototype.toJSON = function toJSON() {
version: this.version, version: this.version,
height: this.height, height: this.height,
value: utils.btc(this.value), value: utils.btc(this.value),
script: utils.toHex(this.script.encode()), script: this.script.encode().toString('hex'),
coinbase: this.coinbase, coinbase: this.coinbase,
hash: this.hash ? utils.revHex(this.hash) : null, hash: this.hash ? utils.revHex(this.hash) : null,
index: this.index index: this.index
@ -195,7 +193,7 @@ Coin.prototype.toRaw = function toRaw(enc) {
var data = bcoin.protocol.framer.coin(this, false); var data = bcoin.protocol.framer.coin(this, false);
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };
@ -238,7 +236,7 @@ Coin.prototype.toExtended = function toExtended(enc) {
var data = bcoin.protocol.framer.coin(this, true); var data = bcoin.protocol.framer.coin(this, true);
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -31,9 +31,6 @@ function Coins(options, hash) {
if (!(this instanceof Coins)) if (!(this instanceof Coins))
return new Coins(options, hash); return new Coins(options, hash);
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
this.version = options.version; this.version = options.version;
this.height = options.height; this.height = options.height;

View File

@ -112,7 +112,7 @@ Headers.prototype.toRaw = function toRaw(enc) {
data = this.render(); data = this.render();
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -754,7 +754,7 @@ HTTPClient.prototype.getBlock = function getBlock(hash, callback) {
*/ */
HTTPClient.prototype.broadcast = function broadcast(tx, callback) { HTTPClient.prototype.broadcast = function broadcast(tx, callback) {
var body = { tx: utils.toHex(tx.toRaw()) }; var body = { tx: tx.toRaw('hex') };
callback = utils.ensure(callback); callback = utils.ensure(callback);

View File

@ -44,9 +44,6 @@ function Input(options, mutable) {
if (options.coin) if (options.coin)
this.coin = bcoin.coin(options.coin); this.coin = bcoin.coin(options.coin);
if (Buffer.isBuffer(this.prevout.hash))
this.prevout.hash = utils.toHex(this.prevout.hash);
assert(typeof this.prevout.hash === 'string'); assert(typeof this.prevout.hash === 'string');
assert(typeof this.prevout.index === 'number'); assert(typeof this.prevout.index === 'number');
} }
@ -263,8 +260,8 @@ Input.prototype.toJSON = function toJSON() {
index: this.prevout.index index: this.prevout.index
}, },
coin: this.coin ? this.coin.toJSON() : null, coin: this.coin ? this.coin.toJSON() : null,
script: utils.toHex(this.script.encode()), script: this.script.encode().toString('hex'),
witness: utils.toHex(bcoin.protocol.framer.witness(this.witness)), witness: bcoin.protocol.framer.witness(this.witness).toString('hex'),
sequence: this.sequence sequence: this.sequence
}; };
}; };
@ -309,7 +306,7 @@ Input.prototype.toRaw = function toRaw(enc) {
var data = bcoin.protocol.framer.input(this); var data = bcoin.protocol.framer.input(this);
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };
@ -358,7 +355,7 @@ Input.prototype.toExtended = function toExtended(enc) {
data = p.render(); data = p.render();
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -102,7 +102,7 @@ KeyPair.prototype.getPrivateKey = function getPrivateKey(enc) {
return this.toSecret(); return this.toSecret();
if (enc === 'hex') if (enc === 'hex')
return utils.toHex(this.privateKey); return this.privateKey.toString('hex');
return this.privateKey; return this.privateKey;
}; };
@ -118,7 +118,7 @@ KeyPair.prototype.getPublicKey = function getPublicKey(enc) {
return utils.toBase58(this.publicKey); return utils.toBase58(this.publicKey);
if (enc === 'hex') if (enc === 'hex')
return utils.toHex(this.publicKey); return this.publicKey.toString('hex');
return this.publicKey; return this.publicKey;
}; };

View File

@ -1245,10 +1245,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.ZERO_HASH), hash: constants.NULL_HASH,
version: tip.version, version: tip.version,
prevBlock: tip.hash, prevBlock: tip.hash,
merkleRoot: utils.toHex(constants.ZERO_HASH), merkleRoot: constants.NULL_HASH,
ts: utils.now(), ts: utils.now(),
bits: 0, bits: 0,
nonce: 0, nonce: 0,

View File

@ -161,7 +161,7 @@ MerkleBlock.prototype.verifyPartial = function verifyPartial() {
if (flag === 0 || depth === height) { if (flag === 0 || depth === height) {
if (depth === height) { if (depth === height) {
tx.push(utils.toHex(hashes[j])); tx.push(hashes[j].toString('hex'));
txMap[tx[tx.length - 1]] = true; txMap[tx[tx.length - 1]] = true;
} }
return hashes[j++]; return hashes[j++];
@ -173,7 +173,7 @@ MerkleBlock.prototype.verifyPartial = function verifyPartial() {
return null; return null;
right = visit(depth + 1); right = visit(depth + 1);
if (right && utils.isEqual(right, left)) if (right && utils.equals(right, left))
return null; return null;
if (!right) if (!right)
@ -182,9 +182,9 @@ MerkleBlock.prototype.verifyPartial = function verifyPartial() {
return utils.dsha256(Buffer.concat([left, right])); return utils.dsha256(Buffer.concat([left, right]));
} }
root = utils.toHex(visit(1)); root = visit(1);
if (!root || root !== this.merkleRoot) { if (!root || root.toString('hex') !== this.merkleRoot) {
this._partialVerified = false; this._partialVerified = false;
return false; return false;
} }
@ -261,7 +261,7 @@ MerkleBlock.prototype.toRaw = function toRaw(enc) {
data = this.render(); data = this.render();
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -118,7 +118,7 @@ Miner.prototype._init = function _init() {
block.height, block.height,
block.hash('hex')); block.hash('hex'));
// Emit the block hex as a failsafe (in case we can't send it) // Emit the block hex as a failsafe (in case we can't send it)
bcoin.debug('Raw: %s', utils.toHex(block.render())); bcoin.debug('Raw: %s', block.render().toString('hex'));
}); });
this.on('status', function(stat) { this.on('status', function(stat) {

View File

@ -121,7 +121,7 @@ MTX.prototype.clone = function clone() {
MTX.prototype.hash = function hash(enc) { MTX.prototype.hash = function hash(enc) {
var hash = utils.dsha256(this.renderNormal()); var hash = utils.dsha256(this.renderNormal());
return enc === 'hex' ? utils.toHex(hash) : hash; return enc === 'hex' ? hash.toString('hex') : hash;
}; };
/** /**
@ -138,7 +138,7 @@ MTX.prototype.witnessHash = function witnessHash(enc) {
if (this.isCoinbase()) { if (this.isCoinbase()) {
return enc === 'hex' return enc === 'hex'
? utils.toHex(constants.ZERO_HASH) ? constants.NULL_HASH
: utils.slice(constants.ZERO_HASH); : utils.slice(constants.ZERO_HASH);
} }
@ -147,7 +147,7 @@ MTX.prototype.witnessHash = function witnessHash(enc) {
hash = utils.dsha256(this.renderWitness()); hash = utils.dsha256(this.renderWitness());
return enc === 'hex' ? utils.toHex(hash) : hash; return enc === 'hex' ? hash.toString('hex') : hash;
}; };
/** /**
@ -305,7 +305,7 @@ MTX.prototype.scriptInput = function scriptInput(index, addr) {
// with segwit: figuring out where the redeem script and witness // with segwit: figuring out where the redeem script and witness
// redeem scripts go. // redeem scripts go.
if (prev.isScripthash()) { if (prev.isScripthash()) {
if (addr.program && utils.isEqual(prev.code[1], addr.programHash)) { if (addr.program && utils.equals(prev.code[1], addr.programHash)) {
// Witness program nested in regular P2SH. // Witness program nested in regular P2SH.
redeemScript = addr.program.encode(); redeemScript = addr.program.encode();
vector = input.witness.items; vector = input.witness.items;
@ -321,7 +321,7 @@ MTX.prototype.scriptInput = function scriptInput(index, addr) {
} else { } else {
assert(false, 'Unknown program.'); assert(false, 'Unknown program.');
} }
} else if (addr.script && utils.isEqual(prev.code[1], addr.scriptHash160)) { } else if (addr.script && utils.equals(prev.code[1], addr.scriptHash160)) {
// Regular P2SH. // Regular P2SH.
redeemScript = addr.script.encode(); redeemScript = addr.script.encode();
vector = input.script.code; vector = input.script.code;
@ -337,14 +337,14 @@ MTX.prototype.scriptInput = function scriptInput(index, addr) {
if (prev.isWitnessScripthash()) { if (prev.isWitnessScripthash()) {
// Bare P2WSH. // Bare P2WSH.
if (!addr.script || !utils.isEqual(prev.code[1], addr.scriptHash256)) if (!addr.script || !utils.equals(prev.code[1], addr.scriptHash256))
return false; return false;
witnessScript = addr.script.encode(); witnessScript = addr.script.encode();
prev = addr.script; prev = addr.script;
} else if (prev.isWitnessPubkeyhash()) { } else if (prev.isWitnessPubkeyhash()) {
// Bare P2WPKH. // Bare P2WPKH.
if (!utils.isEqual(prev.code[1], addr.keyHash)) if (!utils.equals(prev.code[1], addr.keyHash))
return false; return false;
prev = Script.createPubkeyhash(prev.code[1]); prev = Script.createPubkeyhash(prev.code[1]);
@ -360,7 +360,7 @@ MTX.prototype.scriptInput = function scriptInput(index, addr) {
if (prev.isPubkey()) { if (prev.isPubkey()) {
// P2PK // P2PK
if (!utils.isEqual(prev.code[0], addr.publicKey)) if (!utils.equals(prev.code[0], addr.publicKey))
return false; return false;
// Already has a script template (at least) // Already has a script template (at least)
@ -370,7 +370,7 @@ MTX.prototype.scriptInput = function scriptInput(index, addr) {
vector[0] = dummy; vector[0] = dummy;
} else if (prev.isPubkeyhash()) { } else if (prev.isPubkeyhash()) {
// P2PKH // P2PKH
if (!utils.isEqual(prev.code[2], addr.keyHash)) if (!utils.equals(prev.code[2], addr.keyHash))
return false; return false;
// Already has a script template (at least) // Already has a script template (at least)
@ -535,7 +535,7 @@ MTX.prototype.signInput = function signInput(index, addr, type) {
return true; return true;
// Make sure the pubkey is ours. // Make sure the pubkey is ours.
if (!utils.isEqual(addr.publicKey, prev.code[0])) if (!utils.equals(addr.publicKey, prev.code[0]))
return false; return false;
vector[0] = signature; vector[0] = signature;
@ -550,7 +550,7 @@ MTX.prototype.signInput = function signInput(index, addr, type) {
return true; return true;
// Make sure the pubkey hash is ours. // Make sure the pubkey hash is ours.
if (!utils.isEqual(addr.keyHash, prev.code[2])) if (!utils.equals(addr.keyHash, prev.code[2]))
return false; return false;
vector[0] = signature; vector[0] = signature;

View File

@ -139,7 +139,7 @@ Output.prototype.inspect = function inspect() {
Output.prototype.toJSON = function toJSON() { Output.prototype.toJSON = function toJSON() {
return { return {
value: utils.btc(this.value), value: utils.btc(this.value),
script: utils.toHex(this.script.encode()) script: this.script.encode().toString('hex')
}; };
}; };
@ -177,7 +177,7 @@ Output.prototype.toRaw = function toRaw(enc) {
var data = bcoin.protocol.framer.output(this); var data = bcoin.protocol.framer.output(this);
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -1044,7 +1044,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
for (i = 0; i < items.length; i++) { for (i = 0; i < items.length; i++) {
item = items[i]; item = items[i];
hash = utils.toHex(item.hash); hash = item.hash;
entry = this._broadcast.map[hash]; entry = this._broadcast.map[hash];
isWitness = item.type & constants.WITNESS_MASK; isWitness = item.type & constants.WITNESS_MASK;
value = null; value = null;
@ -1065,7 +1065,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
'Peer %s requested %s:%s as a %s packet.', 'Peer %s requested %s:%s as a %s packet.',
this.host, this.host,
entry.packetType, entry.packetType,
utils.revHex(utils.toHex(entry.hash)), utils.revHex(entry.hash),
isWitness ? 'witness' : 'normal'); isWitness ? 'witness' : 'normal');
if (isWitness) if (isWitness)
@ -1082,7 +1082,7 @@ Peer.prototype._handleGetData = function handleGetData(items) {
utils.forEachSerial(check, function(item, next) { utils.forEachSerial(check, function(item, next) {
var isWitness = item.type & constants.WITNESS_MASK; var isWitness = item.type & constants.WITNESS_MASK;
var type = item.type & ~constants.WITNESS_MASK; var type = item.type & ~constants.WITNESS_MASK;
var hash = utils.toHex(item.hash); var hash = item.hash;
var i, tx, data; var i, tx, data;
if (type === constants.inv.TX) { if (type === constants.inv.TX) {
@ -1337,7 +1337,7 @@ Peer.prototype._handleReject = function handleReject(payload) {
if (!payload.data) if (!payload.data)
return; return;
hash = utils.toHex(payload.data); hash = payload.data;
entry = this._broadcast.map[hash]; entry = this._broadcast.map[hash];
if (!entry) if (!entry)

View File

@ -736,8 +736,6 @@ Pool.prototype._handleBlocks = function _handleBlocks(hashes, peer, callback) {
this._startTimer(); this._startTimer();
utils.forEachSerial(hashes, function(hash, next, i) { utils.forEachSerial(hashes, function(hash, next, i) {
hash = utils.toHex(hash);
// Resolve orphan chain. // Resolve orphan chain.
if (self.chain.hasOrphan(hash)) { if (self.chain.hasOrphan(hash)) {
bcoin.debug('Peer sent a hash that is already a known orphan.'); bcoin.debug('Peer sent a hash that is already a known orphan.');
@ -781,7 +779,6 @@ Pool.prototype._handleInv = function _handleInv(hashes, peer, callback) {
return callback(); return callback();
utils.forEachSerial(hashes, function(hash, next) { utils.forEachSerial(hashes, function(hash, next) {
hash = utils.toHex(hash);
if (self.options.headers) if (self.options.headers)
self.getHeaders(peer, null, hash, next); self.getHeaders(peer, null, hash, next);
else else
@ -921,7 +918,7 @@ Pool.prototype._createPeer = function _createPeer(options) {
peer.on('reject', function(payload) { peer.on('reject', function(payload) {
var data = payload.data var data = payload.data
? utils.revHex(utils.toHex(payload.data)) ? utils.revHex(payload.data)
: null; : null;
bcoin.debug( bcoin.debug(
@ -946,7 +943,7 @@ Pool.prototype._createPeer = function _createPeer(options) {
for (i = 0; i < items.length; i++) { for (i = 0; i < items.length; i++) {
item = items[i]; item = items[i];
req = self.request.map[utils.toHex(item.hash)]; req = self.request.map[item.hash];
if (req && req.peer === peer) if (req && req.peer === peer)
item.finish(); item.finish();
} }
@ -991,7 +988,7 @@ Pool.prototype._createPeer = function _createPeer(options) {
} }
for (i = 0; i < txs.length; i++) { for (i = 0; i < txs.length; i++) {
hash = utils.toHex(txs[i]); hash = txs[i];
if (self.markTX(hash, 0)) if (self.markTX(hash, 0))
self.getData(peer, self.tx.type, hash); self.getData(peer, self.tx.type, hash);
} }
@ -1213,9 +1210,7 @@ Pool.prototype._addPeer = function _addPeer() {
}; };
Pool.prototype.markTX = function(hash, state) { Pool.prototype.markTX = function(hash, state) {
if (Buffer.isBuffer(hash)) if (hash.hash)
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex'); hash = hash.hash('hex');
if (this.tx.count >= 5000) { if (this.tx.count >= 5000) {
@ -1287,7 +1282,7 @@ Pool.prototype.watch = function watch(id) {
} }
if (id) { if (id) {
hid = utils.toHex(id); hid = id.toString('hex');
if (this.watchMap[hid]) { if (this.watchMap[hid]) {
this.watchMap[hid]++; this.watchMap[hid]++;
@ -1310,14 +1305,14 @@ Pool.prototype.watch = function watch(id) {
Pool.prototype.unwatch = function unwatch(id) { Pool.prototype.unwatch = function unwatch(id) {
var self = this; var self = this;
var i; var i, hid;
id = utils.toHex(id); hid = id.toString('hex');
if (!this.watchMap[id] || --this.watchMap[id] !== 0) if (!this.watchMap[hid] || --this.watchMap[hid] !== 0)
return; return;
delete this.watchMap[id]; delete this.watchMap[hid];
// Reset bloom filter // Reset bloom filter
this.bloom.reset(); this.bloom.reset();
@ -1600,9 +1595,6 @@ Pool.prototype.getData = function getData(peer, type, hash, options, callback) {
if (!options) if (!options)
options = {}; options = {};
if (Buffer.isBuffer(hash))
hash = utils.toHex(hash);
function done(err, exists) { function done(err, exists) {
if (err) if (err)
return callback(err); return callback(err);
@ -1719,9 +1711,7 @@ Pool.prototype._sendRequests = function _sendRequests(peer) {
Pool.prototype.fulfill = function fulfill(hash) { Pool.prototype.fulfill = function fulfill(hash) {
var i, item; var i, item;
if (Buffer.isBuffer(hash)) if (hash.hash)
hash = utils.toHex(hash);
else if (hash.hash)
hash = hash.hash('hex'); hash = hash.hash('hex');
item = this.request.map[hash]; item = this.request.map[hash];
@ -1782,8 +1772,6 @@ Pool.prototype.getTX = function getTX(hash, range, callback) {
if (!this.options.spv) if (!this.options.spv)
return callback(new Error('Cannot get tx with full node')); return callback(new Error('Cannot get tx with full node'));
hash = utils.toHex(hash);
if (typeof range === 'function') { if (typeof range === 'function') {
callback = range; callback = range;
range = null; range = null;

View File

@ -54,7 +54,7 @@ Framer.prototype.header = function header(cmd, payload) {
utils.writeU32(h, network.magic, 0); utils.writeU32(h, network.magic, 0);
// Command // Command
len = utils.copy(cmd, h, 4); len = cmd.copy(h, 4);
for (i = 4 + len; i < 4 + 12; i++) for (i = 4 + len; i < 4 + 12; i++)
h[i] = 0; h[i] = 0;
@ -62,7 +62,7 @@ Framer.prototype.header = function header(cmd, payload) {
utils.writeU32(h, payload.length, 16); utils.writeU32(h, payload.length, 16);
// Checksum // Checksum
utils.copy(utils.checksum(payload), h, 20); utils.checksum(payload).copy(h, 20);
return h; return h;
}; };

View File

@ -66,7 +66,7 @@ Parser.prototype.feed = function feed(data) {
len = 0; len = 0;
while (off < chunk.length) { while (off < chunk.length) {
len = utils.copy(this.pending[0], chunk, off); len = this.pending[0].copy(chunk, off);
if (len === this.pending[0].length) if (len === this.pending[0].length)
this.pending.shift(); this.pending.shift();
else else

View File

@ -1377,7 +1377,7 @@ Script.prototype.interpret = function interpret(stack, flags, tx, index, version
case opcodes.OP_EQUAL: { case opcodes.OP_EQUAL: {
if (stack.length < 2) if (stack.length < 2)
throw new ScriptError('Stack too small.', op, ip); throw new ScriptError('Stack too small.', op, ip);
res = utils.isEqual(stack.pop(), stack.pop()); res = utils.equals(stack.pop(), stack.pop());
if (op === opcodes.OP_EQUALVERIFY) { if (op === opcodes.OP_EQUALVERIFY) {
if (!res) if (!res)
throw new ScriptError('Equal verification failed.', op, ip); throw new ScriptError('Equal verification failed.', op, ip);
@ -1850,7 +1850,7 @@ Script.prototype.removeData = function removeData(data) {
for (i = this.code.length - 1; i >= 0; i--) { for (i = this.code.length - 1; i >= 0; i--) {
if (!Buffer.isBuffer(this.code[i])) if (!Buffer.isBuffer(this.code[i]))
continue; continue;
if (utils.isEqual(this.code[i], data)) { if (utils.equals(this.code[i], data)) {
this.code.splice(i, 1); this.code.splice(i, 1);
total++; total++;
} }
@ -2322,15 +2322,15 @@ Script.getInputHash = function getInputHash(isWitness) {
return; return;
if (Script.isPubkeyhashInput(code)) if (Script.isPubkeyhashInput(code))
return utils.toHex(utils.ripesha(code[1])); return utils.ripesha(code[1]).toString('hex');
if (Script.isMultisigInput(code, isWitness)) if (Script.isMultisigInput(code, isWitness))
return; return;
if (Script.isScripthashInput(code, isWitness)) { if (Script.isScripthashInput(code, isWitness)) {
return isWitness return isWitness
? utils.toHex(utils.sha256(code[code.length - 1])) ? utils.sha256(code[code.length - 1]).toString('hex')
: utils.toHex(utils.ripesha(code[code.length - 1])); : utils.ripesha(code[code.length - 1]).toString('hex')
} }
}; };
@ -2348,20 +2348,20 @@ Script.prototype.getHash = function getHash() {
program = this.getWitnessProgram(); program = this.getWitnessProgram();
if (!program.type || program.type === 'unknown') if (!program.type || program.type === 'unknown')
return; return;
return utils.toHex(program.data); return program.data.toString('hex');
} }
if (this.isPubkey()) if (this.isPubkey())
return utils.toHex(utils.ripesha(this.code[0])); return utils.ripesha(this.code[0]).toString('hex');
if (this.isPubkeyhash()) if (this.isPubkeyhash())
return utils.toHex(this.code[2]); return this.code[2].toString('hex');
if (this.isMultisig()) if (this.isMultisig())
return utils.toHex(utils.ripesha(this.encode())); return utils.ripesha(this.encode()).toString('hex');
if (this.isScripthash()) if (this.isScripthash())
return utils.toHex(this.code[1]); return this.code[1].toString('hex');
}; };
/** /**
@ -3271,7 +3271,7 @@ Script.format = function format(code) {
return Script.concat(scripts).map(function(chunk) { return Script.concat(scripts).map(function(chunk) {
if (Buffer.isBuffer(chunk)) if (Buffer.isBuffer(chunk))
return '[' + utils.toHex(chunk) + ']'; return '[' + chunk.toString('hex') + ']';
assert(typeof chunk === 'number'); assert(typeof chunk === 'number');
@ -3589,7 +3589,7 @@ Script.verify = function verify(input, witness, output, tx, i, flags) {
hadWitness = true; hadWitness = true;
// Input script must be exactly one push of the redeem script. // Input script must be exactly one push of the redeem script.
if (!(input.code.length === 1 && utils.isEqual(input.code[0], raw))) if (!(input.code.length === 1 && utils.equals(input.code[0], raw)))
return false; return false;
// Verify the program in the redeem script // Verify the program in the redeem script
@ -3671,7 +3671,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) {
witnessScript = stack.pop(); witnessScript = stack.pop();
if (!utils.isEqual(utils.sha256(witnessScript), program.data)) if (!utils.equals(utils.sha256(witnessScript), program.data))
return false; return false;
redeem = new Script(witnessScript); redeem = new Script(witnessScript);

View File

@ -187,7 +187,7 @@ TX.prototype.hash = function hash(enc) {
if (!this._hash) if (!this._hash)
this._hash = utils.dsha256(this.renderNormal()); this._hash = utils.dsha256(this.renderNormal());
return enc === 'hex' ? utils.toHex(this._hash) : this._hash; return enc === 'hex' ? this._hash.toString('hex') : this._hash;
}; };
/** /**
@ -202,7 +202,7 @@ 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.ZERO_HASH) ? constants.NULL_HASH
: utils.slice(constants.ZERO_HASH); : utils.slice(constants.ZERO_HASH);
} }
@ -212,7 +212,7 @@ TX.prototype.witnessHash = function witnessHash(enc) {
if (!this._whash) if (!this._whash)
this._whash = utils.dsha256(this.renderWitness()); this._whash = utils.dsha256(this.renderWitness());
return enc === 'hex' ? utils.toHex(this._whash) : this._whash; return enc === 'hex' ? this._whash.toString('hex') : this._whash;
}; };
/** /**
@ -1659,7 +1659,7 @@ TX.prototype.toRaw = function toRaw(enc) {
var data = this.render(); var data = this.render();
if (enc === 'hex') if (enc === 'hex')
data = utils.toHex(data); data = data.toString('hex');
return data; return data;
}; };

View File

@ -676,7 +676,7 @@ TXDB.prototype.isSpent = function isSpent(hash, index, callback) {
if (!hash) if (!hash)
return callback(null, null); return callback(null, null);
return callback(null, utils.toHex(hash)); return callback(null, hash.toString('hex'));
}); });
}; };

View File

@ -363,7 +363,7 @@ utils.pbkdf2 = function pbkdf2(key, salt, iterations, dkLen) {
var i, j, k, destPos, len; var i, j, k, destPos, len;
utils.copy(salt.slice(0, salt.length), block1, 0); salt.copy(block1);
for (i = 1; i <= l; i++) { for (i = 1; i <= l; i++) {
block1[salt.length + 0] = i >> 24 & 0xff; block1[salt.length + 0] = i >> 24 & 0xff;
@ -373,7 +373,7 @@ utils.pbkdf2 = function pbkdf2(key, salt, iterations, dkLen) {
U = utils.sha512hmac(block1, key); U = utils.sha512hmac(block1, key);
utils.copy(U.slice(0, hLen), T, 0); U.copy(T, 0, 0, hLen);
for (j = 1; j < iterations; j++) { for (j = 1; j < iterations; j++) {
U = utils.sha512hmac(U, key); U = utils.sha512hmac(U, key);
@ -384,7 +384,7 @@ utils.pbkdf2 = function pbkdf2(key, salt, iterations, dkLen) {
destPos = (i - 1) * hLen; destPos = (i - 1) * hLen;
len = i === l ? r : hLen; len = i === l ? r : hLen;
utils.copy(T.slice(0, len), DK, 0); T.copy(DK, 0, 0, len);
} }
return DK; return DK;
@ -466,30 +466,6 @@ utils.decrypt = function decrypt(data, passphrase) {
return out; return out;
}; };
/**
* Copy a buffer onto another.
* @param {Buffer} src
* @param {Buffer} dst
* @param {Number?} offset
*/
utils.copy = function copy(src, dst, off) {
return src.copy(dst, off, 0, src.length);
};
/**
* Convert a buffer to hex (ensure hex).
* @param {Buffer|String} msg
* @returns {String} Hex string.
*/
utils.toHex = function toHex(msg) {
if (typeof msg === 'string')
return msg;
return msg.toString('hex');
};
/** /**
* Test whether a string is hex. Note that this * Test whether a string is hex. Note that this
* may yield a false positive on base58 strings. * may yield a false positive on base58 strings.
@ -508,11 +484,11 @@ utils.isHex = function isHex(msg) {
* @returns {Boolean} * @returns {Boolean}
*/ */
utils.isEqual = function isEqual(a, b) { utils.equals = function isEqual(a, b) {
var i; var i;
if (!a || !b) assert(Buffer.isBuffer(a));
return false; assert(Buffer.isBuffer(b));
if (a.length !== b.length) if (a.length !== b.length)
return false; return false;
@ -2522,7 +2498,7 @@ utils.buildMerkleTree = function buildMerkleTree(leaves) {
for (i = 0; i < size; i += 2) { for (i = 0; i < size; i += 2) {
i2 = Math.min(i + 1, size - 1); i2 = Math.min(i + 1, size - 1);
if (i2 === i + 1 && i2 + 1 === size if (i2 === i + 1 && i2 + 1 === size
&& utils.isEqual(tree[j + i], tree[j + i2])) { && utils.equals(tree[j + i], tree[j + i2])) {
return; return;
} }
hash = Buffer.concat([tree[j + i], tree[j + i2]]); hash = Buffer.concat([tree[j + i], tree[j + i2]]);
@ -2623,7 +2599,7 @@ utils.indexOf = function indexOf(arr, buf) {
for (i = 0; i < arr.length; i++) { for (i = 0; i < arr.length; i++) {
if (!Buffer.isBuffer(arr[i])) if (!Buffer.isBuffer(arr[i]))
continue; continue;
if (utils.isEqual(arr[i], buf)) if (utils.equals(arr[i], buf))
return i; return i;
} }
@ -2806,7 +2782,7 @@ function VerifyError(object, code, reason, score) {
+ ' (code=' + code + ' (code=' + code
+ ', score=' + score + ', score=' + score
+ ', height=' + this.height + ', height=' + this.height
+ ', hash=' + utils.revHex(utils.toHex(this.hash)) + ')'; + ', hash=' + utils.revHex(this.hash.toString('hex')) + ')';
} }
utils.inherits(VerifyError, Error); utils.inherits(VerifyError, Error);

View File

@ -1049,7 +1049,7 @@ Wallet.prototype.getRedeem = function getRedeem(hash, prefix) {
return; return;
if (address.program && hash.length === 20) { if (address.program && hash.length === 20) {
if (utils.isEqual(hash, address.programHash)) if (utils.equals(hash, address.programHash))
return address.program; return address.program;
} }

View File

@ -55,9 +55,9 @@ BufferWriter.prototype.render = function render(keep) {
case '64': off += utils.write64(data, item[1], off); break; case '64': off += utils.write64(data, item[1], off); break;
case '64be': off += utils.write64BE(data, item[1], off); break; case '64be': off += utils.write64BE(data, item[1], off); break;
case 'varint': off += utils.writeVarint(data, item[1], off); break; case 'varint': off += utils.writeVarint(data, item[1], off); break;
case 'bytes': off += utils.copy(item[1], data, off); break; case 'bytes': off += item[1].copy(data, off); break;
case 'checksum': case 'checksum':
off += utils.copy(utils.checksum(data.slice(0, off)), data, off); off += utils.checksum(data.slice(0, off)).copy(data, off);
break; break;
} }
} }

View File

@ -26,7 +26,7 @@ describe('Block', function() {
'33825657ba32afe269819f01993bd77baba86379043168c94845d32370e53562' ], '33825657ba32afe269819f01993bd77baba86379043168c94845d32370e53562' ],
flags: new Buffer([ 245, 90, 0 ]) flags: new Buffer([ 245, 90, 0 ])
}, 'merkleblock'); }, 'merkleblock');
var raw = bcoin.utils.toHex(block.toRaw()); var raw = block.toRaw('hex');
it('should parse partial merkle tree', function() { it('should parse partial merkle tree', function() {
assert(block.verify()); assert(block.verify());
@ -41,7 +41,7 @@ describe('Block', function() {
it('should decode/encode with parser/framer', function() { it('should decode/encode with parser/framer', function() {
var b = bcoin.merkleblock(parser.parseMerkleBlock(new Buffer(raw, 'hex'))); var b = bcoin.merkleblock(parser.parseMerkleBlock(new Buffer(raw, 'hex')));
assert.equal(bcoin.utils.toHex(b.render()), raw); assert.equal(b.render().toString('hex'), raw);
}); });
it('should be verifiable', function() { it('should be verifiable', function() {

View File

@ -32,7 +32,7 @@ describe('HD', function() {
var master, child1, child2, child3, child4, child5, child6; var master, child1, child2, child3, child4, child5, child6;
it('should create a pbkdf2 seed', function() { it('should create a pbkdf2 seed', function() {
var checkSeed = utils.toHex(bcoin.utils.pbkdf2(phrase, 'mnemonic' + 'foo', 2048, 64)); var checkSeed = bcoin.utils.pbkdf2(phrase, 'mnemonic' + 'foo', 2048, 64).toString('hex');
assert.equal(checkSeed, seed); assert.equal(checkSeed, seed);
}); });

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.ONE_HASH, hash: constants.ONE_HASH.toString('hex'),
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.ONE_HASH, hash: constants.ONE_HASH.toString('hex'),
index: 0 index: 0
}, },
script: new bcoin.script([]), script: new bcoin.script([]),

View File

@ -15,15 +15,15 @@ describe('Script', function() {
var decoded = bcoin.script.decode(new Buffer(src, 'hex')); var decoded = bcoin.script.decode(new Buffer(src, 'hex'));
assert.equal(decoded.length, 3); assert.equal(decoded.length, 3);
assert.equal( assert.equal(
bcoin.utils.toHex(decoded[0]), decoded[0].toString('hex'),
'000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'); '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
assert.equal( assert.equal(
bcoin.utils.toHex(decoded[1]), decoded[1].toString('hex'),
'101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f'); '101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f');
assert.equal(decoded[2], opcodes.OP_CHECKSIG); assert.equal(decoded[2], opcodes.OP_CHECKSIG);
var dst = bcoin.script.encode(decoded); var dst = bcoin.script.encode(decoded);
assert.equal(bcoin.utils.toHex(dst), src); assert.equal(dst.toString('hex'), src);
}); });
if (0) if (0)

View File

@ -43,7 +43,7 @@ describe('TX', function() {
it('should decode/encode with parser/framer', function() { it('should decode/encode with parser/framer', function() {
var tx = bcoin.tx(parser.parseTX(new Buffer(raw, 'hex'))); var tx = bcoin.tx(parser.parseTX(new Buffer(raw, 'hex')));
assert.equal(bcoin.utils.toHex(tx.render()), raw); assert.equal(tx.render().toString('hex'), raw);
}); });
it('should be verifiable', function() { it('should be verifiable', function() {

View File

@ -6,7 +6,7 @@ var assert = utils.assert;
var dummyInput = { var dummyInput = {
prevout: { prevout: {
hash: constants.ZERO_HASH, hash: constants.NULL_HASH,
index: 0 index: 0
}, },
coin: { coin: {
@ -15,7 +15,7 @@ var dummyInput = {
value: constants.MAX_MONEY.clone(), value: constants.MAX_MONEY.clone(),
script: new bcoin.script([]), script: new bcoin.script([]),
coinbase: false, coinbase: false,
hash: constants.ZERO_HASH, hash: constants.NULL_HASH,
index: 0 index: 0
}, },
script: new bcoin.script([]), script: new bcoin.script([]),