From c9ebe29e39d429db9d77d75ea7ccca35d99c0497 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Tue, 6 Sep 2016 15:15:36 -0700 Subject: [PATCH] crypto: do not expose crypto module from utils. --- lib/bip70/bip70.js | 3 +- lib/bip70/pk.js | 46 ++++------ lib/bip70/x509.js | 5 +- lib/chain/chainentry.js | 3 +- lib/crypto/crypto.js | 37 ++++++++ lib/crypto/ec.js | 23 ----- lib/crypto/scrypt-async.js | 5 +- lib/crypto/scrypt.js | 6 +- lib/hd/mnemonic.js | 22 +++-- lib/hd/private.js | 7 +- lib/hd/public.js | 5 +- lib/http/rpc.js | 17 ++-- lib/http/server.js | 7 +- lib/miner/minerblock.js | 5 +- lib/net/bip150.js | 11 ++- lib/net/bip151.js | 13 +-- lib/net/bip152.js | 3 +- lib/net/framer.js | 3 +- lib/net/packets.js | 3 +- lib/net/parser.js | 3 +- lib/primitives/abstractblock.js | 3 +- lib/primitives/address.js | 19 ++-- lib/primitives/block.js | 21 +++-- lib/primitives/keyring.js | 5 +- lib/primitives/merkleblock.js | 5 +- lib/primitives/mtx.js | 3 +- lib/primitives/tx.js | 17 ++-- lib/script/script.js | 23 ++--- lib/utils/reader.js | 3 +- lib/utils/utils.js | 157 +------------------------------- lib/utils/writer.js | 3 +- lib/wallet/wallet.js | 15 +-- lib/wallet/walletdb.js | 3 +- test/aes-test.js | 25 ++--- test/bip150-test.js | 1 + test/bip151-test.js | 1 + test/bip70-test.js | 1 + test/block-test.js | 1 + test/bloom-test.js | 1 + test/chain-test.js | 1 + test/hd-test.js | 3 +- test/http-test.js | 1 + test/mempool-test.js | 5 +- test/mnemonic-test.js | 1 + test/protocol-test.js | 1 + test/script-test.js | 1 + test/tx-test.js | 3 +- test/utils-test.js | 11 ++- test/wallet-test.js | 1 + 49 files changed, 232 insertions(+), 330 deletions(-) diff --git a/lib/bip70/bip70.js b/lib/bip70/bip70.js index e7d59f64..3138b09d 100644 --- a/lib/bip70/bip70.js +++ b/lib/bip70/bip70.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var assert = require('assert'); var utils = bcoin.utils; +var crypto = require('../crypto/crypto'); var x509 = require('./x509'); var asn1 = require('./asn1'); var protobuf = require('./protobuf'); @@ -140,7 +141,7 @@ PaymentRequest.prototype.signatureData = function signatureData() { PaymentRequest.prototype.signatureHash = function signatureHash() { var alg = this.getAlgorithm(); assert(alg, 'No hash algorithm available.'); - return utils.hash(alg.hash, this.signatureData()); + return crypto.hash(alg.hash, this.signatureData()); }; PaymentRequest.prototype.setChain = function setChain(chain) { diff --git a/lib/bip70/pk.js b/lib/bip70/pk.js index 20b5d26b..0890f955 100644 --- a/lib/bip70/pk.js +++ b/lib/bip70/pk.js @@ -9,12 +9,12 @@ var bn = require('bn.js'); var asn1 = require('./asn1'); var elliptic = require('elliptic'); -var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); -var crypto; +var nativeCrypto; try { - crypto = require('crypto'); + nativeCrypto = require('crypto'); } catch (e) { ; } @@ -39,7 +39,7 @@ rsa.prefixes = { // https://github.com/golang/go/blob/master/src/crypto/rsa/pkcs1v15.go rsa.verify = function verify(hashAlg, msg, sig, key) { - var hash = utils.hash(hashAlg, msg); + var hash = crypto.hash(hashAlg, msg); var prefix = rsa.prefixes[hashAlg]; var len = prefix.length + hash.length; var pub = asn1.parseRSAPublic(key); @@ -54,20 +54,20 @@ rsa.verify = function verify(hashAlg, msg, sig, key) { m = rsa.encrypt(N, e, sig); em = leftpad(m, k); - ok = ceq(em[0], 0x00); - ok &= ceq(em[1], 0x01); - ok &= utils.ccmp(em.slice(k - hash.length, k), hash); - ok &= utils.ccmp(em.slice(k - len, k - hash.length), prefix); - ok &= ceq(em[k - len - 1], 0x00); + ok = crypto.ceq(em[0], 0x00); + ok &= crypto.ceq(em[1], 0x01); + ok &= crypto.ccmp(em.slice(k - hash.length, k), hash); + ok &= crypto.ccmp(em.slice(k - len, k - hash.length), prefix); + ok &= crypto.ceq(em[k - len - 1], 0x00); for (i = 2; i < k - len - 1; i++) - ok &= ceq(em[i], 0xff); + ok &= crypto.ceq(em[i], 0xff); return ok === 1; }; rsa.sign = function sign(hashAlg, msg, key) { - var hash = utils.hash(hashAlg, msg); + var hash = crypto.hash(hashAlg, msg); var prefix = rsa.prefixes[hashAlg]; var len = prefix.length + hash.length; var priv = asn1.parseRSAPrivate(key); @@ -114,13 +114,13 @@ rsa.encrypt = function encrypt(N, e, m) { }; ecdsa.verify = function verify(curve, msg, hashAlg, key, sig) { - var hash = utils.hash(hashAlg, msg); + var hash = crypto.hash(hashAlg, msg); var ec = elliptic.ec(curve); return ec.verify(hash, sig, key); }; ecdsa.sign = function sign(curve, msg, hashAlg, key) { - var hash = utils.hash(hashAlg, msg); + var hash = crypto.hash(hashAlg, msg); var ec = elliptic.ec(curve); return new Buffer(ec.sign(hash, key)); }; @@ -128,11 +128,11 @@ ecdsa.sign = function sign(curve, msg, hashAlg, key) { native.verify = function verify(alg, hash, msg, sig, key) { var algo, verify; - if (!crypto) + if (!nativeCrypto) return false; algo = normalizeAlg(alg, hash); - verify = crypto.createVerify(algo); + verify = nativeCrypto.createVerify(algo); verify.update(msg); return verify.verify(key, sig); @@ -141,11 +141,11 @@ native.verify = function verify(alg, hash, msg, sig, key) { native.sign = function _sign(alg, hash, msg, key) { var algo, sig; - if (!crypto) + if (!nativeCrypto) return false; algo = normalizeAlg(alg, hash); - sig = crypto.createSign(algo); + sig = nativeCrypto.createSign(algo); sig.update(msg); return sig.sign(key); }; @@ -175,7 +175,7 @@ pk._verify = function verify(hash, msg, sig, key) { pem = pk.toPEM(key, 'public key'); return native.verify(key.alg, hash, msg, sig, pem); case 'rsa': - if (crypto) { + if (nativeCrypto) { pem = pk.toPEM(key, 'public key'); return native.verify(key.alg, hash, msg, sig, pem); } @@ -204,7 +204,7 @@ pk.sign = function sign(hash, msg, key) { pem = pk.toPEM(key, 'private key'); return native.sign(key.alg, hash, msg, pem); case 'rsa': - if (crypto) { + if (nativeCrypto) { pem = pk.toPEM(key, 'private key'); return native.sign(key.alg, hash, msg, pem); } @@ -218,14 +218,6 @@ pk.sign = function sign(hash, msg, key) { } }; -function ceq(a, b) { - var r = ~(a ^ b) & 0xff; - r &= r >>> 4; - r &= r >>> 2; - r &= r >>> 1; - return r === 1; -} - function leftpad(input, size) { var n = input.length; var out; diff --git a/lib/bip70/x509.js b/lib/bip70/x509.js index de089e0c..136ca1f0 100644 --- a/lib/bip70/x509.js +++ b/lib/bip70/x509.js @@ -9,6 +9,7 @@ var assert = require('assert'); var asn1 = require('./asn1'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var pk = require('./pk'); var x509 = exports; @@ -43,7 +44,7 @@ x509.trusted = {}; x509.allowUntrusted = false; x509.isTrusted = function isTrusted(cert) { - var fingerprint = utils.sha256(cert.raw); + var fingerprint = crypto.sha256(cert.raw); var hash = fingerprint.toString('hex'); return x509.trusted[hash] === true; }; @@ -78,7 +79,7 @@ x509.setTrust = function setTrust(certs) { cert = x509.parse(cert); assert(cert, 'Could not parse certificate.'); - hash = utils.sha256(cert.raw).toString('hex'); + hash = crypto.sha256(cert.raw).toString('hex'); x509.trusted[hash] = true; } }; diff --git a/lib/chain/chainentry.js b/lib/chain/chainentry.js index 049ff1bd..5942556e 100644 --- a/lib/chain/chainentry.js +++ b/lib/chain/chainentry.js @@ -11,6 +11,7 @@ var bcoin = require('../env'); var bn = require('bn.js'); var constants = bcoin.constants; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var BufferWriter = require('../utils/writer'); var BufferReader = require('../utils/reader'); @@ -528,7 +529,7 @@ ChainEntry.prototype.toRaw = function toRaw(writer) { ChainEntry.prototype.fromRaw = function fromRaw(data) { var p = new BufferReader(data, true); - var hash = utils.hash256(p.readBytes(80)); + var hash = crypto.hash256(p.readBytes(80)); p.seek(-80); diff --git a/lib/crypto/crypto.js b/lib/crypto/crypto.js index 6006f82e..73135770 100644 --- a/lib/crypto/crypto.js +++ b/lib/crypto/crypto.js @@ -8,6 +8,7 @@ 'use strict'; var assert = require('assert'); +var random = require('./random'); var nativeCrypto, supersha, hash, aes; var isBrowser = @@ -416,6 +417,21 @@ crypto.ccmp = function ccmp(a, b) { return res === 0; }; +/** + * Compare two bytes in constant time. + * @param {Number} a + * @param {Number} b + * @returns {Boolean} + */ + +crypto.ceq = function ceq(a, b) { + var r = ~(a ^ b) & 0xff; + r &= r >>> 4; + r &= r >>> 2; + r &= r >>> 1; + return r === 1; +}; + /** * Build a merkle tree from leaves. * @param {Buffer[]} leaves @@ -527,3 +543,24 @@ crypto.checkMerkleBranch = function checkMerkleBranch(hash, branch, index) { return hash; }; + +/** + * Generate some random bytes. + * @function + * @param {Number} size + * @returns {Buffer} + */ + +crypto.randomBytes = random.randomBytes; + +/** + * Generate a random number within a range. + * Probably more cryptographically sound than + * `Math.random()`. + * @function + * @param {Number} min - Inclusive. + * @param {Number} max - Exclusive. + * @returns {Number} + */ + +crypto.randomInt = random.randomInt; diff --git a/lib/crypto/ec.js b/lib/crypto/ec.js index ba556cae..73e3dcaa 100644 --- a/lib/crypto/ec.js +++ b/lib/crypto/ec.js @@ -218,29 +218,6 @@ ec.recover = function recover(msg, sig, j, compressed) { return new Buffer(key); }; -/** - * Generate some random bytes. - * @param {Number} size - * @returns {Buffer} - */ - -ec.random = function _random(size) { - return random.randomBytes(size); -}; - -/** - * Generate a random number within a range. - * Probably more cryptographically sound than - * `Math.random()`. - * @param {Number} min - Inclusive. - * @param {Number} max - Exclusive. - * @returns {Number} - */ - -ec.rand = function rand(min, max) { - return random.randomInt(min, max); -}; - /** * Verify a signature. * @param {Buffer} msg diff --git a/lib/crypto/scrypt-async.js b/lib/crypto/scrypt-async.js index 2fe0a415..73f6bef9 100644 --- a/lib/crypto/scrypt-async.js +++ b/lib/crypto/scrypt-async.js @@ -34,6 +34,7 @@ 'use strict'; var utils = require('../utils/utils'); +var crypto = require('./crypto'); /** * Javascript scrypt implementation. Scrypt is @@ -69,7 +70,7 @@ function scrypt(passwd, salt, N, r, p, len, callback) { XY = new Buffer(256 * r); V = new Buffer(128 * r * N); - utils.pbkdf2(passwd, salt, 1, p * 128 * r, 'sha256', function(err, B) { + crypto.pbkdf2(passwd, salt, 1, p * 128 * r, 'sha256', function(err, B) { if (err) return callback(err); @@ -79,7 +80,7 @@ function scrypt(passwd, salt, N, r, p, len, callback) { if (err) return callback(err); - utils.pbkdf2(passwd, B, 1, len, 'sha256', callback); + crypto.pbkdf2(passwd, B, 1, len, 'sha256', callback); }); }); } diff --git a/lib/crypto/scrypt.js b/lib/crypto/scrypt.js index a68abd50..8bacbb85 100644 --- a/lib/crypto/scrypt.js +++ b/lib/crypto/scrypt.js @@ -33,7 +33,7 @@ 'use strict'; -var utils = require('../utils/utils'); +var crypto = require('./crypto'); /** * Javascript scrypt implementation. Scrypt is @@ -69,12 +69,12 @@ function scrypt(passwd, salt, N, r, p, len) { XY = new Buffer(256 * r); V = new Buffer(128 * r * N); - B = utils.pbkdf2Sync(passwd, salt, 1, p * 128 * r, 'sha256'); + B = crypto.pbkdf2Sync(passwd, salt, 1, p * 128 * r, 'sha256'); for (i = 0; i < p; i++) smix(B, i * 128 * r, r, N, V, XY); - return utils.pbkdf2Sync(passwd, B, 1, len, 'sha256'); + return crypto.pbkdf2Sync(passwd, B, 1, len, 'sha256'); } function salsa20_8(B) { diff --git a/lib/hd/mnemonic.js b/lib/hd/mnemonic.js index 9c95a01a..93d44509 100644 --- a/lib/hd/mnemonic.js +++ b/lib/hd/mnemonic.js @@ -8,6 +8,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var random = require('../crypto/random'); var assert = utils.assert; var constants = bcoin.constants; @@ -141,7 +142,7 @@ Mnemonic.prototype.toSeed = function toSeed(passphrase) { this.passphrase = passphrase; - return utils.pbkdf2Sync( + return crypto.pbkdf2Sync( nfkd(this.getPhrase()), nfkd('mnemonic' + passphrase), 2048, 64, 'sha512'); @@ -181,7 +182,8 @@ Mnemonic.prototype.getEntropy = function getEntropy() { */ Mnemonic.prototype.getPhrase = function getPhrase() { - var i, j, phrase, wordlist, bits, entropy, index, pos, oct, bit; + var i, j, phrase, wordlist, bits, ent, entropy; + var index, pos, oct, bit; if (this.phrase) return this.phrase; @@ -189,18 +191,20 @@ Mnemonic.prototype.getPhrase = function getPhrase() { phrase = []; wordlist = Mnemonic.getWordlist(this.language); - entropy = this.getEntropy(); + ent = this.getEntropy(); bits = this.bits; - // Append the hash to the entropy to - // make things easy when grabbing - // the checksum bits. - entropy = Buffer.concat([entropy, utils.sha256(entropy)]); - // Include the first `ENT / 32` bits // of the hash (the checksum). bits += bits / 32; + // Append the hash to the entropy to + // make things easy when grabbing + // the checksum bits. + entropy = new Buffer(Math.ceil(bits / 8)); + ent.copy(entropy, 0); + crypto.sha256(ent).copy(entropy, ent.length); + // Build the mnemonic by reading // 11 bit indexes from the entropy. for (i = 0; i < bits / 11; i++) { @@ -273,7 +277,7 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) { entropy = ent.slice(0, ent.length - cbytes); ent = ent.slice(ent.length - cbytes); - chk = utils.sha256(entropy); + chk = crypto.sha256(entropy); for (i = 0; i < cbits; i++) { bit = i % 8; diff --git a/lib/hd/private.js b/lib/hd/private.js index 14934647..fee159fd 100644 --- a/lib/hd/private.js +++ b/lib/hd/private.js @@ -8,6 +8,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var ec = require('../crypto/ec'); var random = require('../crypto/random'); var assert = utils.assert; @@ -222,7 +223,7 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) { data = p.render(); - hash = utils.hmac('sha512', data, this.chainCode); + hash = crypto.hmac('sha512', data, this.chainCode); left = hash.slice(0, 32); right = hash.slice(32, 64); @@ -233,7 +234,7 @@ HDPrivateKey.prototype.derive = function derive(index, hardened) { } if (!this.fingerPrint) - this.fingerPrint = utils.hash160(this.publicKey).slice(0, 4); + this.fingerPrint = crypto.hash160(this.publicKey).slice(0, 4); child = new HDPrivateKey(); child.network = this.network; @@ -480,7 +481,7 @@ HDPrivateKey.prototype.fromSeed = function fromSeed(seed, network) { throw new Error('Entropy not in range.'); } - hash = utils.hmac('sha512', seed, 'Bitcoin seed'); + hash = crypto.hmac('sha512', seed, 'Bitcoin seed'); left = hash.slice(0, 32); right = hash.slice(32, 64); diff --git a/lib/hd/public.js b/lib/hd/public.js index d0848309..a03fd59f 100644 --- a/lib/hd/public.js +++ b/lib/hd/public.js @@ -8,6 +8,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var ec = require('../crypto/ec'); var assert = utils.assert; var constants = bcoin.constants; @@ -165,7 +166,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) { p.writeU32BE(index); data = p.render(); - hash = utils.hmac('sha512', data, this.chainCode); + hash = crypto.hmac('sha512', data, this.chainCode); left = hash.slice(0, 32); right = hash.slice(32, 64); @@ -176,7 +177,7 @@ HDPublicKey.prototype.derive = function derive(index, hardened) { } if (!this.fingerPrint) - this.fingerPrint = utils.hash160(this.publicKey).slice(0, 4); + this.fingerPrint = crypto.hash160(this.publicKey).slice(0, 4); child = new HDPublicKey(); child.network = this.network; diff --git a/lib/http/rpc.js b/lib/http/rpc.js index 4d4cc5a6..33cf9efa 100644 --- a/lib/http/rpc.js +++ b/lib/http/rpc.js @@ -8,6 +8,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var NetworkAddress = bcoin.packets.NetworkAddress; @@ -1954,7 +1955,7 @@ RPC.prototype.decodescript = function decodescript(args, callback) { if (data.length > 0) script.fromRaw(new Buffer(data, 'hex')); - hash = utils.hash160(script.toRaw()); + hash = crypto.hash160(script.toRaw()); address = bcoin.address.fromHash(hash, bcoin.script.types.SCRIPTHASH); script = this._scriptToJSON(script); @@ -2284,7 +2285,7 @@ RPC.prototype._scriptForWitness = function scriptForWitness(script) { var hash; if (script.isPubkey()) { - hash = utils.hash160(script.get(0)); + hash = crypto.hash160(script.get(0)); return bcoin.script.fromProgram(0, hash); } @@ -2293,7 +2294,7 @@ RPC.prototype._scriptForWitness = function scriptForWitness(script) { return bcoin.script.fromProgram(0, hash); } - hash = utils.sha256(script.toRaw()); + hash = crypto.sha256(script.toRaw()); return bcoin.script.fromProgram(0, hash); }; @@ -2373,16 +2374,16 @@ RPC.prototype.verifymessage = function verifymessage(args, callback) { sig = new Buffer(sig, 'base64'); msg = new Buffer(RPC.magic + msg, 'utf8'); - msg = utils.hash256(msg); + msg = crypto.hash256(msg); key = bcoin.ec.recover(msg, sig, 0, true); if (!key) return callback(null, false); - key = utils.hash160(key); + key = crypto.hash160(key); - callback(null, utils.ccmp(key, address)); + callback(null, crypto.ccmp(key, address)); }; RPC.prototype.signmessagewithprivkey = function signmessagewithprivkey(args, callback) { @@ -2396,7 +2397,7 @@ RPC.prototype.signmessagewithprivkey = function signmessagewithprivkey(args, cal key = bcoin.keyring.fromSecret(key); msg = new Buffer(RPC.magic + msg, 'utf8'); - msg = utils.hash256(msg); + msg = crypto.hash256(msg); sig = key.sign(msg); @@ -3941,7 +3942,7 @@ RPC.prototype.signmessage = function signmessage(args, callback) { return callback(new RPCError('Wallet is locked.')); msg = new Buffer(RPC.magic + msg, 'utf8'); - msg = utils.hash256(msg); + msg = crypto.hash256(msg); sig = ring.sign(msg); diff --git a/lib/http/server.js b/lib/http/server.js index b0c9fd88..c3229c37 100644 --- a/lib/http/server.js +++ b/lib/http/server.js @@ -15,6 +15,7 @@ var constants = bcoin.constants; var http = require('./'); var HTTPBase = http.base; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var random = require('../crypto/random'); var assert = utils.assert; var RPC; /*= require('./rpc'); - load lazily */ @@ -145,7 +146,7 @@ HTTPServer.prototype._init = function _init() { if (!self.apiHash) return next(); - if (utils.ccmp(hash256(req.password), self.apiHash)) + if (crypto.ccmp(hash256(req.password), self.apiHash)) return next(); res.setHeader('WWW-Authenticate', 'Basic realm="node"'); @@ -965,7 +966,7 @@ HTTPServer.prototype._initIO = function _initIO() { socket.stop(); if (self.apiHash) { - if (!utils.ccmp(hash256(apiKey), self.apiHash)) + if (!crypto.ccmp(hash256(apiKey), self.apiHash)) return callback({ error: 'Bad key.' }); } @@ -1449,7 +1450,7 @@ function hash256(data) { return new Buffer(0); if (data.length > 200) return new Buffer(0); - return utils.hash256(new Buffer(data, 'utf8')); + return crypto.hash256(new Buffer(data, 'utf8')); } function softMerge(a, b, soft) { diff --git a/lib/miner/minerblock.js b/lib/miner/minerblock.js index 82cb2ea9..a6fbe27e 100644 --- a/lib/miner/minerblock.js +++ b/lib/miner/minerblock.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var bn = require('bn.js'); @@ -115,7 +116,7 @@ MinerBlock.prototype._init = function _init() { // Our witness nonce is the hash256 // of the previous block hash. hash = new Buffer(this.tip.hash, 'hex'); - witnessNonce = utils.hash256(hash); + witnessNonce = crypto.hash256(hash); // Set up the witness nonce. input.witness.set(0, witnessNonce); @@ -255,7 +256,7 @@ MinerBlock.prototype.findNonce = function findNonce() { // The heart and soul of the miner: match the target. while (block.nonce <= 0xffffffff) { // Hash and test against the next target. - if (rcmp(utils.hash256(data), target) <= 0) { + if (rcmp(crypto.hash256(data), target) <= 0) { this.coinbase.mutable = false; this.block.mutable = false; return true; diff --git a/lib/net/bip150.js b/lib/net/bip150.js index 96c6af59..1bb2eca4 100644 --- a/lib/net/bip150.js +++ b/lib/net/bip150.js @@ -11,6 +11,7 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var random = require('../crypto/random'); var assert = utils.assert; var constants = bcoin.constants; @@ -91,7 +92,7 @@ BIP150.prototype.challenge = function challenge(payload) { msg = this.hash(this.input.sid, type, this.publicKey); - if (!utils.ccmp(hash, msg)) + if (!crypto.ccmp(hash, msg)) return ZERO_SIG; if (this.isAuthed()) { @@ -194,7 +195,7 @@ BIP150.prototype.rekey = function rekey(sid, key, req, res) { key.copy(seed, 32); req.copy(seed, 64); res.copy(seed, 97); - return utils.hash256(seed); + return crypto.hash256(seed); }; BIP150.prototype.rekeyInput = function rekeyInput() { @@ -220,7 +221,7 @@ BIP150.prototype.hash = function hash(sid, ch, key) { sid.copy(data, 0); data[32] = ch.charCodeAt(0); key.copy(data, 33); - return utils.hash256(data); + return crypto.hash256(data); }; BIP150.prototype.findAuthorized = function findAuthorized(hash) { @@ -234,7 +235,7 @@ BIP150.prototype.findAuthorized = function findAuthorized(hash) { // XXX Do we really need a constant // time compare here? Do it just to // be safe I guess. - if (utils.ccmp(msg, hash)) + if (crypto.ccmp(msg, hash)) return key; } }; @@ -289,7 +290,7 @@ BIP150.address = function address(key) { var p = new bcoin.writer(); p.writeU8(0x0f); p.writeU16BE(0xff01); - p.writeBytes(utils.hash160(key)); + p.writeBytes(crypto.hash160(key)); p.writeChecksum(); return utils.toBase58(p.render()); }; diff --git a/lib/net/bip151.js b/lib/net/bip151.js index 4d3568f2..a63818cb 100644 --- a/lib/net/bip151.js +++ b/lib/net/bip151.js @@ -15,6 +15,7 @@ var EventEmitter = require('events').EventEmitter; var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var chachapoly = require('../crypto/chachapoly'); @@ -101,10 +102,10 @@ BIP151Stream.prototype.init = function init(publicKey) { p.writeBytes(this.secret); p.writeU8(this.cipher); - this.prk = utils.hkdfExtract(p.render(), HKDF_SALT, 'sha256'); - this.k1 = utils.hkdfExpand(this.prk, INFO_KEY1, 32, 'sha256'); - this.k2 = utils.hkdfExpand(this.prk, INFO_KEY2, 32, 'sha256'); - this.sid = utils.hkdfExpand(this.prk, INFO_SID, 32, 'sha256'); + this.prk = crypto.hkdfExtract(p.render(), HKDF_SALT, 'sha256'); + this.k1 = crypto.hkdfExpand(this.prk, INFO_KEY1, 32, 'sha256'); + this.k2 = crypto.hkdfExpand(this.prk, INFO_KEY2, 32, 'sha256'); + this.sid = crypto.hkdfExpand(this.prk, INFO_SID, 32, 'sha256'); this.seq = 0; @@ -151,10 +152,10 @@ BIP151Stream.prototype.rekey = function rekey(k1, k2) { this.sid.copy(seed, 0); this.k1.copy(seed, 32); - this.k1 = utils.hash256(seed); + this.k1 = crypto.hash256(seed); this.k2.copy(seed, 32); - this.k2 = utils.hash256(seed); + this.k2 = crypto.hash256(seed); } else { this.k1 = k1; this.k2 = k2; diff --git a/lib/net/bip152.js b/lib/net/bip152.js index bae64f62..9f4eebd6 100644 --- a/lib/net/bip152.js +++ b/lib/net/bip152.js @@ -8,6 +8,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var siphash = require('../crypto/siphash'); @@ -246,7 +247,7 @@ CompactBlock.prototype.initKey = function initKey() { this.abbr().copy(data, 0); this.keyNonce.copy(data, 80); - hash = utils.sha256(data); + hash = crypto.sha256(data); this.sipKey = hash.slice(0, 16); }; diff --git a/lib/net/framer.js b/lib/net/framer.js index 6356eb05..5f8b73ed 100644 --- a/lib/net/framer.js +++ b/lib/net/framer.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var BufferWriter = require('../utils/writer'); var DUMMY = new Buffer(0); @@ -66,7 +67,7 @@ Framer.prototype.packet = function packet(cmd, payload, checksum) { packet.writeUInt32LE(payload.length, 16, true); if (!checksum) - checksum = utils.hash256(payload); + checksum = crypto.hash256(payload); // Checksum checksum.copy(packet, 20, 0, 4); diff --git a/lib/net/packets.js b/lib/net/packets.js index cbaa506d..1b63f872 100644 --- a/lib/net/packets.js +++ b/lib/net/packets.js @@ -10,6 +10,7 @@ var bcoin = require('../env'); var constants = require('../protocol/constants'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var bn = require('bn.js'); var IP = require('../utils/ip'); var assert = utils.assert; @@ -436,7 +437,7 @@ AlertPacket.fromOptions = function fromOptions(options) { AlertPacket.prototype.hash = function hash(enc) { if (!this._hash) - this._hash = utils.hash256(this.toPayload()); + this._hash = crypto.hash256(this.toPayload()); return enc === 'hex' ? this._hash.toString('hex') : this._hash; }; diff --git a/lib/net/parser.js b/lib/net/parser.js index 7b3f57e5..43338cee 100644 --- a/lib/net/parser.js +++ b/lib/net/parser.js @@ -10,6 +10,7 @@ var bcoin = require('../env'); var EventEmitter = require('events').EventEmitter; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = require('../protocol/constants'); var BufferReader = require('../utils/reader'); @@ -135,7 +136,7 @@ Parser.prototype.parse = function parse(chunk) { this.packet.payload = chunk; - checksum = utils.checksum(this.packet.payload).readUInt32LE(0, true); + checksum = crypto.checksum(this.packet.payload).readUInt32LE(0, true); if (checksum !== this.packet.checksum) { this.waiting = 24; diff --git a/lib/primitives/abstractblock.js b/lib/primitives/abstractblock.js index bb52c1f3..46bd848b 100644 --- a/lib/primitives/abstractblock.js +++ b/lib/primitives/abstractblock.js @@ -10,6 +10,7 @@ var bcoin = require('../env'); var constants = bcoin.constants; var utils = bcoin.utils; +var crypto = require('../crypto/crypto'); var assert = utils.assert; /** @@ -135,7 +136,7 @@ AbstractBlock.prototype.hash = function hash(enc) { var hash = this._hash; if (!hash) { - hash = utils.hash256(this.abbr()); + hash = crypto.hash256(this.abbr()); if (!this.mutable) this._hash = hash; } diff --git a/lib/primitives/address.js b/lib/primitives/address.js index 512b71f8..ea0323fc 100644 --- a/lib/primitives/address.js +++ b/lib/primitives/address.js @@ -11,6 +11,7 @@ var bcoin = require('../env'); var networks = bcoin.networks; var constants = bcoin.constants; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var BufferWriter = require('../utils/writer'); var BufferReader = require('../utils/reader'); @@ -256,7 +257,7 @@ Address.fromBase58 = function fromBase58(address) { Address.prototype.fromScript = function fromScript(script) { if (script.isPubkey()) { - this.hash = utils.hash160(script.get(0)); + this.hash = crypto.hash160(script.get(0)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; @@ -316,14 +317,14 @@ Address.prototype.fromWitness = function fromWitness(witness) { // We're pretty much screwed here // since we can't get the version. if (witness.isPubkeyhashInput()) { - this.hash = utils.hash160(witness.get(1)); + this.hash = crypto.hash160(witness.get(1)); this.type = scriptTypes.WITNESSPUBKEYHASH; this.version = 0; return this; } if (witness.isScripthashInput()) { - this.hash = utils.sha256(witness.get(witness.length - 1)); + this.hash = crypto.sha256(witness.get(witness.length - 1)); this.type = scriptTypes.WITNESSSCRIPTHASH; this.version = 0; return this; @@ -338,14 +339,14 @@ Address.prototype.fromWitness = function fromWitness(witness) { Address.prototype.fromInputScript = function fromInputScript(script) { if (script.isPubkeyhashInput()) { - this.hash = utils.hash160(script.get(1)); + this.hash = crypto.hash160(script.get(1)); this.type = scriptTypes.PUBKEYHASH; this.version = -1; return this; } if (script.isScripthashInput()) { - this.hash = utils.hash160(script.get(script.length - 1)); + this.hash = crypto.hash160(script.get(script.length - 1)); this.type = scriptTypes.SCRIPTHASH; this.version = -1; return this; @@ -472,10 +473,10 @@ Address.prototype.fromData = function fromData(data, type, version, network) { if (type === scriptTypes.WITNESSSCRIPTHASH) { if (version === 0) { assert(Buffer.isBuffer(data)); - data = utils.sha256(data); + data = crypto.sha256(data); } else if (version === 1) { assert(Array.isArray(data)); - data = utils.getMerkleRoot(data); + data = crypto.getMerkleRoot(data); } else { throw new Error('Cannot create from version=' + version); } @@ -483,9 +484,9 @@ Address.prototype.fromData = function fromData(data, type, version, network) { if (version !== 0) throw new Error('Cannot create from version=' + version); assert(Buffer.isBuffer(data)); - data = utils.hash160(data); + data = crypto.hash160(data); } else { - data = utils.hash160(data); + data = crypto.hash160(data); } return this.fromHash(data, type, version, network); diff --git a/lib/primitives/block.js b/lib/primitives/block.js index 5062bfe2..4eb1994f 100644 --- a/lib/primitives/block.js +++ b/lib/primitives/block.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var AbstractBlock = bcoin.abstractblock; @@ -284,7 +285,7 @@ Block.prototype.getMerkleRoot = function getMerkleRoot(enc) { for (i = 0; i < this.txs.length; i++) leaves.push(this.txs[i].hash()); - root = utils.getMerkleRoot(leaves); + root = crypto.getMerkleRoot(leaves); if (!root) return; @@ -304,7 +305,7 @@ Block.prototype.getMerkleRoot = function getMerkleRoot(enc) { Block.prototype.getCommitmentHash = function getCommitmentHash(enc) { var leaves = []; var witnessNonce = this.witnessNonce; - var i, witnessRoot, commitmentHash; + var i, buf, witnessRoot, commitmentHash; if (!witnessNonce) return; @@ -312,12 +313,16 @@ Block.prototype.getCommitmentHash = function getCommitmentHash(enc) { for (i = 0; i < this.txs.length; i++) leaves.push(this.txs[i].witnessHash()); - witnessRoot = utils.getMerkleRoot(leaves); + witnessRoot = crypto.getMerkleRoot(leaves); if (!witnessRoot) return; - commitmentHash = utils.hash256(Buffer.concat([witnessRoot, witnessNonce])); + buf = new Buffer(64); + witnessRoot.copy(buf, 0); + witnessNonce.copy(buf, 32); + + commitmentHash = crypto.hash256(buf); return enc === 'hex' ? commitmentHash.toString('hex') @@ -343,7 +348,7 @@ Block.prototype.__defineGetter__('witnessNonce', function() { }); Block.prototype.__defineGetter__('commitmentHash', function() { - var coinbase, i, commitment, commitmentHash; + var i, coinbase, script, commitmentHash; if (this._commitmentHash) return this._commitmentHash; @@ -354,9 +359,9 @@ Block.prototype.__defineGetter__('commitmentHash', function() { return; for (i = coinbase.outputs.length - 1; i >= 0; i--) { - commitment = coinbase.outputs[i].script; - if (commitment.isCommitment()) { - commitmentHash = commitment.getCommitmentHash(); + script = coinbase.outputs[i].script; + if (script.isCommitment()) { + commitmentHash = script.getCommitmentHash(); commitmentHash = commitmentHash.toString('hex'); if (!this.mutable) diff --git a/lib/primitives/keyring.js b/lib/primitives/keyring.js index daad4cd8..903ebabd 100644 --- a/lib/primitives/keyring.js +++ b/lib/primitives/keyring.js @@ -10,6 +10,7 @@ var bcoin = require('../env'); var constants = bcoin.constants; var utils = bcoin.utils; +var crypto = require('../crypto/crypto'); var assert = utils.assert; var networks = bcoin.networks; var BufferReader = require('../utils/reader'); @@ -345,7 +346,7 @@ KeyRing.prototype.getProgram = function getProgram() { if (!this._program) { if (!this.script) { - hash = utils.hash160(this.publicKey); + hash = crypto.hash160(this.publicKey); program = bcoin.script.fromProgram(0, hash); } else { hash = this.script.sha256(); @@ -485,7 +486,7 @@ KeyRing.prototype.getScriptAddress = function getScriptAddress(enc) { KeyRing.prototype.getKeyHash = function getKeyHash(enc) { if (!this._keyHash) - this._keyHash = utils.hash160(this.publicKey); + this._keyHash = crypto.hash160(this.publicKey); return enc === 'hex' ? this._keyHash.toString('hex') diff --git a/lib/primitives/merkleblock.js b/lib/primitives/merkleblock.js index f3854bbf..5f624855 100644 --- a/lib/primitives/merkleblock.js +++ b/lib/primitives/merkleblock.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var DUMMY = new Buffer([0]); @@ -223,7 +224,7 @@ MerkleBlock.prototype.extractTree = function extractTree() { left.copy(buf, 0); right.copy(buf, 32); - return utils.hash256(buf); + return crypto.hash256(buf); } for (p = 0; p < this.hashes.length; p++) @@ -553,7 +554,7 @@ MerkleBlock.fromMatches = function fromMatches(block, matches) { left.copy(buf, 0); right.copy(buf, 32); - return utils.hash256(buf); + return crypto.hash256(buf); } function traverse(height, pos, leaves, matches) { diff --git a/lib/primitives/mtx.js b/lib/primitives/mtx.js index 5ac2d31e..be32a799 100644 --- a/lib/primitives/mtx.js +++ b/lib/primitives/mtx.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var Script = bcoin.script; @@ -486,7 +487,7 @@ MTX.prototype.signVector = function signVector(prev, vector, sig, key) { // P2PKH if (prev.isPubkeyhash()) { // Make sure the pubkey hash is ours. - if (!utils.equal(utils.hash160(pub), prev.get(2))) + if (!utils.equal(crypto.hash160(pub), prev.get(2))) return false; // Already signed. diff --git a/lib/primitives/tx.js b/lib/primitives/tx.js index d91ccc2d..9b09e283 100644 --- a/lib/primitives/tx.js +++ b/lib/primitives/tx.js @@ -9,6 +9,7 @@ var bcoin = require('../env'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var Script = bcoin.script; @@ -200,7 +201,7 @@ TX.prototype.hash = function _hash(enc) { var hash = this._hash; if (!hash) { - hash = utils.hash256(this.toNormal()); + hash = crypto.hash256(this.toNormal()); if (!this.mutable) this._hash = hash; } @@ -230,7 +231,7 @@ TX.prototype.witnessHash = function witnessHash(enc) { return this.hash(enc); if (!hash) { - hash = utils.hash256(this.toWitness()); + hash = crypto.hash256(this.toWitness()); if (!this.mutable) this._whash = hash; } @@ -550,7 +551,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { // Append the hash type. p.writeU32(type); - return utils.hash256(p.render()); + return crypto.hash256(p.render()); }; /** @@ -573,7 +574,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { hashPrevouts = new BufferWriter(); for (i = 0; i < this.inputs.length; i++) this.inputs[i].prevout.toRaw(hashPrevouts); - hashPrevouts = utils.hash256(hashPrevouts.render()); + hashPrevouts = crypto.hash256(hashPrevouts.render()); if (!this.mutable) this._hashPrevouts = hashPrevouts; } @@ -590,7 +591,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { hashSequence = new BufferWriter(); for (i = 0; i < this.inputs.length; i++) hashSequence.writeU32(this.inputs[i].sequence); - hashSequence = utils.hash256(hashSequence.render()); + hashSequence = crypto.hash256(hashSequence.render()); if (!this.mutable) this._hashSequence = hashSequence; } @@ -606,13 +607,13 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { hashOutputs = new BufferWriter(); for (i = 0; i < this.outputs.length; i++) this.outputs[i].toRaw(hashOutputs); - hashOutputs = utils.hash256(hashOutputs.render()); + hashOutputs = crypto.hash256(hashOutputs.render()); if (!this.mutable) this._hashOutputs = hashOutputs; } } else if ((type & 0x1f) === constants.hashType.SINGLE && index < this.outputs.length) { hashOutputs = this.outputs[index].toRaw(); - hashOutputs = utils.hash256(hashOutputs); + hashOutputs = crypto.hash256(hashOutputs); } else { hashOutputs = utils.copy(constants.ZERO_HASH); } @@ -629,7 +630,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, type) { p.writeU32(this.locktime); p.writeU32(type); - return utils.hash256(p.render()); + return crypto.hash256(p.render()); }; /** diff --git a/lib/script/script.js b/lib/script/script.js index f73fbcdf..2a02bbe3 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -11,6 +11,7 @@ var bcoin = require('../env'); var bn = require('bn.js'); var constants = bcoin.constants; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var BufferWriter = require('../utils/writer'); var BufferReader = require('../utils/reader'); @@ -780,31 +781,31 @@ Script.prototype.execute = function execute(stack, flags, tx, index, version) { case opcodes.OP_RIPEMD160: { if (stack.length === 0) throw new ScriptError('INVALID_STACK_OPERATION', op, ip); - stack.push(utils.ripemd160(stack.pop())); + stack.push(crypto.ripemd160(stack.pop())); break; } case opcodes.OP_SHA1: { if (stack.length === 0) throw new ScriptError('INVALID_STACK_OPERATION', op, ip); - stack.push(utils.sha1(stack.pop())); + stack.push(crypto.sha1(stack.pop())); break; } case opcodes.OP_SHA256: { if (stack.length === 0) throw new ScriptError('INVALID_STACK_OPERATION', op, ip); - stack.push(utils.sha256(stack.pop())); + stack.push(crypto.sha256(stack.pop())); break; } case opcodes.OP_HASH160: { if (stack.length === 0) throw new ScriptError('INVALID_STACK_OPERATION', op, ip); - stack.push(utils.hash160(stack.pop())); + stack.push(crypto.hash160(stack.pop())); break; } case opcodes.OP_HASH256: { if (stack.length === 0) throw new ScriptError('INVALID_STACK_OPERATION', op, ip); - stack.push(utils.hash256(stack.pop())); + stack.push(crypto.hash256(stack.pop())); break; } case opcodes.OP_CODESEPARATOR: { @@ -1750,7 +1751,7 @@ Script.prototype.getAddress = function getAddress() { */ Script.prototype.hash160 = function hash160(enc) { - var hash = utils.hash160(this.toRaw()); + var hash = crypto.hash160(this.toRaw()); if (enc === 'hex') hash = hash.toString('hex'); return hash; @@ -1762,7 +1763,7 @@ Script.prototype.hash160 = function hash160(enc) { */ Script.prototype.sha256 = function sha256(enc) { - var hash = utils.sha256(this.toRaw()); + var hash = crypto.sha256(this.toRaw()); if (enc === 'hex') hash = hash.toString('hex'); return hash; @@ -1996,7 +1997,7 @@ Script.prototype.forWitness = function() { return this; if (this.isPubkey()) { - hash = utils.hash160(this.get(0)); + hash = crypto.hash160(this.get(0)); return Script.fromProgram(0, hash); } @@ -3237,7 +3238,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) { witnessScript = stack.pop(); - if (!utils.equal(utils.sha256(witnessScript), program.data)) + if (!utils.equal(crypto.sha256(witnessScript), program.data)) throw new ScriptError('WITNESS_PROGRAM_MISMATCH'); redeem = new Script(witnessScript); @@ -3260,7 +3261,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) { witnessScript = stack.pop(); redeem = new Script(witnessScript); - hash = utils.hash256(witnessScript); + hash = crypto.hash256(witnessScript); pathdata = stack.pop(); if (pathdata.length & 0x1f) @@ -3298,7 +3299,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i) { throw new ScriptError('WITNESS_PROGRAM_MISMATCH'); } - root = utils.checkMerkleBranch(hash, path, pos); + root = crypto.checkMerkleBranch(hash, path, pos); if (!utils.equal(root, program.data)) throw new ScriptError('WITNESS_PROGRAM_MISMATCH'); diff --git a/lib/utils/reader.js b/lib/utils/reader.js index 3e880d92..0d7ec221 100644 --- a/lib/utils/reader.js +++ b/lib/utils/reader.js @@ -8,6 +8,7 @@ 'use strict'; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; /** @@ -594,7 +595,7 @@ BufferReader.prototype.readNullString = function readNullString(enc) { BufferReader.prototype.createChecksum = function createChecksum() { var start = this.stack[this.stack.length - 1] || 0; var data = this.data.slice(start, this.offset); - return utils.checksum(data).readUInt32LE(0, true); + return crypto.checksum(data).readUInt32LE(0, true); }; /** diff --git a/lib/utils/utils.js b/lib/utils/utils.js index 7a4c4432..2d3a1b1c 100644 --- a/lib/utils/utils.js +++ b/lib/utils/utils.js @@ -18,9 +18,8 @@ var utils = exports; var assert = require('assert'); var bn = require('bn.js'); var util = require('util'); -var crypto = require('../crypto/crypto'); var Number, Math, Date; -var fs, crypto; +var fs; /** * Reference to the global object. @@ -229,160 +228,6 @@ utils.isBase58 = function isBase58(obj) { return typeof obj === 'string' && /^[1-9a-zA-Z]+$/.test(obj); }; -/** - * @function - * @see crypto.hash - */ - -utils.hash = crypto.hash; - -/** - * @function - * @see crypto.ripemd160 - */ - -utils.ripemd160 = crypto.ripemd160; - -/** - * @function - * @see crypto.ripemd160 - */ - -utils.sha1 = crypto.sha1; - -/** - * @function - * @see crypto.sha256 - */ - -utils.sha256 = crypto.sha256; - -/** - * @function - * @see crypto.hash160 - */ - -utils.hash160 = crypto.hash160; - -/** - * @function - * @see crypto.hash256 - */ - -utils.hash256 = crypto.hash256; - -/** - * @function - * @see crypto.checksum - */ - -utils.checksum = crypto.checksum; - -/** - * @function - * @see crypto.hmac - */ - -utils.hmac = crypto.hmac; - -/** - * @function - * @see crypto.pbkdf2Sync - */ - -utils.pbkdf2Sync = crypto.pbkdf2Sync; - -/** - * @function - * @see crypto.pbkdf2 - */ - -utils.pbkdf2 = crypto.pbkdf2; - -/** - * @function - * @see crypto.derive - */ - -utils.derive = crypto.derive; - -/** - * @function - * @see crypto.encrypt - */ - -utils.encrypt = crypto.encrypt; - -/** - * @function - * @see crypto.encipher - */ - -utils.encipher = crypto.encipher; - -/** - * @function - * @see crypto.decrypt - */ - -utils.decrypt = crypto.decrypt; - -/** - * @function - * @see crypto.decipher - */ - -utils.decipher = crypto.decipher; - -/** - * @function - * @see crypto.hkdfExtract - */ - -utils.hkdfExtract = crypto.hkdfExtract; - -/** - * @function - * @see crypto.hkdfExpand - */ - -utils.hkdfExpand = crypto.hkdfExpand; - -/** - * @function - * @see crypto.ccmp - */ - -utils.ccmp = crypto.ccmp; - -/** - * @function - * @see crypto.buildMerkleTree - */ - -utils.buildMerkleTree = crypto.buildMerkleTree; - -/** - * @function - * @see crypto.getMerkleRoot - */ - -utils.getMerkleRoot = crypto.getMerkleRoot; - -/** - * @function - * @see crypto.getMerkleBranch - */ - -utils.getMerkleBranch = crypto.getMerkleBranch; - -/** - * @function - * @see crypto.checkMerkleBranch - */ - -utils.checkMerkleBranch = crypto.checkMerkleBranch; - /** * Return hrtime (shim for browser). * @param {Array} time diff --git a/lib/utils/writer.js b/lib/utils/writer.js index df4decf4..381c1e9d 100644 --- a/lib/utils/writer.js +++ b/lib/utils/writer.js @@ -8,6 +8,7 @@ 'use strict'; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; /* @@ -104,7 +105,7 @@ BufferWriter.prototype.render = function render(keep) { case BYTES: off += item[1].copy(data, off); break; case STR: off += data.write(item[1], off, item[2]); break; case CHECKSUM: - off += utils.checksum(data.slice(0, off)).copy(data, off); + off += crypto.checksum(data.slice(0, off)).copy(data, off); break; case FILL: data.fill(item[1], off, off + item[2]); diff --git a/lib/wallet/wallet.js b/lib/wallet/wallet.js index 71a18ccc..69cfb472 100644 --- a/lib/wallet/wallet.js +++ b/lib/wallet/wallet.js @@ -11,6 +11,7 @@ var bcoin = require('../env'); var EventEmitter = require('events').EventEmitter; var constants = bcoin.constants; var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var BufferReader = require('../utils/reader'); var BufferWriter = require('../utils/writer'); @@ -451,7 +452,7 @@ Wallet.prototype.getID = function getID() { p.writeBytes(key.publicKey); p.writeU32(this.network.magic); - hash = utils.hash160(p.render()); + hash = crypto.hash160(p.render()); p = new BufferWriter(); p.writeU8(0x03); @@ -483,7 +484,7 @@ Wallet.prototype.getToken = function getToken(master, nonce) { p.writeBytes(key.privateKey); p.writeU32(nonce); - return utils.hash256(p.render()); + return crypto.hash256(p.render()); }; /** @@ -2220,7 +2221,7 @@ MasterKey.prototype.unlock = function unlock(passphrase, timeout, callback) { assert(this.encrypted); - utils.decrypt(this.ciphertext, passphrase, this.iv, function(err, data, key) { + crypto.decrypt(this.ciphertext, passphrase, this.iv, function(err, data, key) { if (err) return callback(err); @@ -2277,7 +2278,7 @@ MasterKey.prototype.encipher = function encipher(data, iv) { if (typeof iv === 'string') iv = new Buffer(iv, 'hex'); - return utils.encipher(data, this.aesKey, iv.slice(0, 16)); + return crypto.encipher(data, this.aesKey, iv.slice(0, 16)); }; MasterKey.prototype.decipher = function decipher(data, iv) { @@ -2287,7 +2288,7 @@ MasterKey.prototype.decipher = function decipher(data, iv) { if (typeof iv === 'string') iv = new Buffer(iv, 'hex'); - return utils.decipher(data, this.aesKey, iv.slice(0, 16)); + return crypto.decipher(data, this.aesKey, iv.slice(0, 16)); }; /** @@ -2340,7 +2341,7 @@ MasterKey.prototype.decrypt = function decrypt(passphrase, callback) { this.destroy(); - utils.decrypt(this.ciphertext, passphrase, this.iv, function(err, data) { + crypto.decrypt(this.ciphertext, passphrase, this.iv, function(err, data) { if (err) return callback(err); @@ -2384,7 +2385,7 @@ MasterKey.prototype.encrypt = function encrypt(passphrase, callback) { this.stop(); - utils.encrypt(data, passphrase, iv, function(err, data) { + crypto.encrypt(data, passphrase, iv, function(err, data) { if (err) return callback(err); diff --git a/lib/wallet/walletdb.js b/lib/wallet/walletdb.js index 216d7ca0..74b9e991 100644 --- a/lib/wallet/walletdb.js +++ b/lib/wallet/walletdb.js @@ -10,6 +10,7 @@ var bcoin = require('../env'); var AsyncObject = require('../utils/async'); var utils = require('../utils/utils'); +var crypto = require('../crypto/crypto'); var assert = utils.assert; var constants = bcoin.constants; var BufferReader = require('../utils/reader'); @@ -592,7 +593,7 @@ WalletDB.prototype.auth = function auth(wid, token, callback) { } // Compare in constant time: - if (!utils.ccmp(token, wallet.token)) + if (!crypto.ccmp(token, wallet.token)) return callback(new Error('Authentication error.')); callback(null, wallet); diff --git a/test/aes-test.js b/test/aes-test.js index 831a5e17..21d62eab 100644 --- a/test/aes-test.js +++ b/test/aes-test.js @@ -2,13 +2,14 @@ var bn = require('bn.js'); var utils = require('../lib/utils/utils'); +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var aes = require('../lib/crypto/aes'); -var crypto = require('crypto'); +var nativeCrypto = require('crypto'); describe('AES', function() { function pbkdf2key(passphrase, iterations, dkLen, ivLen, alg) { - var key = utils.pbkdf2Sync(passphrase, '', iterations, dkLen + ivLen, 'sha512'); + var key = crypto.pbkdf2Sync(passphrase, '', iterations, dkLen + ivLen, 'sha512'); return { key: key.slice(0, dkLen), iv: key.slice(dkLen, dkLen + ivLen) @@ -18,7 +19,7 @@ describe('AES', function() { function nencrypt(data, passphrase) { var key, cipher; - assert(crypto, 'No crypto module available.'); + assert(nativeCrypto, 'No crypto module available.'); assert(passphrase, 'No passphrase.'); if (typeof data === 'string') @@ -28,7 +29,7 @@ describe('AES', function() { passphrase = new Buffer(passphrase, 'utf8'); key = pbkdf2key(passphrase, 2048, 32, 16); - cipher = crypto.createCipheriv('aes-256-cbc', key.key, key.iv); + cipher = nativeCrypto.createCipheriv('aes-256-cbc', key.key, key.iv); return Buffer.concat([ cipher.update(data), @@ -39,7 +40,7 @@ describe('AES', function() { function ndecrypt(data, passphrase) { var key, decipher; - assert(crypto, 'No crypto module available.'); + assert(nativeCrypto, 'No crypto module available.'); assert(passphrase, 'No passphrase.'); if (typeof data === 'string') @@ -49,7 +50,7 @@ describe('AES', function() { passphrase = new Buffer(passphrase, 'utf8'); key = pbkdf2key(passphrase, 2048, 32, 16); - decipher = crypto.createDecipheriv('aes-256-cbc', key.key, key.iv); + decipher = nativeCrypto.createDecipheriv('aes-256-cbc', key.key, key.iv); return Buffer.concat([ decipher.update(data), @@ -60,7 +61,7 @@ describe('AES', function() { function encrypt(data, passphrase) { var key, cipher; - assert(crypto, 'No crypto module available.'); + assert(nativeCrypto, 'No crypto module available.'); assert(passphrase, 'No passphrase.'); if (typeof data === 'string') @@ -77,7 +78,7 @@ describe('AES', function() { function decrypt(data, passphrase) { var key, decipher; - assert(crypto, 'No crypto module available.'); + assert(nativeCrypto, 'No crypto module available.'); assert(passphrase, 'No passphrase.'); if (typeof data === 'string') @@ -92,11 +93,11 @@ describe('AES', function() { } it('should encrypt and decrypt a hash with 2 blocks', function() { - var hash = utils.sha256(new Buffer([])); + var hash = crypto.sha256(new Buffer([])); var enchash = encrypt(hash, 'foo'); var dechash = decrypt(enchash, 'foo'); - var hash2 = utils.sha256(new Buffer([])); + var hash2 = crypto.sha256(new Buffer([])); var enchash2 = nencrypt(hash2, 'foo'); var dechash2 = ndecrypt(enchash2, 'foo'); @@ -106,11 +107,11 @@ describe('AES', function() { }); it('should encrypt and decrypt a hash with uneven blocks', function() { - var hash = Buffer.concat([utils.sha256(new Buffer([])), new Buffer([1,2,3])]); + var hash = Buffer.concat([crypto.sha256(new Buffer([])), new Buffer([1,2,3])]); var enchash = encrypt(hash, 'foo'); var dechash = decrypt(enchash, 'foo'); - var hash2 = Buffer.concat([utils.sha256(new Buffer([])), new Buffer([1,2,3])]); + var hash2 = Buffer.concat([crypto.sha256(new Buffer([])), new Buffer([1,2,3])]); var enchash2 = nencrypt(hash2, 'foo'); var dechash2 = ndecrypt(enchash2, 'foo'); diff --git a/test/bip150-test.js b/test/bip150-test.js index d2124259..f0db4143 100644 --- a/test/bip150-test.js +++ b/test/bip150-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var network = bcoin.networks; var assert = require('assert'); diff --git a/test/bip151-test.js b/test/bip151-test.js index dbda5ac0..b8589cb5 100644 --- a/test/bip151-test.js +++ b/test/bip151-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var network = bcoin.networks; var assert = require('assert'); diff --git a/test/bip70-test.js b/test/bip70-test.js index cbc2ee16..1737c014 100644 --- a/test/bip70-test.js +++ b/test/bip70-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var network = bcoin.networks; var assert = require('assert'); diff --git a/test/block-test.js b/test/block-test.js index f665e8ff..125294f0 100644 --- a/test/block-test.js +++ b/test/block-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var network = bcoin.networks; var assert = require('assert'); diff --git a/test/bloom-test.js b/test/bloom-test.js index 0a3eb179..679862b8 100644 --- a/test/bloom-test.js +++ b/test/bloom-test.js @@ -2,6 +2,7 @@ var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var assert = require('assert'); diff --git a/test/chain-test.js b/test/chain-test.js index 9d765704..c01fa0de 100644 --- a/test/chain-test.js +++ b/test/chain-test.js @@ -4,6 +4,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('regtest'); var constants = bcoin.constants; var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var opcodes = constants.opcodes; diff --git a/test/hd-test.js b/test/hd-test.js index fa8282e8..89e0e72a 100644 --- a/test/hd-test.js +++ b/test/hd-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki @@ -90,7 +91,7 @@ describe('HD', function() { var master, child1, child2, child3, child4, child5, child6; it('should create a pbkdf2 seed', function() { - var checkSeed = bcoin.utils.pbkdf2Sync( + var checkSeed = crypto.pbkdf2Sync( phrase, 'mnemonic' + 'foo', 2048, 64, 'sha512').toString('hex'); assert.equal(checkSeed, seed); }); diff --git a/test/http-test.js b/test/http-test.js index eac59cf7..0c316178 100644 --- a/test/http-test.js +++ b/test/http-test.js @@ -5,6 +5,7 @@ var bcoin = require('../').set('regtest'); var constants = bcoin.constants; var network = bcoin.networks; var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var scriptTypes = constants.scriptTypes; diff --git a/test/mempool-test.js b/test/mempool-test.js index c3a9ce86..d4412d52 100644 --- a/test/mempool-test.js +++ b/test/mempool-test.js @@ -4,6 +4,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var constants = bcoin.constants; var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var opcodes = constants.opcodes; @@ -167,7 +168,7 @@ describe('Mempool', function() { // Coinbase var t1 = bcoin.mtx().addOutput(w, 50000).addOutput(w, 10000); // 10000 instead of 1000 var prev = new bcoin.script([kp.publicKey, opcodes.OP_CHECKSIG]); - var prevHash = bcoin.ec.random(32).toString('hex'); + var prevHash = crypto.randomBytes(32).toString('hex'); var dummyInput = { prevout: { hash: prevHash, @@ -202,7 +203,7 @@ describe('Mempool', function() { // Coinbase var t1 = bcoin.mtx().addOutput(w, 50000).addOutput(w, 10000); // 10000 instead of 1000 var prev = new bcoin.script([kp.publicKey, opcodes.OP_CHECKSIG]); - var prevHash = bcoin.ec.random(32).toString('hex'); + var prevHash = crypto.randomBytes(32).toString('hex'); var dummyInput = { prevout: { hash: prevHash, diff --git a/test/mnemonic-test.js b/test/mnemonic-test.js index 4b0bd236..8d2720cb 100644 --- a/test/mnemonic-test.js +++ b/test/mnemonic-test.js @@ -3,6 +3,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var mnemonic1 = require('./data/mnemonic1').english; var mnemonic2 = require('./data/mnemonic2'); diff --git a/test/protocol-test.js b/test/protocol-test.js index 8bb0e3f1..a98aeab7 100644 --- a/test/protocol-test.js +++ b/test/protocol-test.js @@ -5,6 +5,7 @@ var assert = require('assert'); var constants = bcoin.constants; var network = bcoin.network.get(); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var fs = require('fs'); var alertData = fs.readFileSync(__dirname + '/data/alertTests.raw'); var NetworkAddress = bcoin.packets.NetworkAddress; diff --git a/test/script-test.js b/test/script-test.js index b0e0d93b..e7955faa 100644 --- a/test/script-test.js +++ b/test/script-test.js @@ -5,6 +5,7 @@ var assert = require('assert'); var Script = bcoin.script; var Stack = bcoin.stack; var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var opcodes = bcoin.constants.opcodes; var scripts = require('./data/script_tests'); diff --git a/test/tx-test.js b/test/tx-test.js index f38d1603..0c98e92b 100644 --- a/test/tx-test.js +++ b/test/tx-test.js @@ -4,6 +4,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var assert = require('assert'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var constants = bcoin.constants; var opcodes = bcoin.constants.opcodes; var valid = require('./data/tx_valid.json'); @@ -305,7 +306,7 @@ describe('TX', function() { }); function createInput(value) { - var hash = bcoin.ec.random(32).toString('hex'); + var hash = crypto.randomBytes(32).toString('hex'); return { prevout: { hash: hash, diff --git a/test/utils-test.js b/test/utils-test.js index e1ca035e..6742d604 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -4,6 +4,7 @@ var bn = require('bn.js'); var bcoin = require('../').set('main'); var assert = require('assert'); var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var schnorr = require('../lib/crypto/schnorr'); describe('Utils', function() { @@ -243,8 +244,8 @@ describe('Utils', function() { salt = new Buffer(salt, 'hex'); info = new Buffer(info, 'hex'); - var prk = utils.hkdfExtract(ikm, salt, 'sha256'); - var okm = utils.hkdfExpand(prk, info, len, 'sha256'); + var prk = crypto.hkdfExtract(ikm, salt, 'sha256'); + var okm = crypto.hkdfExpand(prk, info, len, 'sha256'); assert.equal(prk.toString('hex'), prkE); assert.equal(okm.toString('hex'), okmE); @@ -285,8 +286,8 @@ describe('Utils', function() { salt = new Buffer(salt, 'hex'); info = new Buffer(info, 'hex'); - var prk = utils.hkdfExtract(ikm, salt, 'sha256'); - var okm = utils.hkdfExpand(prk, info, len, 'sha256'); + var prk = crypto.hkdfExtract(ikm, salt, 'sha256'); + var okm = crypto.hkdfExpand(prk, info, len, 'sha256'); assert.equal(prk.toString('hex'), prkE); assert.equal(okm.toString('hex'), okmE); @@ -295,7 +296,7 @@ describe('Utils', function() { it('should do proper schnorr', function() { var key = bcoin.ec.generatePrivateKey(); var pub = bcoin.ec.publicKeyCreate(key, true); - var msg = utils.hash256(new Buffer('foo', 'ascii')); + var msg = crypto.hash256(new Buffer('foo', 'ascii')); var sig = schnorr.sign(msg, key); assert(schnorr.verify(msg, sig, pub)); assert.deepEqual(schnorr.recover(sig, msg), pub); diff --git a/test/wallet-test.js b/test/wallet-test.js index 1a49ed28..be153334 100644 --- a/test/wallet-test.js +++ b/test/wallet-test.js @@ -5,6 +5,7 @@ var bcoin = require('../').set('main'); var constants = bcoin.constants; var network = bcoin.networks; var utils = bcoin.utils; +var crypto = require('../lib/crypto/crypto'); var assert = require('assert'); var scriptTypes = constants.scriptTypes;