From e00472891df5934d8fc3aa63662f852816aa86b0 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 29 Jun 2017 04:30:14 -0700 Subject: [PATCH] refactor: start using for...of. --- bin/cli | 5 +- lib/bip70/payment.js | 19 +-- lib/bip70/paymentdetails.js | 11 +- lib/bip70/x509.js | 34 ++-- lib/blockchain/chain.js | 44 ++--- lib/blockchain/chaindb.js | 145 +++++++--------- lib/btc/uri.js | 5 +- lib/coins/coins.js | 7 +- lib/coins/coinview.js | 35 ++-- lib/coins/undocoins.js | 12 +- lib/db/level.js | 5 +- lib/db/memdb.js | 10 +- lib/hd/common.js | 5 +- lib/hd/mnemonic.js | 5 +- lib/hd/private.js | 6 +- lib/hd/public.js | 6 +- lib/http/base.js | 33 ++-- lib/http/rpc.js | 95 ++++------- lib/http/rpcbase.js | 11 +- lib/http/server.js | 42 ++--- lib/mempool/fees.js | 6 +- lib/mempool/mempool.js | 171 ++++++++----------- lib/mempool/mempoolentry.js | 21 +-- lib/mining/miner.js | 18 +- lib/mining/template.js | 29 ++-- lib/net/bip150.js | 40 ++--- lib/net/bip152.js | 34 ++-- lib/net/dns.js | 6 +- lib/net/hostlist.js | 35 ++-- lib/net/packets.js | 30 ++-- lib/net/peer.js | 59 +++---- lib/net/pool.js | 94 ++++------ lib/net/proxysocket.js | 11 +- lib/net/socks.js | 6 +- lib/net/upnp.js | 45 ++--- lib/node/config.js | 39 ++--- lib/node/fullnode.js | 37 ++-- lib/node/node.js | 22 +-- lib/primitives/abstractblock.js | 6 +- lib/primitives/block.js | 23 +-- lib/primitives/merkleblock.js | 31 ++-- lib/primitives/mtx.js | 47 +++-- lib/primitives/tx.js | 294 ++++++++++++-------------------- lib/protocol/network.js | 14 +- lib/protocol/timedata.js | 5 +- lib/script/common.js | 21 +-- lib/script/script.js | 74 +++----- lib/script/witness.js | 28 ++- lib/utils/asyncemitter.js | 6 +- lib/utils/asyncobject.js | 10 +- lib/utils/fs.js | 12 +- lib/utils/gcs.js | 42 ++--- lib/utils/ip.js | 17 +- lib/utils/lock.js | 6 +- lib/utils/lru.js | 5 +- lib/utils/util.js | 40 ++--- lib/utils/validator.js | 20 +-- lib/utils/writer.js | 5 +- lib/wallet/account.js | 17 +- lib/wallet/client.js | 11 +- lib/wallet/common.js | 26 +-- lib/wallet/http.js | 58 +++---- lib/wallet/records.js | 16 +- lib/wallet/rpc.js | 124 +++++--------- lib/wallet/txdb.js | 164 ++++++------------ lib/wallet/wallet.js | 69 +++----- lib/wallet/walletdb.js | 75 ++++---- lib/workers/packets.js | 17 +- lib/workers/workerpool.js | 12 +- 69 files changed, 958 insertions(+), 1575 deletions(-) diff --git a/bin/cli b/bin/cli index 7ae5859a..0ec3bef4 100755 --- a/bin/cli +++ b/bin/cli @@ -454,10 +454,9 @@ CLI.prototype.unlock = async function unlock() { CLI.prototype.rpc = async function rpc() { var method = this.argv.shift(); var params = []; - var i, arg, param, result; + var arg, param, result; - for (i = 0; i < this.argv.length; i++) { - arg = this.argv[i]; + for (arg of this.argv) { try { param = JSON.parse(arg); } catch (e) { diff --git a/lib/bip70/payment.js b/lib/bip70/payment.js index e7ec56d5..77f1b3b8 100644 --- a/lib/bip70/payment.js +++ b/lib/bip70/payment.js @@ -46,23 +46,23 @@ function Payment(options) { */ Payment.prototype.fromOptions = function fromOptions(options) { - var i, tx, output; + var item, tx, output; if (options.merchantData) this.setData(options.merchantData); if (options.transactions) { assert(Array.isArray(options.transactions)); - for (i = 0; i < options.transactions.length; i++) { - tx = new TX(options.transactions[i]); + for (item of options.transactions) { + tx = new TX(item); this.transactions.push(tx); } } if (options.refundTo) { assert(Array.isArray(options.refundTo)); - for (i = 0; i < options.refundTo.length; i++) { - output = new Output(options.refundTo[i]); + for (item of options.refundTo) { + output = new Output(item); this.refundTo.push(output); } } @@ -155,19 +155,16 @@ Payment.fromRaw = function fromRaw(data, enc) { Payment.prototype.toRaw = function toRaw() { var bw = new ProtoWriter(); - var i, tx, op, output; + var tx, op, output; if (this.merchantData) bw.writeFieldBytes(1, this.merchantData); - for (i = 0; i < this.transactions.length; i++) { - tx = this.transactions[i]; + for (tx of this.transactions) bw.writeFieldBytes(2, tx.toRaw()); - } - for (i = 0; i < this.refundTo.length; i++) { + for (output of this.refundTo) { op = new ProtoWriter(); - output = this.refundTo[i]; op.writeFieldU64(1, output.value); op.writeFieldBytes(2, output.script.toRaw()); bw.writeFieldBytes(3, op.render()); diff --git a/lib/bip70/paymentdetails.js b/lib/bip70/paymentdetails.js index 13dab8d5..63fb4aa5 100644 --- a/lib/bip70/paymentdetails.js +++ b/lib/bip70/paymentdetails.js @@ -50,7 +50,7 @@ function PaymentDetails(options) { */ PaymentDetails.prototype.fromOptions = function fromOptions(options) { - var i, output; + var item, output; if (options.network != null) { assert(typeof options.network === 'string'); @@ -59,8 +59,8 @@ PaymentDetails.prototype.fromOptions = function fromOptions(options) { if (options.outputs) { assert(Array.isArray(options.outputs)); - for (i = 0; i < options.outputs.length; i++) { - output = new Output(options.outputs[i]); + for (item of options.outputs) { + output = new Output(item); this.outputs.push(output); } } @@ -210,13 +210,12 @@ PaymentDetails.fromRaw = function fromRaw(data, enc) { PaymentDetails.prototype.toRaw = function toRaw() { var bw = new ProtoWriter(); - var i, op, output; + var op, output; if (this.network != null) bw.writeFieldString(1, this.network); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) { op = new ProtoWriter(); op.writeFieldU64(1, output.value); op.writeFieldBytes(2, output.script.toRaw()); diff --git a/lib/bip70/x509.js b/lib/bip70/x509.js index 064478d6..0f9e80ae 100644 --- a/lib/bip70/x509.js +++ b/lib/bip70/x509.js @@ -87,10 +87,9 @@ x509.curves = { x509.getSubjectOID = function getSubjectOID(cert, oid) { var subject = cert.tbs.subject; - var i, entry; + var entry; - for (i = 0; i < subject.length; i++) { - entry = subject[i]; + for (entry of subject) { if (entry.type === oid) return entry.value; } @@ -138,13 +137,11 @@ x509.isTrusted = function isTrusted(cert) { */ x509.setTrust = function setTrust(certs) { - var i, cert, pem, hash; + var cert, pem, hash; assert(Array.isArray(certs), 'Certs must be an array.'); - for (i = 0; i < certs.length; i++) { - cert = certs[i]; - + for (cert of certs) { if (typeof cert === 'string') { pem = PEM.decode(cert); assert(pem.type === 'certificate', 'Must add certificates to trust.'); @@ -168,13 +165,11 @@ x509.setTrust = function setTrust(certs) { */ x509.setFingerprints = function setFingerprints(hashes) { - var i, hash; + var hash; assert(Array.isArray(hashes), 'Certs must be an array.'); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; - + for (hash of hashes) { if (typeof hash === 'string') hash = Buffer.from(hash, 'hex'); @@ -392,10 +387,10 @@ x509.verifySubject = function verifySubject(hash, msg, sig, chain) { x509.parseChain = function parseChain(chain) { var certs = []; - var i, cert; + var item, cert; - for (i = 0; i < chain.length; i++) { - cert = x509.parse(chain[i]); + for (item of chain) { + cert = x509.parse(item); certs.push(cert); } @@ -409,10 +404,9 @@ x509.parseChain = function parseChain(chain) { */ x509.verifyTimes = function verifyTimes(chain) { - var i, cert; + var cert; - for (i = 0; i < chain.length; i++) { - cert = chain[i]; + for (cert of chain) { if (!x509.verifyTime(cert)) return false; } @@ -428,7 +422,7 @@ x509.verifyTimes = function verifyTimes(chain) { */ x509.verifyTrust = function verifyTrust(chain) { - var i, cert; + var cert; // If trust hasn't been // setup, just return. @@ -437,9 +431,7 @@ x509.verifyTrust = function verifyTrust(chain) { // Make sure we trust one // of the certs in the chain. - for (i = 0; i < chain.length; i++) { - cert = chain[i]; - + for (cert of chain) { // If any certificate in the chain // is trusted, assume we also trust // the parent. diff --git a/lib/blockchain/chain.js b/lib/blockchain/chain.js index 8367d77f..e304f6b3 100644 --- a/lib/blockchain/chain.js +++ b/lib/blockchain/chain.js @@ -221,7 +221,7 @@ Chain.prototype.verify = async function verify(block, prev, flags) { var hash = block.hash('hex'); var now = this.network.now(); var height = prev.height + 1; - var i, ts, tx, mtp; + var ts, tx, mtp; var valid, reason, score, commit, state, bits; assert(typeof flags === 'number'); @@ -320,9 +320,7 @@ Chain.prototype.verify = async function verify(block, prev, flags) { // Transactions must be finalized with // regards to nSequence and nLockTime. - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; - + for (tx of block.txs) { if (!tx.isFinal(height, ts)) { throw new VerifyError(block, 'invalid', @@ -492,7 +490,7 @@ Chain.prototype.setDeploymentState = function setDeploymentState(state) { Chain.prototype.verifyDuplicates = async function verifyDuplicates(block, prev, state) { var height = prev.height + 1; - var i, tx, result; + var tx, result; if (this.options.spv) return; @@ -506,8 +504,7 @@ Chain.prototype.verifyDuplicates = async function verifyDuplicates(block, prev, return; // Check all transactions. - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + for (tx of block.txs) { result = await this.db.hasCoins(tx.hash()); if (result) { @@ -549,17 +546,15 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { var sigops = 0; var reward = 0; var jobs = []; - var i, tx, valid, reason, score, fee; + var tx, valid, reason, score, fee; if (this.options.spv) return view; // Check all transactions - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; - + for (tx of block.txs) { // Ensure tx is not double spending an output. - if (i > 0) { + if (!tx.isCoinbase()) { if (!(await view.spendInputs(this.db, tx))) { assert(!historical, 'BUG: Spent inputs in historical data!'); throw new VerifyError(block, @@ -577,7 +572,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { } // Verify sequence locks. - if (i > 0 && tx.version >= 2) { + if (!tx.isCoinbase() && tx.version >= 2) { valid = await this.verifyLocks(prev, tx, view, state.lockFlags); if (!valid) { @@ -599,7 +594,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { } // Contextual sanity checks. - if (i > 0) { + if (!tx.isCoinbase()) { [fee, reason, score] = tx.checkContext(view, height); if (fee === -1) { @@ -773,7 +768,7 @@ Chain.prototype.reorganizeSPV = async function reorganizeSPV(competitor, block) var fork = await this.findFork(tip, competitor); var disconnect = []; var entry = tip; - var i, headers, view; + var headers, view; assert(fork, 'No free space or data corruption.'); @@ -792,8 +787,7 @@ Chain.prototype.reorganizeSPV = async function reorganizeSPV(competitor, block) // Emit disconnection events now that // the chain has successfully reset. - for (i = 0; i < disconnect.length; i++) { - entry = disconnect[i]; + for (entry of disconnect) { headers = entry.toHeaders(); view = new CoinView(); await this.fire('disconnect', entry, headers, view); @@ -2041,10 +2035,9 @@ Chain.prototype.retarget = function retarget(prev, first) { */ Chain.prototype.findLocator = async function findLocator(locator) { - var i, hash; + var hash; - for (i = 0; i < locator.length; i++) { - hash = locator[i]; + for (hash of locator) { if (await this.db.isMainChain(hash)) return hash; } @@ -2194,10 +2187,9 @@ Chain.prototype.getState = async function getState(prev, deployment) { Chain.prototype.computeBlockVersion = async function computeBlockVersion(prev) { var version = 0; - var i, deployment, state; + var deployment, state; - for (i = 0; i < this.network.deploys.length; i++) { - deployment = this.network.deploys[i]; + for (deployment of this.network.deploys) { state = await this.getState(prev, deployment); if (state === common.thresholdStates.LOCKED_IN @@ -2279,14 +2271,12 @@ Chain.prototype.getLocks = async function getLocks(prev, tx, view, flags) { var minHeight = -1; var minTime = -1; var coinHeight, coinTime; - var i, input, entry; + var input, entry; if (tx.isCoinbase() || tx.version < 2 || !hasFlag) return [minHeight, minTime]; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; - + for (input of tx.inputs) { if (input.sequence & disableFlag) continue; diff --git a/lib/blockchain/chaindb.js b/lib/blockchain/chaindb.js index b86bd0a6..d64698ce 100644 --- a/lib/blockchain/chaindb.js +++ b/lib/blockchain/chaindb.js @@ -557,7 +557,7 @@ ChainDB.prototype.verifyFlags = async function verifyFlags(state) { ChainDB.prototype.getStateCache = async function getStateCache() { var stateCache = new StateCache(this.network); - var i, items, item, key, bit, hash, state; + var items, item, key, bit, hash, state; items = await this.db.range({ gte: layout.v(0, encoding.ZERO_HASH), @@ -565,8 +565,7 @@ ChainDB.prototype.getStateCache = async function getStateCache() { values: true }); - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { key = layout.vv(item.key); bit = key[0]; hash = key[1]; @@ -595,12 +594,11 @@ ChainDB.prototype.saveDeployments = function saveDeployments() { ChainDB.prototype.writeDeployments = function writeDeployments(batch) { var bw = new StaticWriter(1 + 9 * this.network.deploys.length); - var i, deployment; + var deployment; bw.writeU8(this.network.deploys.length); - for (i = 0; i < this.network.deploys.length; i++) { - deployment = this.network.deploys[i]; + for (deployment of this.network.deploys) { bw.writeU8(deployment.bit); bw.writeU32(deployment.startTime); bw.writeU32(deployment.timeout); @@ -654,15 +652,14 @@ ChainDB.prototype.checkDeployments = async function checkDeployments() { ChainDB.prototype.verifyDeployments = async function verifyDeployments() { var invalid = await this.checkDeployments(); - var i, bit, batch; + var bit, batch; if (invalid.length === 0) return true; batch = this.db.batch(); - for (i = 0; i < invalid.length; i++) { - bit = invalid[i]; + for (bit of invalid) { this.logger.warning('Versionbit deployment params modified.'); this.logger.warning('Invalidating cache for bit %d.', bit); await this.invalidateCache(bit, batch); @@ -683,17 +680,15 @@ ChainDB.prototype.verifyDeployments = async function verifyDeployments() { */ ChainDB.prototype.invalidateCache = async function invalidateCache(bit, batch) { - var i, keys, key; + var keys, key; keys = await this.db.keys({ gte: layout.v(bit, encoding.ZERO_HASH), lte: layout.v(bit, encoding.MAX_HASH) }); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) batch.del(key); - } }; /** @@ -907,10 +902,9 @@ ChainDB.prototype.hasCoins = function hasCoins(hash) { ChainDB.prototype.getCoinView = async function getCoinView(tx) { var view = new CoinView(); var prevout = tx.getPrevout(); - var i, hash, coins; + var hash, coins; - for (i = 0; i < prevout.length; i++) { - hash = prevout[i]; + for (hash of prevout) { coins = await this.getCoins(hash); if (!coins) { @@ -1096,23 +1090,22 @@ ChainDB.prototype.hasTX = function hasTX(hash) { /** * Get all coins pertinent to an address. * @method - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {Promise} - Returns {@link Coin}[]. */ -ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addresses) { +ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { var coins = []; - var i, j, address, hash, keys, key, coin; + var addr, hash, keys, key, coin; if (!this.options.indexAddress) return coins; - if (!Array.isArray(addresses)) - addresses = [addresses]; + if (!Array.isArray(addrs)) + addrs = [addrs]; - for (i = 0; i < addresses.length; i++) { - address = addresses[i]; - hash = Address.getHash(address); + for (addr of addrs) { + hash = Address.getHash(addr); keys = await this.db.keys({ gte: layout.C(hash, encoding.ZERO_HASH, 0), @@ -1120,8 +1113,7 @@ ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addresses parse: layout.Cc }); - for (j = 0; j < keys.length; j++) { - key = keys[j]; + for (key of keys) { coin = await this.getCoin(key[0], key[1]); assert(coin); coins.push(coin); @@ -1134,20 +1126,19 @@ ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addresses /** * Get all transaction hashes to an address. * @method - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {Promise} - Returns {@link Hash}[]. */ -ChainDB.prototype.getHashesByAddress = async function getHashesByAddress(addresses) { +ChainDB.prototype.getHashesByAddress = async function getHashesByAddress(addrs) { var hashes = {}; - var i, address, hash; + var addr, hash; if (!this.options.indexTX || !this.options.indexAddress) return []; - for (i = 0; i < addresses.length; i++) { - address = addresses[i]; - hash = Address.getHash(address); + for (addr of addrs) { + hash = Address.getHash(addr); await this.db.keys({ gte: layout.T(hash, encoding.ZERO_HASH), @@ -1165,19 +1156,17 @@ ChainDB.prototype.getHashesByAddress = async function getHashesByAddress(address /** * Get all transactions pertinent to an address. * @method - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {Promise} - Returns {@link TX}[]. */ -ChainDB.prototype.getTXByAddress = async function getTXByAddress(addresses) { - var mtxs = await this.getMetaByAddress(addresses); +ChainDB.prototype.getTXByAddress = async function getTXByAddress(addrs) { + var mtxs = await this.getMetaByAddress(addrs); var out = []; - var i, mtx; + var mtx; - for (i = 0; i < mtxs.length; i++) { - mtx = mtxs[i]; + for (mtx of mtxs) out.push(mtx.tx); - } return out; }; @@ -1185,24 +1174,23 @@ ChainDB.prototype.getTXByAddress = async function getTXByAddress(addresses) { /** * Get all transactions pertinent to an address. * @method - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {Promise} - Returns {@link TXMeta}[]. */ -ChainDB.prototype.getMetaByAddress = async function getTXByAddress(addresses) { +ChainDB.prototype.getMetaByAddress = async function getTXByAddress(addrs) { var txs = []; - var i, hashes, hash, tx; + var hashes, hash, tx; if (!this.options.indexTX || !this.options.indexAddress) return txs; - if (!Array.isArray(addresses)) - addresses = [addresses]; + if (!Array.isArray(addrs)) + addrs = [addrs]; - hashes = await this.getHashesByAddress(addresses); + hashes = await this.getHashesByAddress(addrs); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { tx = await this.getMeta(hash); assert(tx); txs.push(tx); @@ -1222,7 +1210,7 @@ ChainDB.prototype.getMetaByAddress = async function getTXByAddress(addresses) { ChainDB.prototype.scan = async function scan(start, filter, iter) { var total = 0; - var i, j, entry, hash, tx, txs, block; + var i, entry, hash, tx, txs, block; var found, input, output, prevout; if (start == null) @@ -1258,19 +1246,18 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) { 'Scanning block %s (%d).', entry.rhash(), entry.height); - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + for (tx of block.txs) { found = false; - for (j = 0; j < tx.outputs.length; j++) { - output = tx.outputs[j]; + for (i = 0; i < tx.outputs.length; i++) { + output = tx.outputs[i]; hash = output.getHash(); if (!hash) continue; if (filter.test(hash)) { - prevout = Outpoint.fromTX(tx, j); + prevout = Outpoint.fromTX(tx, i); filter.add(prevout.toRaw()); found = true; } @@ -1281,11 +1268,10 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) { continue; } - if (i === 0) + if (tx.isCoinbase()) continue; - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + for (input of tx.inputs) { prevout = input.prevout; if (filter.test(prevout.toRaw())) { @@ -1489,17 +1475,15 @@ ChainDB.prototype._disconnect = async function disconnect(entry, block) { ChainDB.prototype.saveUpdates = function saveUpdates() { var updates = this.stateCache.updates; - var i, update; + var update; if (updates.length === 0) return; this.logger.info('Saving %d state cache updates.', updates.length); - for (i = 0; i < updates.length; i++) { - update = updates[i]; + for (update of updates) this.put(layout.v(update.bit, update.hash), update.toRaw()); - } }; /** @@ -1589,15 +1573,15 @@ ChainDB.prototype.reset = async function reset(block) { ChainDB.prototype.removeChains = async function removeChains() { var tips = await this.getTips(); - var i; + var tip; // Note that this has to be // one giant atomic write! this.start(); try { - for (i = 0; i < tips.length; i++) - await this._removeChain(tips[i]); + for (tip of tips) + await this._removeChain(tip); } catch (e) { this.drop(); throw e; @@ -1725,7 +1709,7 @@ ChainDB.prototype.saveView = function saveView(view) { ChainDB.prototype.connectBlock = async function connectBlock(entry, block, view) { var hash = block.hash(); - var i, j, tx, input, output; + var i, tx, input, output; if (this.options.spv) return; @@ -1740,16 +1724,12 @@ ChainDB.prototype.connectBlock = async function connectBlock(entry, block, view) for (i = 0; i < block.txs.length; i++) { tx = block.txs[i]; - if (i > 0) { - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + if (!tx.isCoinbase()) { + for (input of tx.inputs) this.pending.spend(view.getOutput(input)); - } } - for (j = 0; j < tx.outputs.length; j++) { - output = tx.outputs[j]; - + for (output of tx.outputs) { if (output.script.isUnspendable()) continue; @@ -1795,7 +1775,7 @@ ChainDB.prototype.disconnectBlock = async function disconnectBlock(entry, block) for (i = block.txs.length - 1; i >= 0; i--) { tx = block.txs[i]; - if (i > 0) { + if (!tx.isCoinbase()) { await view.ensureInputs(this, tx); for (j = tx.inputs.length - 1; j >= 0; j--) { @@ -1896,10 +1876,8 @@ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { if (this.options.indexAddress) { hashes = tx.getHashes(view); - for (i = 0; i < hashes.length; i++) { - addr = hashes[i]; + for (addr of hashes) this.put(layout.T(addr, hash), DUMMY); - } } } @@ -1907,8 +1885,7 @@ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { return; if (!tx.isCoinbase()) { - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; addr = view.getOutput(input).getHash(); @@ -1945,10 +1922,8 @@ ChainDB.prototype.unindexTX = function unindexTX(tx, view) { this.del(layout.t(hash)); if (this.options.indexAddress) { hashes = tx.getHashes(view); - for (i = 0; i < hashes.length; i++) { - addr = hashes[i]; + for (addr of hashes) this.del(layout.T(addr, hash)); - } } } @@ -1956,7 +1931,7 @@ ChainDB.prototype.unindexTX = function unindexTX(tx, view) { return; if (!tx.isCoinbase()) { - for (i = 0; i < tx.inputs.length; i++) { + for (input of tx.inputs) { input = tx.inputs[i]; prevout = input.prevout; addr = view.getOutput(input).getHash(); @@ -2172,8 +2147,7 @@ StateCache.prototype._init = function _init() { for (i = 0; i < 32; i++) this.bits.push(null); - for (i = 0; i < this.network.deploys.length; i++) { - deployment = this.network.deploys[i]; + for (deployment of this.network.deploys) { assert(!this.bits[deployment.bit]); this.bits[deployment.bit] = new Map(); } @@ -2209,10 +2183,9 @@ StateCache.prototype.commit = function commit() { }; StateCache.prototype.drop = function drop() { - var i, update, cache; + var update, cache; - for (i = 0; i < this.updates.length; i++) { - update = this.updates[i]; + for (update of this.updates) { cache = this.bits[update.bit]; assert(cache); cache.delete(update.hash); diff --git a/lib/btc/uri.js b/lib/btc/uri.js index 5918b2f1..8492615d 100644 --- a/lib/btc/uri.js +++ b/lib/btc/uri.js @@ -202,10 +202,9 @@ function parsePairs(str) { var parts = str.split('&'); var data = new BitcoinQuery(); var size = 0; - var i, index, pair, key, value; + var index, pair, key, value; - for (i = 0; i < parts.length; i++) { - pair = parts[i]; + for (pair of parts) { index = pair.indexOf('='); if (index === -1) { diff --git a/lib/coins/coins.js b/lib/coins/coins.js index 0c347203..8e9808c2 100644 --- a/lib/coins/coins.js +++ b/lib/coins/coins.js @@ -564,7 +564,7 @@ Coins.fromRaw = function fromRaw(data, hash) { */ Coins.prototype.fromTX = function fromTX(tx, height) { - var i, output; + var output; assert(typeof height === 'number'); @@ -573,14 +573,11 @@ Coins.prototype.fromTX = function fromTX(tx, height) { this.height = height; this.coinbase = tx.isCoinbase(); - for (i = 0; i < tx.outputs.length; i++) { - output = tx.outputs[i]; - + for (output of tx.outputs) { if (output.script.isUnspendable()) { this.outputs.push(null); continue; } - this.outputs.push(CoinEntry.fromOutput(output)); } diff --git a/lib/coins/coinview.js b/lib/coins/coinview.js index 439a5119..fb2ca4c0 100644 --- a/lib/coins/coinview.js +++ b/lib/coins/coinview.js @@ -328,10 +328,9 @@ CoinView.prototype.readCoins = async function readCoins(db, hash) { CoinView.prototype.ensureInputs = async function ensureInputs(db, tx) { var found = true; - var i, input; + var input; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { if (!(await this.readCoins(db, input.prevout.hash))) found = false; } @@ -348,10 +347,9 @@ CoinView.prototype.ensureInputs = async function ensureInputs(db, tx) { */ CoinView.prototype.spendInputs = async function spendInputs(db, tx) { - var i, input, prevout, coins; + var input, prevout, coins; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; coins = await this.readCoins(db, prevout.hash); @@ -387,12 +385,11 @@ CoinView.prototype.toArray = function toArray() { CoinView.prototype.getFastSize = function getFastSize(tx) { var size = 0; - var i, input, entry; + var input, entry; size += tx.inputs.length; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { entry = this.getEntry(input); if (!entry) @@ -412,10 +409,9 @@ CoinView.prototype.getFastSize = function getFastSize(tx) { */ CoinView.prototype.toFast = function toFast(bw, tx) { - var i, input, prevout, coins, entry; + var input, prevout, coins, entry; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; coins = this.get(prevout.hash); @@ -447,10 +443,9 @@ CoinView.prototype.toFast = function toFast(bw, tx) { */ CoinView.prototype.fromFast = function fromFast(br, tx) { - var i, input, prevout, coins, entry; + var input, prevout, coins, entry; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (br.readU8() === 0) @@ -493,10 +488,9 @@ CoinView.fromFast = function fromFast(br, tx) { CoinView.prototype.toWriter = function toWriter(bw, tx) { var map = {}; - var i, input, prevout, coins, entry, height; + var input, prevout, coins, entry, height; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; coins = this.get(prevout.hash); @@ -549,10 +543,9 @@ CoinView.prototype.toRaw = function toRaw(tx) { */ CoinView.prototype.fromReader = function fromReader(br, tx) { - var i, input, prevout, coins, entry, height; + var input, prevout, coins, entry, height; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (br.readU8() === 0) diff --git a/lib/coins/undocoins.js b/lib/coins/undocoins.js index 15d3cc9e..c34a099f 100644 --- a/lib/coins/undocoins.js +++ b/lib/coins/undocoins.js @@ -52,14 +52,12 @@ UndoCoins.prototype.push = function push(entry) { UndoCoins.prototype.getSize = function getSize() { var size = 0; - var i, coin; + var coin; size += 4; - for (i = 0; i < this.items.length; i++) { - coin = this.items[i]; + for (coin of this.items) size += coin.getSize(); - } return size; }; @@ -72,14 +70,12 @@ UndoCoins.prototype.getSize = function getSize() { UndoCoins.prototype.toRaw = function toRaw() { var size = this.getSize(); var bw = new StaticWriter(size); - var i, coin; + var coin; bw.writeU32(this.items.length); - for (i = 0; i < this.items.length; i++) { - coin = this.items[i]; + for (coin of this.items) coin.toWriter(bw); - } return bw.render(); }; diff --git a/lib/db/level.js b/lib/db/level.js index 9a6a0acb..56d75c9f 100644 --- a/lib/db/level.js +++ b/lib/db/level.js @@ -35,14 +35,13 @@ DB.prototype.del = function del(key, options, callback) { }; DB.prototype.batch = function batch(ops, options, callback) { - var i, op; + var op; if (!ops) return new Batch(this); if (this.bufferKeys) { - for (i = 0; i < ops.length; i++) { - op = ops[i]; + for (op of ops) { if (Buffer.isBuffer(op.key)) op.key = op.key.toString('hex'); } diff --git a/lib/db/memdb.js b/lib/db/memdb.js index eab6c411..09c57f17 100644 --- a/lib/db/memdb.js +++ b/lib/db/memdb.js @@ -273,10 +273,9 @@ MemDB.prototype.getProperty = function getProperty(name) { MemDB.prototype.approximateSize = function approximateSize(start, end, callback) { var items = this.range(start, end); var size = 0; - var i, item; + var item; - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { size += item.key.length; size += item.value.length; } @@ -351,7 +350,7 @@ Batch.prototype.del = function del(key) { */ Batch.prototype.write = function write(callback) { - var i, op; + var op; if (this.written) { setImmediate(function() { @@ -360,8 +359,7 @@ Batch.prototype.write = function write(callback) { return; } - for (i = 0; i < this.ops.length; i++) { - op = this.ops[i]; + for (op of this.ops) { switch (op.type) { case 'put': this.db.insert(op.key, op.value); diff --git a/lib/hd/common.js b/lib/hd/common.js index 2110c805..c4a295e0 100644 --- a/lib/hd/common.js +++ b/lib/hd/common.js @@ -68,7 +68,7 @@ common.parsePath = function parsePath(path, max) { var parts = path.split('/'); var root = parts.shift(); var result = []; - var i, hardened, index; + var hardened, index; if (max == null) max = common.MAX_INDEX; @@ -80,8 +80,7 @@ common.parsePath = function parsePath(path, max) { throw new Error('Bad path root.'); } - for (i = 0; i < parts.length; i++) { - index = parts[i]; + for (index of parts) { hardened = index[index.length - 1] === '\''; if (hardened) diff --git a/lib/hd/mnemonic.js b/lib/hd/mnemonic.js index 0e933311..c6149546 100644 --- a/lib/hd/mnemonic.js +++ b/lib/hd/mnemonic.js @@ -345,10 +345,9 @@ Mnemonic.fromEntropy = function fromEntropy(entropy, lang) { */ Mnemonic.getLanguage = function getLanguage(word) { - var i, lang, wordlist; + var lang, wordlist; - for (i = 0; i < Mnemonic.languages.length; i++) { - lang = Mnemonic.languages[i]; + for (lang of Mnemonic.languages) { wordlist = Mnemonic.getWordlist(lang); if (util.binarySearch(wordlist, word, util.strcmp) !== -1) return lang; diff --git a/lib/hd/private.js b/lib/hd/private.js index a8f0dd19..39da88c2 100644 --- a/lib/hd/private.js +++ b/lib/hd/private.js @@ -385,10 +385,10 @@ HDPrivateKey.isValidPath = function isValidPath(path) { HDPrivateKey.prototype.derivePath = function derivePath(path) { var indexes = common.parsePath(path, common.MAX_INDEX); var key = this; - var i; + var index; - for (i = 0; i < indexes.length; i++) - key = key.derive(indexes[i]); + for (index of indexes) + key = key.derive(index); return key; }; diff --git a/lib/hd/public.js b/lib/hd/public.js index f5bdbac3..580b2f69 100644 --- a/lib/hd/public.js +++ b/lib/hd/public.js @@ -301,10 +301,10 @@ HDPublicKey.isValidPath = function isValidPath(path) { HDPublicKey.prototype.derivePath = function derivePath(path) { var indexes = common.parsePath(path, common.HARDENED); var key = this; - var i; + var index; - for (i = 0; i < indexes.length; i++) - key = key.derive(indexes[i]); + for (index of indexes) + key = key.derive(index); return key; }; diff --git a/lib/http/base.js b/lib/http/base.js index 6e14ae87..6d279f0d 100644 --- a/lib/http/base.js +++ b/lib/http/base.js @@ -126,7 +126,7 @@ HTTPBase.prototype._initRouter = function _initRouter() { */ HTTPBase.prototype.handleRequest = async function handleRequest(req, res) { - var i, routes, route, params; + var routes, route, params; if (await this.handleMounts(req, res)) return; @@ -141,8 +141,7 @@ HTTPBase.prototype.handleRequest = async function handleRequest(req, res) { if (!routes) throw new Error('No routes found for method: ' + req.method); - for (i = 0; i < routes.length; i++) { - route = routes[i]; + for (route of routes) { params = route.match(req.pathname); if (!params) @@ -441,10 +440,9 @@ HTTPBase.prototype.jsonRPC = function jsonRPC(rpc) { HTTPBase.prototype.handleMounts = async function handleMounts(req, res) { var url = req.url; - var i, route, server; + var route, server; - for (i = 0; i < this.mounts.length; i++) { - route = this.mounts[i]; + for (route of this.mounts) { server = route.handler; if (!route.hasPrefix(req.pathname)) @@ -472,11 +470,9 @@ HTTPBase.prototype.handleMounts = async function handleMounts(req, res) { */ HTTPBase.prototype.handleStack = async function handleStack(req, res) { - var i, route; - - for (i = 0; i < this.stack.length; i++) { - route = this.stack[i]; + var route; + for (route of this.stack) { if (!route.hasPrefix(req.pathname)) continue; @@ -496,11 +492,9 @@ HTTPBase.prototype.handleStack = async function handleStack(req, res) { */ HTTPBase.prototype.handleHooks = async function handleHooks(req, res) { - var i, route; - - for (i = 0; i < this.hooks.length; i++) { - route = this.hooks[i]; + var route; + for (route of this.hooks) { if (!route.hasPrefix(req.pathname)) continue; @@ -595,7 +589,7 @@ HTTPBase.prototype.all = function all() { HTTPBase.prototype.addSocket = function addSocket(ws) { var self = this; var socket = new WebSocket(ws, this); - var i, route; + var route; socket.on('error', function(err) { self.emit('error', err); @@ -615,10 +609,8 @@ HTTPBase.prototype.addSocket = function addSocket(ws) { this.sockets.push(socket); - for (i = 0; i < this.mounts.length; i++) { - route = this.mounts[i]; + for (route of this.mounts) route.handler.addSocket(ws); - } this.emit('socket', socket); }; @@ -1671,15 +1663,14 @@ function nop() {} function parsePairs(str, limit) { var parts = str.split('&'); var data = Object.create(null); - var i, index, pair, key, value; + var index, pair, key, value; if (parts.length > limit) return data; assert(!limit || parts.length <= limit, 'Too many keys in querystring.'); - for (i = 0; i < parts.length; i++) { - pair = parts[i]; + for (pair of parts) { index = pair.indexOf('='); if (index === -1) { diff --git a/lib/http/rpc.js b/lib/http/rpc.js index f32254be..e59870f7 100644 --- a/lib/http/rpc.js +++ b/lib/http/rpc.js @@ -307,7 +307,7 @@ RPC.prototype.getAddedNodeInfo = async function getAddedNodeInfo(args, help) { var valid = new Validator([args]); var addr = valid.str(0, ''); var result = []; - var i, target, node, peer; + var target, node, peer; if (help || args.length > 1) throw new RPCError(errs.MISC_ERROR, 'getaddednodeinfo ( "node" )'); @@ -315,9 +315,7 @@ RPC.prototype.getAddedNodeInfo = async function getAddedNodeInfo(args, help) { if (args.length === 1) target = parseIP(addr, this.network); - for (i = 0; i < hosts.nodes.length; i++) { - node = hosts.nodes[i]; - + for (node of hosts.nodes) { if (target) { if (node.host !== target.host) continue; @@ -655,7 +653,7 @@ RPC.prototype.getBlockHeader = async function getBlockHeader(args, help) { }; RPC.prototype.getChainTips = async function getChainTips(args, help) { - var i, hash, tips, result, entry, fork, main; + var hash, tips, result, entry, fork, main; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'getchaintips'); @@ -663,8 +661,7 @@ RPC.prototype.getChainTips = async function getChainTips(args, help) { tips = await this.chain.db.getTips(); result = []; - for (i = 0; i < tips.length; i++) { - hash = tips[i]; + for (hash of tips) { entry = await this.chain.db.getEntry(hash); assert(entry); @@ -710,7 +707,7 @@ RPC.prototype.getMempoolAncestors = async function getMempoolAncestors(args, hel var hash = valid.hash(0); var verbose = valid.bool(1, false); var out = []; - var i, entry, entries; + var entry, entries; if (help || args.length < 1 || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'getmempoolancestors txid (verbose)'); @@ -729,15 +726,11 @@ RPC.prototype.getMempoolAncestors = async function getMempoolAncestors(args, hel entries = this.mempool.getAncestors(entry); if (verbose) { - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) out.push(this.entryToJSON(entry)); - } } else { - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) out.push(entry.txid()); - } } return out; @@ -748,7 +741,7 @@ RPC.prototype.getMempoolDescendants = async function getMempoolDescendants(args, var hash = valid.hash(0); var verbose = valid.bool(1, false); var out = []; - var i, entry, entries; + var entry, entries; if (help || args.length < 1 || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'getmempooldescendants txid (verbose)'); @@ -767,15 +760,11 @@ RPC.prototype.getMempoolDescendants = async function getMempoolDescendants(args, entries = this.mempool.getDescendants(entry); if (verbose) { - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) out.push(this.entryToJSON(entry)); - } } else { - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) out.push(entry.txid()); - } } return out; @@ -921,8 +910,7 @@ RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { if (!block) throw new RPCError(errs.MISC_ERROR, 'Block not found.'); - for (i = 0; i < txids.length; i++) { - txid = txids[i]; + for (txid of txids) { if (!block.hasTX(txid)) { throw new RPCError(errs.VERIFY_ERROR, 'Block does not contain all txids.'); @@ -938,7 +926,7 @@ RPC.prototype.verifyTXOutProof = async function verifyTXOutProof(args, help) { var valid = new Validator([args]); var data = valid.buf(0); var out = []; - var i, block, hash, entry; + var block, hash, entry; if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'verifytxoutproof "proof"'); @@ -956,10 +944,8 @@ RPC.prototype.verifyTXOutProof = async function verifyTXOutProof(args, help) { if (!entry) throw new RPCError(errs.MISC_ERROR, 'Block not found in chain.'); - for (i = 0; i < block.tree.matches.length; i++) { - hash = block.tree.matches[i]; + for (hash of block.tree.matches) out.push(util.revHex(hash)); - } return out; }; @@ -1182,7 +1168,7 @@ RPC.prototype.getBlockTemplate = async function getBlockTemplate(args, help) { var coinbase = false; var txnCap = false; var valueCap = false; - var i, capability, block; + var capability, block; if (help || args.length > 1) { throw new RPCError(errs.MISC_ERROR, @@ -1216,9 +1202,7 @@ RPC.prototype.getBlockTemplate = async function getBlockTemplate(args, help) { maxVersion = -1; if (capabilities) { - for (i = 0; i < capabilities.length; i++) { - capability = capabilities[i]; - + for (capability of capabilities) { if (typeof capability !== 'string') throw new RPCError(errs.TYPE_ERROR, 'Invalid capability.'); @@ -1345,8 +1329,7 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb } // Calculate version based on given rules. - for (i = 0; i < this.network.deploys.length; i++) { - deploy = this.network.deploys[i]; + for (deploy of this.network.deploys) { state = await this.chain.getState(this.chain.tip, deploy); name = deploy.name; @@ -1466,7 +1449,7 @@ RPC.prototype.getMiningInfo = async function getMiningInfo(args, help) { var weight = 0; var txs = 0; var diff = 0; - var i, item; + var item; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'getmininginfo'); @@ -1476,10 +1459,8 @@ RPC.prototype.getMiningInfo = async function getMiningInfo(args, help) { txs = attempt.items.length + 1; diff = attempt.getDifficulty(); size = 1000; - for (i = 0; i < attempt.items.length; i++) { - item = attempt.items[i]; + for (item of attempt.items) size += item.tx.getBaseSize(); - } } return { @@ -1646,7 +1627,7 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h var inputs = valid.array(0); var sendTo = valid.obj(1); var locktime = valid.u32(2); - var i, tx, input, output, hash, index, sequence; + var tx, input, output, hash, index, sequence; var keys, addrs, key, value, address, b58; if (help || args.length < 2 || args.length > 3) { @@ -1667,8 +1648,7 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h if (locktime != null) tx.locktime = locktime; - for (i = 0; i < inputs.length; i++) { - input = inputs[i]; + for (input of tx.inputs) { valid = new Validator([input]); hash = valid.hash('txid'); @@ -1693,9 +1673,7 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h valid = new Validator([sendTo]); addrs = {}; - for (i = 0; i < keys.length; i++) { - key = keys[i]; - + for (key of keys) { if (key === 'data') { value = valid.buf(key); @@ -1831,7 +1809,7 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) var type = Script.hashType.ALL; var keys = []; var map = {}; - var i, j, tx, secret, key, coin; + var i, tx, secret, key, coin; var hash, index, script, value; var prev, redeem, op, parts; @@ -1864,8 +1842,7 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) } if (prevout) { - for (i = 0; i < prevout.length; i++) { - prev = prevout[i]; + for (prev of prevout) { valid = new Validator([prev]); hash = valid.hash('txid'); index = valid.u32('index'); @@ -1897,9 +1874,7 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) redeem = Script.fromRaw(redeem); - for (j = 0; j < redeem.code.length; j++) { - op = redeem.code[j]; - + for (op of redeem.code) { if (!op.data) continue; @@ -2271,7 +2246,7 @@ RPC.prototype.longpoll = function longpoll() { RPC.prototype.refreshBlock = function refreshBlock() { var pollers = this.pollers; - var i, job; + var job; this.attempt = null; this.lastActivity = 0; @@ -2280,10 +2255,8 @@ RPC.prototype.refreshBlock = function refreshBlock() { this.nonce2 = 0; this.pollers = []; - for (i = 0; i < pollers.length; i++) { - job = pollers[i]; + for (job of pollers) job.resolve(); - } }; RPC.prototype.bindChain = function bindChain() { @@ -2452,10 +2425,9 @@ RPC.prototype.getSoftforks = function getSoftforks() { RPC.prototype.getBIP9Softforks = async function getBIP9Softforks() { var tip = this.chain.tip; var forks = {}; - var i, deployment, state, status; + var deployment, state, status; - for (i = 0; i < this.network.deploys.length; i++) { - deployment = this.network.deploys[i]; + for (deployment of this.network.deploys) { state = await this.chain.getState(tip, deployment); switch (state) { @@ -2577,9 +2549,7 @@ RPC.prototype.txToJSON = function txToJSON(tx, entry) { conf = this.chain.height - height + 1; } - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; - + for (input of tx.inputs) { json = { coinbase: undefined, txid: undefined, @@ -2689,17 +2659,14 @@ RPC.prototype.blockToJSON = async function blockToJSON(entry, block, details) { var mtp = await entry.getMedianTime(); var nextHash = await this.chain.db.getNextHash(entry.hash); var txs = []; - var i, tx, json; - - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + var tx, json; + for (tx of block.txs) { if (details) { json = this.txToJSON(tx, entry); txs.push(json); continue; } - txs.push(tx.txid()); } diff --git a/lib/http/rpcbase.js b/lib/http/rpcbase.js index 3a39c043..5a516858 100644 --- a/lib/http/rpcbase.js +++ b/lib/http/rpcbase.js @@ -105,16 +105,14 @@ RPCBase.prototype.call = async function call(body, query) { var cmds = body; var out = []; var array = true; - var i, cmd, result, code; + var cmd, result, code; if (!Array.isArray(cmds)) { cmds = [cmds]; array = false; } - for (i = 0; i < cmds.length; i++) { - cmd = cmds[i]; - + for (cmd of cmds) { if (!cmd || typeof cmd !== 'object') { out.push({ result: null, @@ -245,11 +243,10 @@ RPCBase.prototype.call = async function call(body, query) { RPCBase.prototype.execute = async function execute(json, help) { var func = this.calls[json.method]; - var i, mount; + var mount; if (!func) { - for (i = 0; i < this.mounts.length; i++) { - mount = this.mounts[i]; + for (mount of this.mounts) { if (mount.calls[json.method]) return await mount.execute(json, help); } diff --git a/lib/http/server.js b/lib/http/server.js index 309f2854..0fbbff44 100644 --- a/lib/http/server.js +++ b/lib/http/server.js @@ -146,17 +146,15 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var address = valid.str('address'); var result = []; - var i, coins, coin; + var coins, coin; enforce(address, 'Address is required.'); enforce(!this.chain.options.spv, 'Cannot get coins in SPV mode.'); coins = await this.node.getCoinsByAddress(address); - for (i = 0; i < coins.length; i++) { - coin = coins[i]; + for (coin of coins) result.push(coin.getJSON(this.network)); - } res.send(200, result); }); @@ -187,17 +185,15 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var address = valid.array('addresses'); var result = []; - var i, coins, coin; + var coins, coin; enforce(address, 'Address is required.'); enforce(!this.chain.options.spv, 'Cannot get coins in SPV mode.'); coins = await this.node.getCoinsByAddress(address); - for (i = 0; i < coins.length; i++) { - coin = coins[i]; + for (coin of coins) result.push(coin.getJSON(this.network)); - } res.send(200, result); }); @@ -228,15 +224,14 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var address = valid.str('address'); var result = []; - var i, metas, meta, view; + var metas, meta, view; enforce(address, 'Address is required.'); enforce(!this.chain.options.spv, 'Cannot get TX in SPV mode.'); metas = await this.node.getMetaByAddress(address); - for (i = 0; i < metas.length; i++) { - meta = metas[i]; + for (meta of metas) { view = await this.node.getMetaView(meta); result.push(meta.getJSON(this.network, view)); } @@ -249,15 +244,14 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var address = valid.array('address'); var result = []; - var i, metas, meta, view; + var metas, meta, view; enforce(address, 'Address is required.'); enforce(!this.chain.options.spv, 'Cannot get TX in SPV mode.'); metas = await this.node.getMetaByAddress(address); - for (i = 0; i < metas.length; i++) { - meta = metas[i]; + for (meta of metas) { view = await this.node.getMetaView(meta); result.push(meta.getJSON(this.network, view)); } @@ -301,16 +295,14 @@ HTTPServer.prototype.initRouter = function initRouter() { // Mempool snapshot this.get('/mempool', async function(req, res) { var result = []; - var i, hash, hashes; + var hash, hashes; enforce(this.mempool, 'No mempool available.'); hashes = this.mempool.getSnapshot(); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) result.push(util.revHex(hash)); - } res.send(200, result); }); @@ -631,13 +623,12 @@ HTTPServer.prototype.bindChain = function bindChain() { HTTPServer.prototype.filterBlock = function filterBlock(socket, block) { var txs = []; - var i, tx; + var tx; if (!socket.filter) return txs; - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + for (tx of block.txs) { if (this.filterTX(socket, tx)) txs.push(tx.toRaw()); } @@ -678,8 +669,7 @@ HTTPServer.prototype.filterTX = function filterTX(socket, tx) { return true; if (!tx.isCoinbase()) { - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (socket.filter.test(prevout.toRaw())) return true; @@ -715,12 +705,10 @@ HTTPServer.prototype.scan = async function scan(socket, start) { HTTPServer.prototype.scanner = function scanner(socket, entry, txs) { var block = entry.toRaw(); var raw = []; - var i, tx; + var tx; - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) raw.push(tx.toRaw()); - } socket.emit('block rescan', block, raw); diff --git a/lib/mempool/fees.js b/lib/mempool/fees.js index 82174aba..9efca002 100644 --- a/lib/mempool/fees.js +++ b/lib/mempool/fees.js @@ -636,7 +636,7 @@ PolicyEstimator.prototype.processBlockTX = function processBlockTX(height, entry */ PolicyEstimator.prototype.processBlock = function processBlock(height, entries, current) { - var i; + var entry; // Ignore reorgs. if (height <= this.bestHeight) @@ -684,8 +684,8 @@ PolicyEstimator.prototype.processBlock = function processBlock(height, entries, this.feeStats.clearCurrent(height); this.priStats.clearCurrent(height); - for (i = 0; i < entries.length; i++) - this.processBlockTX(height, entries[i]); + for (entry of entries) + this.processBlockTX(height, entry); this.feeStats.updateAverages(); this.priStats.updateAverages(); diff --git a/lib/mempool/mempool.js b/lib/mempool/mempool.js index c9d4c93c..0032cafc 100644 --- a/lib/mempool/mempool.js +++ b/lib/mempool/mempool.js @@ -105,7 +105,7 @@ util.inherits(Mempool, AsyncObject); Mempool.prototype._open = async function open() { var size = (this.options.maxSize / 1024).toFixed(2); - var i, entries, entry, view, fees; + var entries, entry, view, fees; await this.chain.open(); await this.cache.open(); @@ -113,14 +113,10 @@ Mempool.prototype._open = async function open() { if (this.options.persistent) { entries = await this.cache.getEntries(); - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) this.trackEntry(entry); - } - - for (i = 0; i < entries.length; i++) { - entry = entries[i]; + for (entry of entries) { this.updateAncestors(entry, addFee); if (this.options.indexAddress) { @@ -371,18 +367,16 @@ Mempool.prototype.limitSize = function limitSize(added) { var threshold = maxSize - (maxSize / 10); var expiryTime = this.options.expiryTime; var now = util.now(); - var i, queue, hashes, hash, entry, start; + var queue, hash, entry, start; if (this.size <= maxSize) return false; queue = new Heap(cmpRate); - hashes = this.getSnapshot(); start = util.hrtime(); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of this.map.keys()) { entry = this.getEntry(hash); if (!entry) @@ -530,74 +524,74 @@ Mempool.prototype.getSpentTX = function getSpentTX(hash, index) { /** * Find all coins pertaining to a certain address. - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {Coin[]} */ -Mempool.prototype.getCoinsByAddress = function getCoinsByAddress(addresses) { - var coins = []; - var i, j, coin, hash; +Mempool.prototype.getCoinsByAddress = function getCoinsByAddress(addrs) { + var out = []; + var addr, hash, coins, coin; - if (!Array.isArray(addresses)) - addresses = [addresses]; + if (!Array.isArray(addrs)) + addrs = [addrs]; - for (i = 0; i < addresses.length; i++) { - hash = Address.getHash(addresses[i], 'hex'); - coin = this.coinIndex.get(hash); + for (addr of addrs) { + hash = Address.getHash(addr, 'hex'); + coins = this.coinIndex.get(hash); - for (j = 0; j < coin.length; j++) - coins.push(coin[j]); + for (coin of coins) + out.push(coin); } - return coins; + return out; }; /** * Find all transactions pertaining to a certain address. - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {TX[]} */ -Mempool.prototype.getTXByAddress = function getTXByAddress(addresses) { - var txs = []; - var i, j, tx, hash; +Mempool.prototype.getTXByAddress = function getTXByAddress(addrs) { + var out = []; + var addr, hash, txs, tx; - if (!Array.isArray(addresses)) - addresses = [addresses]; + if (!Array.isArray(addrs)) + addrs = [addrs]; - for (i = 0; i < addresses.length; i++) { - hash = Address.getHash(addresses[i], 'hex'); - tx = this.txIndex.get(hash); + for (addr of addrs) { + hash = Address.getHash(addr, 'hex'); + txs = this.txIndex.get(hash); - for (j = 0; j < tx.length; j++) - txs.push(tx[j]); + for (tx of txs) + out.push(tx); } - return txs; + return out; }; /** * Find all transactions pertaining to a certain address. - * @param {Address[]} addresses + * @param {Address[]} addrs * @returns {TXMeta[]} */ -Mempool.prototype.getMetaByAddress = function getMetaByAddress(addresses) { - var txs = []; - var i, j, tx, hash; +Mempool.prototype.getMetaByAddress = function getMetaByAddress(addrs) { + var out = []; + var addr, hash, txs, tx; - if (!Array.isArray(addresses)) - addresses = [addresses]; + if (!Array.isArray(addrs)) + addrs = [addrs]; - for (i = 0; i < addresses.length; i++) { - hash = Address.getHash(addresses[i], 'hex'); - tx = this.txIndex.getMeta(hash); + for (addr of addrs) { + hash = Address.getHash(addr, 'hex'); + txs = this.txIndex.getMeta(hash); - for (j = 0; j < tx.length; j++) - txs.push(tx[j]); + for (tx of txs) + out.push(tx); } - return txs; + return out; }; /** @@ -1187,10 +1181,9 @@ Mempool.prototype.updateAncestors = function updateAncestors(entry, map) { Mempool.prototype._countAncestors = function countAncestors(entry, count, set, child, map) { var tx = entry.tx; - var i, input, hash, parent; + var input, hash, parent; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { hash = input.prevout.hash; parent = this.getEntry(hash); @@ -1284,10 +1277,9 @@ Mempool.prototype.getAncestors = function getAncestors(entry) { Mempool.prototype._getAncestors = function getAncestors(entry, entries, set) { var tx = entry.tx; - var i, hash, input, parent; + var hash, input, parent; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { hash = input.prevout.hash; parent = this.getEntry(hash); @@ -1359,10 +1351,9 @@ Mempool.prototype._getDescendants = function getDescendants(entry, entries, set) Mempool.prototype.getDepends = function getDepends(tx) { var prevout = tx.getPrevout(); var depends = []; - var i, hash; + var hash; - for (i = 0; i < prevout.length; i++) { - hash = prevout[i]; + for (hash of prevout) { if (this.hasEntry(hash)) depends.push(hash); } @@ -1377,10 +1368,9 @@ Mempool.prototype.getDepends = function getDepends(tx) { */ Mempool.prototype.hasDepends = function hasDepends(tx) { - var i, input, hash; + var input, hash; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { hash = input.prevout.hash; if (this.hasEntry(hash)) return true; @@ -1455,7 +1445,7 @@ Mempool.prototype.hasOrphan = function hasOrphan(hash) { Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { var hash = tx.hash('hex'); - var i, prev; + var prev; if (tx.getWeight() > policy.MAX_TX_WEIGHT) { this.logger.debug('Ignoring large orphan: %s', tx.txid()); @@ -1464,8 +1454,7 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { return []; } - for (i = 0; i < missing.length; i++) { - prev = missing[i]; + for (prev of missing) { if (this.hasReject(prev)) { this.logger.debug('Not storing orphan %s (rejected parents).', tx.txid()); this.rejects.add(tx.hash()); @@ -1478,9 +1467,7 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { this.limitOrphans(); - for (i = 0; i < missing.length; i++) { - prev = missing[i]; - + for (prev of missing) { if (!this.waiting.has(prev)) this.waiting.set(prev, new Set()); @@ -1505,11 +1492,9 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { Mempool.prototype.handleOrphans = async function handleOrphans(parent) { var resolved = this.resolveOrphans(parent); - var i, orphan, tx, missing; - - for (i = 0; i < resolved.length; i++) { - orphan = resolved[i]; + var orphan, tx, missing; + for (orphan of resolved) { try { tx = orphan.toTX(); } catch (e) { @@ -1587,7 +1572,7 @@ Mempool.prototype.resolveOrphans = function resolveOrphans(parent) { Mempool.prototype.removeOrphan = function removeOrphan(hash) { var orphan = this.getOrphan(hash); - var i, tx, set, prevout, prev; + var tx, set, prevout, prev; if (!orphan) return false; @@ -1604,8 +1589,7 @@ Mempool.prototype.removeOrphan = function removeOrphan(hash) { prevout = tx.getPrevout(); - for (i = 0; i < prevout.length; i++) { - prev = prevout[i]; + for (prev of prevout) { set = this.waiting.get(prev); if (!set) @@ -1663,10 +1647,9 @@ Mempool.prototype.limitOrphans = function limitOrphans() { */ Mempool.prototype.isDoubleSpend = function isDoubleSpend(tx) { - var i, input, prevout; + var input, prevout; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (this.isSpent(prevout.hash, prevout.index)) return true; @@ -1701,10 +1684,9 @@ Mempool.prototype.getSpentView = async function getSpentView(tx) { Mempool.prototype.getCoinView = async function getCoinView(tx) { var view = new CoinView(); var prevout = tx.getPrevout(); - var i, hash, entry, coins; + var hash, entry, coins; - for (i = 0; i < prevout.length; i++) { - hash = prevout[i]; + for (hash of prevout) { entry = this.getEntry(hash); if (entry) { @@ -1736,11 +1718,9 @@ Mempool.prototype.getCoinView = async function getCoinView(tx) { Mempool.prototype.findMissing = function findMissing(tx, view) { var missing = []; - var i, input; - - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + var input; + for (input of tx.inputs) { if (view.hasEntry(input)) continue; @@ -1802,15 +1782,14 @@ Mempool.prototype.verifyFinal = function verifyFinal(tx, flags) { Mempool.prototype.trackEntry = function trackEntry(entry, view) { var tx = entry.tx; var hash = tx.hash('hex'); - var i, input, key; + var input, key; assert(!this.map.has(hash)); this.map.set(hash, entry); assert(!tx.isCoinbase()); - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { key = input.prevout.toKey(); this.spents.set(key, entry); } @@ -1830,15 +1809,14 @@ Mempool.prototype.trackEntry = function trackEntry(entry, view) { Mempool.prototype.untrackEntry = function untrackEntry(entry) { var tx = entry.tx; var hash = tx.hash('hex'); - var i, input, key; + var input, key; assert(this.map.has(hash)); this.map.delete(hash); assert(!tx.isCoinbase()); - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { key = input.prevout.toKey(); this.spents.delete(key); } @@ -1862,8 +1840,7 @@ Mempool.prototype.indexEntry = function indexEntry(entry, view) { this.txIndex.insert(entry, view); - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prev = input.prevout; this.coinIndex.remove(prev.hash, prev.index); } @@ -1885,8 +1862,7 @@ Mempool.prototype.unindexEntry = function unindexEntry(entry) { this.txIndex.remove(hash); - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout.hash; prev = this.getTX(prevout.hash); @@ -1908,10 +1884,9 @@ Mempool.prototype.unindexEntry = function unindexEntry(entry) { */ Mempool.prototype.removeDoubleSpends = function removeDoubleSpends(tx) { - var i, input, prevout, spent; + var input, prevout, spent; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; spent = this.getSpent(prevout.hash, prevout.index); @@ -2551,12 +2526,10 @@ MempoolCache.prototype.verify = async function verify() { MempoolCache.prototype.wipe = async function wipe() { var batch = this.db.batch(); var keys = await this.getKeys(); - var i, key; + var key; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) batch.del(key); - } batch.put(layout.V, encoding.U32(MempoolCache.VERSION)); batch.put(layout.R, Buffer.from(this.chain.tip.hash, 'hex')); diff --git a/lib/mempool/mempoolentry.js b/lib/mempool/mempoolentry.js index 7256b45d..19789e7e 100644 --- a/lib/mempool/mempoolentry.js +++ b/lib/mempool/mempoolentry.js @@ -98,10 +98,9 @@ MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) { var priority = tx.getPriority(view, height, size); var fee = tx.getFee(view); var dependencies = false; - var i, input; + var input; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { if (view.getHeight(input) === -1) { dependencies = true; break; @@ -229,7 +228,7 @@ MempoolEntry.prototype.getDescRate = function getDescRate() { MempoolEntry.prototype.memUsage = function memUsage() { var tx = this.tx; var total = 0; - var i, j, input, output, op; + var input, output, op; total += 176; // mempool entry total += 48; // dependencies @@ -243,9 +242,7 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // input array - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; - + for (input of tx.inputs) { total += 120; // input total += 104; // prevout total += 88; // prevout hash @@ -255,8 +252,7 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // script code array total += input.script.code.length * 40; // opcodes - for (j = 0; j < input.script.code.length; j++) { - op = input.script.code[j]; + for (op of input.script.code) { if (op.data) total += 80; // op buffers } @@ -268,17 +264,14 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // output array - for (i = 0; i < tx.outputs.length; i++) { - output = tx.outputs[i]; - + for (output of tx.outputs) { total += 104; // output total += 40; // script total += 80; // script raw buffer total += 32; // script code array total += output.script.code.length * 40; // opcodes - for (j = 0; j < output.script.code.length; j++) { - op = output.script.code[j]; + for (op of output.script.code) { if (op.data) total += 80; // op buffers } diff --git a/lib/mining/miner.js b/lib/mining/miner.js index a7ba8161..b9988865 100644 --- a/lib/mining/miner.js +++ b/lib/mining/miner.js @@ -258,7 +258,7 @@ Miner.prototype.assemble = function assemble(attempt) { var depMap = {}; var queue = new Heap(cmpRate); var priority = this.options.priorityWeight > 0; - var i, entry, item, tx, hash, input; + var entry, item, tx, hash, input; var prev, deps, weight, sigops, block; if (priority) @@ -279,8 +279,7 @@ Miner.prototype.assemble = function assemble(attempt) { if (tx.isCoinbase()) throw new Error('Cannot add coinbase to block.'); - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prev = input.prevout.hash; if (!this.mempool.hasEntry(prev)) @@ -347,8 +346,7 @@ Miner.prototype.assemble = function assemble(attempt) { if (!deps) continue; - for (i = 0; i < deps.length; i++) { - item = deps[i]; + for (item of deps) { if (--item.depCount === 0) queue.insert(item); } @@ -410,7 +408,7 @@ function MinerOptions(options) { */ MinerOptions.prototype.fromOptions = function fromOptions(options) { - var i, flags; + var item, flags; assert(options, 'Miner requires options.'); assert(options.chain && typeof options.chain === 'object', @@ -437,8 +435,8 @@ MinerOptions.prototype.fromOptions = function fromOptions(options) { if (options.address) { if (Array.isArray(options.address)) { - for (i = 0; i < options.address.length; i++) - this.addresses.push(new Address(options.address[i])); + for (item of options.address) + this.addresses.push(new Address(item)); } else { this.addresses.push(new Address(options.address)); } @@ -446,8 +444,8 @@ MinerOptions.prototype.fromOptions = function fromOptions(options) { if (options.addresses) { assert(Array.isArray(options.addresses)); - for (i = 0; i < options.addresses.length; i++) - this.addresses.push(new Address(options.addresses[i])); + for (item of options.addresses) + this.addresses.push(new Address(item)); } if (options.coinbaseFlags) { diff --git a/lib/mining/template.js b/lib/mining/template.js index 4f926889..586e6f01 100644 --- a/lib/mining/template.js +++ b/lib/mining/template.js @@ -173,14 +173,12 @@ BlockTemplate.fromOptions = function fromOptions(options) { BlockTemplate.prototype.getWitnessHash = function getWitnessHash() { var nonce = encoding.ZERO_HASH; var leaves = []; - var i, item, root, malleated, data; + var item, root, malleated, data; leaves.push(encoding.ZERO_HASH); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) leaves.push(item.tx.witnessHash()); - } [root, malleated] = merkle.createRoot(leaves); @@ -466,7 +464,7 @@ BlockTemplate.prototype.commit = function commit(proof) { var ts = proof.ts; var nonce = proof.nonce; var block = new Block(); - var i, tx, item; + var tx, item; block.version = this.version; block.prevBlock = this.prevBlock; @@ -479,10 +477,8 @@ BlockTemplate.prototype.commit = function commit(proof) { block.txs.push(tx); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) block.txs.push(item.tx); - } return block; }; @@ -701,10 +697,9 @@ function MerkleTree() { } MerkleTree.prototype.withFirst = function withFirst(hash) { - var i, step, data; + var step, data; - for (i = 0; i < this.steps.length; i++) { - step = this.steps[i]; + for (step of this.steps) { data = util.concat(hash, step); hash = digest.hash256(data); } @@ -714,26 +709,22 @@ MerkleTree.prototype.withFirst = function withFirst(hash) { MerkleTree.prototype.toJSON = function toJSON() { var steps = []; - var i, step; + var step; - for (i = 0; i < this.steps.length; i++) { - step = this.steps[i]; + for (step of this.steps) steps.push(step.toString('hex')); - } return steps; }; MerkleTree.prototype.fromItems = function fromItems(items) { var leaves = []; - var i, item; + var item; leaves.push(encoding.ZERO_HASH); - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) leaves.push(item.tx.hash()); - } return this.fromLeaves(leaves); }; diff --git a/lib/net/bip150.js b/lib/net/bip150.js index 0c67cf9f..f61f70b8 100644 --- a/lib/net/bip150.js +++ b/lib/net/bip150.js @@ -317,11 +317,10 @@ BIP150.prototype.hash = function hash(sid, ch, key) { */ BIP150.prototype.findAuthorized = function findAuthorized(hash) { - var i, key, msg; + var key, msg; // Scary O(n) stuff. - for (i = 0; i < this.db.authorized.length; i++) { - key = this.db.authorized[i]; + for (key of this.db.authorized) { msg = this.hash(this.output.sid, 'p', key); // XXX Do we really need a constant @@ -583,12 +582,11 @@ AuthDB.prototype.addAuthorized = function addAuthorized(key) { AuthDB.prototype.setKnown = function setKnown(map) { var keys = Object.keys(map); - var i, host, key; + var host, key; this.known = {}; - for (i = 0; i < keys.length; i++) { - host = keys[i]; + for (host of keys) { key = map[host]; this.addKnown(host, key); } @@ -600,14 +598,12 @@ AuthDB.prototype.setKnown = function setKnown(map) { */ AuthDB.prototype.setAuthorized = function setAuthorized(keys) { - var i, key; + var key; this.authorized.length = 0; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) this.addAuthorized(key); - } }; /** @@ -636,12 +632,10 @@ AuthDB.prototype.getKnown = function getKnown(hostname) { AuthDB.prototype.lookup = async function lookup() { var jobs = []; - var i, addr; + var addr; - for (i = 0; i < this.dnsKnown.length; i++) { - addr = this.dnsKnown[i]; + for (addr of this.dnsKnown) jobs.push(this.populate(addr[0], addr[1])); - } await Promise.all(jobs); }; @@ -656,7 +650,7 @@ AuthDB.prototype.lookup = async function lookup() { */ AuthDB.prototype.populate = async function populate(addr, key) { - var i, hosts, host; + var hosts, host; assert(addr.type === IP.types.DNS, 'Resolved host passed.'); @@ -669,9 +663,7 @@ AuthDB.prototype.populate = async function populate(addr, key) { return; } - for (i = 0; i < hosts.length; i++) { - host = hosts[i]; - + for (host of hosts) { if (addr.port !== 0) host = IP.toHostname(host, addr.port); @@ -715,10 +707,10 @@ AuthDB.prototype.readKnown = async function readKnown() { AuthDB.prototype.parseKnown = function parseKnown(text) { var lines = text.split(/\n+/); - var i, line, parts, hostname, host, ip, key; + var line, parts, hostname, host, ip, key; - for (i = 0; i < lines.length; i++) { - line = lines[i].trim(); + for (line of lines) { + line = line.trim(); if (line.length === 0) continue; @@ -793,10 +785,10 @@ AuthDB.prototype.readAuth = async function readAuth() { AuthDB.prototype.parseAuth = function parseAuth(text) { var lines = text.split(/\n+/); - var i, line, key; + var line, key; - for (i = 0; i < lines.length; i++) { - line = lines[i].trim(); + for (line of lines) { + line = line.trim(); if (line.length === 0) continue; diff --git a/lib/net/bip152.js b/lib/net/bip152.js index 8c5b1a0b..95082461 100644 --- a/lib/net/bip152.js +++ b/lib/net/bip152.js @@ -233,7 +233,7 @@ CompactBlock.prototype.frameRaw = function frameRaw(witness) { CompactBlock.prototype.getSize = function getSize(witness) { var size = 0; - var i, ptx; + var ptx; size += 80; size += 8; @@ -241,8 +241,7 @@ CompactBlock.prototype.getSize = function getSize(witness) { size += this.ids.length * 6; size += encoding.sizeVarint(this.ptx.length); - for (i = 0; i < this.ptx.length; i++) { - ptx = this.ptx[i]; + for (ptx of this.ptx) { size += encoding.sizeVarint(ptx.index); if (witness) size += ptx.tx.getSize(); @@ -261,7 +260,7 @@ CompactBlock.prototype.getSize = function getSize(witness) { */ CompactBlock.prototype.writeRaw = function writeRaw(bw, witness) { - var i, id, lo, hi, ptx; + var id, lo, hi, ptx; this.writeAbbr(bw); @@ -269,8 +268,7 @@ CompactBlock.prototype.writeRaw = function writeRaw(bw, witness) { bw.writeVarint(this.ids.length); - for (i = 0; i < this.ids.length; i++) { - id = this.ids[i]; + for (id of this.ids) { lo = id % 0x100000000; hi = (id - lo) / 0x100000000; hi &= 0xffff; @@ -280,8 +278,7 @@ CompactBlock.prototype.writeRaw = function writeRaw(bw, witness) { bw.writeVarint(this.ptx.length); - for (i = 0; i < this.ptx.length; i++) { - ptx = this.ptx[i]; + for (ptx of this.ptx) { bw.writeVarint(ptx.index); if (witness) ptx.tx.toWriter(bw); @@ -471,7 +468,7 @@ CompactBlock.prototype.init = function init() { CompactBlock.prototype.toBlock = function toBlock() { var block = new Block(); - var i, tx; + var tx; block.version = this.version; block.prevBlock = this.prevBlock; @@ -482,8 +479,7 @@ CompactBlock.prototype.toBlock = function toBlock() { block._hash = this._hash; block._hhash = this._hhash; - for (i = 0; i < this.available.length; i++) { - tx = this.available[i]; + for (tx of this.available) { assert(tx, 'Compact block is not full.'); block.txs.push(tx); } @@ -849,13 +845,11 @@ TXResponse.fromRaw = function fromRaw(data) { */ TXResponse.prototype.fromBlock = function fromBlock(block, req) { - var i, index; + var index; this.hash = req.hash; - for (i = 0; i < req.indexes.length; i++) { - index = req.indexes[i]; - + for (index of req.indexes) { if (index >= block.txs.length) break; @@ -920,13 +914,12 @@ TXResponse.prototype.toNormalWriter = function toNormalWriter(bw) { TXResponse.prototype.getSize = function getSize(witness) { var size = 0; - var i, tx; + var tx; size += 32; size += encoding.sizeVarint(this.txs.length); - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) { if (witness) size += tx.getSize(); else @@ -944,14 +937,13 @@ TXResponse.prototype.getSize = function getSize(witness) { */ TXResponse.prototype.writeRaw = function writeRaw(bw, witness) { - var i, tx; + var tx; bw.writeHash(this.hash); bw.writeVarint(this.txs.length); - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) { if (witness) tx.toWriter(bw); else diff --git a/lib/net/dns.js b/lib/net/dns.js index 599d5552..ad5090d1 100644 --- a/lib/net/dns.js +++ b/lib/net/dns.js @@ -60,7 +60,7 @@ exports.lookup = function lookup(host, proxy) { return new Promise(function(resolve, reject) { var addrs = []; - var i, addr; + var addr; dns.lookup(host, options, function(err, result) { if (err) { @@ -73,10 +73,8 @@ exports.lookup = function lookup(host, proxy) { return; } - for (i = 0; i < result.length; i++) { - addr = result[i]; + for (addr of result) addrs.push(addr.address); - } resolve(addrs); }); diff --git a/lib/net/hostlist.js b/lib/net/hostlist.js index 087882b6..f990d135 100644 --- a/lib/net/hostlist.js +++ b/lib/net/hostlist.js @@ -906,14 +906,12 @@ HostList.prototype.removeNode = function removeNode(host) { */ HostList.prototype.setSeeds = function setSeeds(seeds) { - var i, host; + var host; this.dnsSeeds.length = 0; - for (i = 0; i < seeds.length; i++) { - host = seeds[i]; + for (host of seeds) this.addSeed(host); - } }; /** @@ -922,15 +920,13 @@ HostList.prototype.setSeeds = function setSeeds(seeds) { */ HostList.prototype.setNodes = function setNodes(nodes) { - var i, host; + var host; this.dnsNodes.length = 0; this.nodes.length = 0; - for (i = 0; i < nodes.length; i++) { - host = nodes[i]; + for (host of nodes) this.addNode(host); - } }; /** @@ -1031,12 +1027,10 @@ HostList.prototype.markLocal = function markLocal(addr) { HostList.prototype.discoverSeeds = async function discoverSeeds() { var jobs = []; - var i, seed; + var seed; - for (i = 0; i < this.dnsSeeds.length; i++) { - seed = this.dnsSeeds[i]; + for (seed of this.dnsSeeds) jobs.push(this.populateSeed(seed)); - } await Promise.all(jobs); }; @@ -1049,12 +1043,10 @@ HostList.prototype.discoverSeeds = async function discoverSeeds() { HostList.prototype.discoverNodes = async function discoverNodes() { var jobs = []; - var i, node; + var node; - for (i = 0; i < this.dnsNodes.length; i++) { - node = this.dnsNodes[i]; + for (node of this.dnsNodes) jobs.push(this.populateNode(node)); - } await Promise.all(jobs); }; @@ -1085,12 +1077,10 @@ HostList.prototype.populateNode = async function populateNode(addr) { HostList.prototype.populateSeed = async function populateSeed(seed) { var addrs = await this.populate(seed); - var i, addr; + var addr; - for (i = 0; i < addrs.length; i++) { - addr = addrs[i]; + for (addr of addrs) this.add(addr); - } }; /** @@ -1173,7 +1163,7 @@ HostList.prototype.fromJSON = function fromJSON(json) { var totalFresh = 0; var used = []; var totalUsed = 0; - var i, bucket, keys, key, addr, entry, src; + var bucket, keys, key, addr, entry, src; assert(json && typeof json === 'object'); @@ -1226,8 +1216,7 @@ HostList.prototype.fromJSON = function fromJSON(json) { assert(json.used.length <= this.options.maxBuckets, 'Buckets mismatch.'); - for (i = 0; i < json.used.length; i++) { - keys = json.used[i]; + for (keys of json.used) { bucket = new List(); for (key of keys) { diff --git a/lib/net/packets.js b/lib/net/packets.js index d88678f3..c2d71c36 100644 --- a/lib/net/packets.js +++ b/lib/net/packets.js @@ -662,14 +662,12 @@ AddrPacket.prototype.getSize = function getSize() { */ AddrPacket.prototype.toWriter = function toWriter(bw) { - var i, item; + var item; bw.writeVarint(this.items.length); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) item.toWriter(bw, true); - } return bw; }; @@ -764,16 +762,14 @@ InvPacket.prototype.getSize = function getSize() { */ InvPacket.prototype.toWriter = function toWriter(bw) { - var i, item; + var item; assert(this.items.length <= 50000); bw.writeVarint(this.items.length); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) item.toWriter(bw); - } return bw; }; @@ -969,15 +965,15 @@ GetBlocksPacket.prototype.getSize = function getSize() { */ GetBlocksPacket.prototype.toWriter = function toWriter(bw) { - var i; + var hash; assert(this.locator.length <= 50000, 'Too many block hashes.'); bw.writeU32(this.version); bw.writeVarint(this.locator.length); - for (i = 0; i < this.locator.length; i++) - bw.writeHash(this.locator[i]); + for (hash of this.locator) + bw.writeHash(hash); bw.writeHash(this.stop || encoding.ZERO_HASH); @@ -1114,14 +1110,12 @@ HeadersPacket.prototype.type = exports.types.HEADERS; HeadersPacket.prototype.getSize = function getSize() { var size = 0; - var i, item; + var item; size += encoding.sizeVarint(this.items.length); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) size += item.getSize(); - } return size; }; @@ -1132,16 +1126,14 @@ HeadersPacket.prototype.getSize = function getSize() { */ HeadersPacket.prototype.toWriter = function toWriter(bw) { - var i, item; + var item; assert(this.items.length <= 2000, 'Too many headers.'); bw.writeVarint(this.items.length); - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) item.toWriter(bw); - } return bw; }; diff --git a/lib/net/peer.js b/lib/net/peer.js index 0aeb1731..90561448 100644 --- a/lib/net/peer.js +++ b/lib/net/peer.js @@ -717,7 +717,7 @@ Peer.prototype.finalize = async function finalize() { Peer.prototype.announceBlock = function announceBlock(blocks) { var inv = []; - var i, block; + var block; if (!this.handshake) return; @@ -728,9 +728,7 @@ Peer.prototype.announceBlock = function announceBlock(blocks) { if (!Array.isArray(blocks)) blocks = [blocks]; - for (i = 0; i < blocks.length; i++) { - block = blocks[i]; - + for (block of blocks) { assert(block instanceof Block); // Don't send if they already have it. @@ -770,7 +768,7 @@ Peer.prototype.announceBlock = function announceBlock(blocks) { Peer.prototype.announceTX = function announceTX(txs) { var inv = []; - var i, tx, hash, rate; + var tx, hash, rate; if (!this.handshake) return; @@ -786,9 +784,7 @@ Peer.prototype.announceTX = function announceTX(txs) { if (!Array.isArray(txs)) txs = [txs]; - for (i = 0; i < txs.length; i++) { - tx = txs[i]; - + for (tx of txs) { assert(tx instanceof TX); // Don't send if they already have it. @@ -823,7 +819,7 @@ Peer.prototype.announceTX = function announceTX(txs) { Peer.prototype.queueInv = function queueInv(items) { var hasBlock = false; - var i, item; + var item; if (!this.handshake) return; @@ -834,8 +830,7 @@ Peer.prototype.queueInv = function queueInv(items) { if (!Array.isArray(items)) items = [items]; - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { if (item.type === invTypes.BLOCK) hasBlock = true; this.invQueue.push(item); @@ -866,9 +861,7 @@ Peer.prototype.flushInv = function flushInv() { this.logger.spam('Serving %d inv items to %s.', queue.length, this.hostname()); - for (i = 0; i < queue.length; i++) { - item = queue[i]; - + for (item of queue) { if (!this.invFilter.added(item.hash, 'hex')) continue; @@ -898,10 +891,8 @@ Peer.prototype.sendInv = function sendInv(items) { if (!Array.isArray(items)) items = [items]; - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) this.invFilter.add(item.hash, 'hex'); - } if (items.length === 0) return; @@ -932,10 +923,8 @@ Peer.prototype.sendHeaders = function sendHeaders(items) { if (!Array.isArray(items)) items = [items]; - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) this.invFilter.add(item.hash()); - } if (items.length === 0) return; @@ -1052,7 +1041,7 @@ Peer.prototype.sendFeeRate = function sendFeeRate(rate) { Peer.prototype.destroy = function destroy() { var connected = this.connected; - var i, cmd, entry, jobs, job; + var cmd, entry, jobs, job; if (this.destroyed) return; @@ -1094,10 +1083,8 @@ Peer.prototype.destroy = function destroy() { this.drainSize = 0; this.drainQueue = []; - for (i = 0; i < jobs.length; i++) { - job = jobs[i]; + for (job of jobs) job.reject(new Error('Peer was destroyed.')); - } for ([cmd, entry] of this.responseMap) { this.responseMap.delete(cmd); @@ -1188,7 +1175,7 @@ Peer.prototype.drain = function drain() { Peer.prototype.handleDrain = function handleDrain() { var jobs = this.drainQueue; - var i, job; + var job; this.drainSize = 0; @@ -1197,10 +1184,8 @@ Peer.prototype.handleDrain = function handleDrain() { this.drainQueue = []; - for (i = 0; i < jobs.length; i++) { - job = jobs[i]; + for (job of jobs) job.resolve(); - } }; /** @@ -1516,12 +1501,10 @@ Peer.prototype.getData = function getData(items) { Peer.prototype.getItems = function getItems(type, hashes) { var items = []; - var i, hash; + var hash; - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) items.push(new InvItem(type, hash)); - } if (items.length === 0) return; @@ -2500,23 +2483,19 @@ RequestEntry.prototype.setTimeout = function setTimeout(timeout) { }; RequestEntry.prototype.reject = function reject(err) { - var i, job; + var job; - for (i = 0; i < this.jobs.length; i++) { - job = this.jobs[i]; + for (job of this.jobs) job.reject(err); - } this.jobs.length = 0; }; RequestEntry.prototype.resolve = function resolve(result) { - var i, job; + var job; - for (i = 0; i < this.jobs.length; i++) { - job = this.jobs[i]; + for (job of this.jobs) job.resolve(result); - } this.jobs.length = 0; }; diff --git a/lib/net/pool.js b/lib/net/pool.js index 1844a191..2b9b0966 100644 --- a/lib/net/pool.js +++ b/lib/net/pool.js @@ -961,10 +961,9 @@ Pool.prototype.resolveHeight = function resolveHeight(hash, height) { */ Pool.prototype.getNextTip = function getNextTip(height) { - var i, next; + var next; - for (i = 0; i < this.network.checkpoints.length; i++) { - next = this.network.checkpoints[i]; + for (next of this.network.checkpoints) { if (next.height > height) return new HeaderEntry(next.hash, next.height); } @@ -1548,7 +1547,7 @@ Pool.prototype.handlePong = async function handlePong(peer, packet) { Pool.prototype.handleGetAddr = async function handleGetAddr(peer, packet) { var items = []; - var i, addrs, addr; + var addrs, addr; if (this.options.selfish) return; @@ -1564,9 +1563,7 @@ Pool.prototype.handleGetAddr = async function handleGetAddr(peer, packet) { addrs = this.hosts.toArray(); - for (i = 0; i < addrs.length; i++) { - addr = addrs[i]; - + for (addr of addrs) { if (!peer.addrFilter.added(addr.hostname, 'ascii')) continue; @@ -1599,11 +1596,9 @@ Pool.prototype.handleAddr = async function handleAddr(peer, packet) { var addrs = packet.items; var now = this.network.now(); var services = this.options.getRequiredServices(); - var i, addr; - - for (i = 0; i < addrs.length; i++) { - addr = addrs[i]; + var addr; + for (addr of addrs) { peer.addrFilter.add(addr.hostname, 'ascii'); if (!addr.isRoutable()) @@ -1661,15 +1656,14 @@ Pool.prototype._handleInv = async function handleInv(peer, packet) { var blocks = []; var txs = []; var unknown = -1; - var i, item; + var item; if (items.length > 50000) { peer.increaseBan(100); return; } - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { switch (item.type) { case invTypes.BLOCK: blocks.push(item.hash); @@ -1815,7 +1809,7 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { var blocks = 0; var compact = 0; var unknown = -1; - var i, j, item, tx, block, result, height; + var item, tx, block, result, height; if (items.length > 50000) { this.logger.warning('Peer sent inv with >50k items (%s).', peer.hostname()); @@ -1824,9 +1818,7 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { return; } - for (i = 0; i < items.length; i++) { - item = items[i]; - + for (item of items) { if (item.isTX()) { tx = await this.getItem(peer, item); @@ -1888,8 +1880,7 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { peer.send(new packets.MerkleBlockPacket(block)); - for (j = 0; j < block.txs.length; j++) { - tx = block.txs[j]; + for (tx of block.txs) { peer.send(new packets.TXPacket(tx, item.hasWitness())); txs++; } @@ -1973,11 +1964,9 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { Pool.prototype.handleNotFound = async function handleNotFound(peer, packet) { var items = packet.items; - var i, item; - - for (i = 0; i < items.length; i++) { - item = items[i]; + var item; + for (item of items) { if (!this.resolveItem(peer, item)) { this.logger.warning( 'Peer sent notfound for unrequested item: %s (%s).', @@ -2115,7 +2104,7 @@ Pool.prototype.handleHeaders = async function handleHeaders(peer, packet) { Pool.prototype._handleHeaders = async function handleHeaders(peer, packet) { var headers = packet.items; var checkpoint = false; - var i, header, hash, height, last, node; + var header, hash, height, last, node; if (!this.checkpoints) return; @@ -2136,8 +2125,7 @@ Pool.prototype._handleHeaders = async function handleHeaders(peer, packet) { assert(this.headerChain.size > 0); - for (i = 0; i < headers.length; i++) { - header = headers[i]; + for (header of headers) { last = this.headerChain.tail; hash = header.hash('hex'); height = last.height + 1; @@ -2622,7 +2610,7 @@ Pool.prototype.handleReject = async function handleReject(peer, packet) { Pool.prototype.handleMempool = async function handleMempool(peer, packet) { var items = []; - var i, hash, hashes; + var hash, hashes; if (!this.mempool) return; @@ -2643,10 +2631,8 @@ Pool.prototype.handleMempool = async function handleMempool(peer, packet) { hashes = this.mempool.getSnapshot(); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) items.push(new InvItem(invTypes.TX, hash)); - } this.logger.debug( 'Sending mempool snapshot (%s).', @@ -3117,9 +3103,7 @@ Pool.prototype.getHost = function getHost() { var now = this.network.now(); var i, entry, addr; - for (i = 0; i < this.hosts.nodes.length; i++) { - addr = this.hosts.nodes[i]; - + for (addr of this.hosts.nodes) { if (this.peers.has(addr.hostname)) continue; @@ -3431,7 +3415,7 @@ Pool.prototype.getBlocks = async function getBlocks(peer, tip, stop) { Pool.prototype.getBlock = function getBlock(peer, hashes) { var now = util.ms(); var items = []; - var i, hash; + var hash; if (!this.loaded) return; @@ -3442,9 +3426,7 @@ Pool.prototype.getBlock = function getBlock(peer, hashes) { if (peer.destroyed) throw new Error('Peer is destroyed (getdata).'); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; - + for (hash of hashes) { if (this.blockMap.has(hash)) continue; @@ -3478,7 +3460,7 @@ Pool.prototype.getBlock = function getBlock(peer, hashes) { Pool.prototype.getTX = function getTX(peer, hashes) { var now = util.ms(); var items = []; - var i, hash; + var hash; if (!this.loaded) return; @@ -3489,9 +3471,7 @@ Pool.prototype.getTX = function getTX(peer, hashes) { if (peer.destroyed) throw new Error('Peer is destroyed (getdata).'); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; - + for (hash of hashes) { if (this.txMap.has(hash)) continue; @@ -3574,11 +3554,9 @@ Pool.prototype.hasTX = function hasTX(hash) { Pool.prototype.ensureTX = function ensureTX(peer, hashes) { var items = []; - var i, hash; - - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + var hash; + for (hash of hashes) { if (this.hasTX(hash)) continue; @@ -4382,14 +4360,12 @@ BroadcastItem.prototype.cleanup = function cleanup() { */ BroadcastItem.prototype.reject = function reject(err) { - var i, job; + var job; this.cleanup(); - for (i = 0; i < this.jobs.length; i++) { - job = this.jobs[i]; + for (job of this.jobs) job.reject(err); - } this.jobs.length = 0; }; @@ -4399,14 +4375,12 @@ BroadcastItem.prototype.reject = function reject(err) { */ BroadcastItem.prototype.resolve = function resolve() { - var i, job; + var job; this.cleanup(); - for (i = 0; i < this.jobs.length; i++) { - job = this.jobs[i]; + for (job of this.jobs) job.resolve(false); - } this.jobs.length = 0; }; @@ -4418,15 +4392,13 @@ BroadcastItem.prototype.resolve = function resolve() { BroadcastItem.prototype.handleAck = function handleAck(peer) { var self = this; - var i, job; + var job; setTimeout(function() { self.emit('ack', peer); - for (i = 0; i < self.jobs.length; i++) { - job = self.jobs[i]; + for (job of self.jobs) job.resolve(true); - } self.jobs.length = 0; }, 1000); @@ -4438,14 +4410,12 @@ BroadcastItem.prototype.handleAck = function handleAck(peer) { */ BroadcastItem.prototype.handleReject = function handleReject(peer) { - var i, job; + var job; this.emit('reject', peer); - for (i = 0; i < this.jobs.length; i++) { - job = this.jobs[i]; + for (job of this.jobs) job.resolve(false); - } this.jobs.length = 0; }; diff --git a/lib/net/proxysocket.js b/lib/net/proxysocket.js index 19df7748..8452b7ef 100644 --- a/lib/net/proxysocket.js +++ b/lib/net/proxysocket.js @@ -98,7 +98,7 @@ ProxySocket.prototype._init = function _init() { ProxySocket.prototype.connect = function connect(port, host) { var nonce = 0; - var i, pow; + var chunk, pow; this.remoteAddress = host; this.remotePort = port; @@ -136,8 +136,8 @@ ProxySocket.prototype.connect = function connect(port, host) { this.socket.emit('tcp connect', port, host, nonce); - for (i = 0; i < this.sendBuffer.length; i++) - this.write(this.sendBuffer[i]); + for (chunk of this.sendBuffer) + this.write(chunk); this.sendBuffer.length = 0; }; @@ -182,13 +182,12 @@ ProxySocket.prototype.pause = function pause() { ProxySocket.prototype.resume = function resume() { var recv = this.recvBuffer; - var i, data; + var data; this.paused = false; this.recvBuffer = []; - for (i = 0; i < recv.length; i++) { - data = recv[i]; + for (data of recv) { this.bytesRead += data.length; this.emit('data', data); } diff --git a/lib/net/socks.js b/lib/net/socks.js index 1bfccc4c..4664b7ac 100644 --- a/lib/net/socks.js +++ b/lib/net/socks.js @@ -563,7 +563,7 @@ util.inherits(Proxy, EventEmitter); Proxy.prototype.connect = async function connect(port, host) { var self = this; - var i, options, socket; + var op, options, socket; assert(!this.socket, 'Already connected.'); @@ -608,8 +608,8 @@ Proxy.prototype.connect = async function connect(port, host) { self.emit('timeout'); }); - for (i = 0; i < this.ops.length; i++) - this.ops[i].call(this); + for (op of this.ops) + op.call(this); this.ops.length = 0; diff --git a/lib/net/upnp.js b/lib/net/upnp.js index 3975983e..7d5d31a2 100644 --- a/lib/net/upnp.js +++ b/lib/net/upnp.js @@ -266,11 +266,9 @@ UPNP.prototype.resolve = async function resolve(location, targets) { UPNP.parseHeader = function parseHeader(str) { var lines = str.split(/\r?\n/); var headers = {}; - var i, line, index, left, right; - - for (i = 0; i < lines.length; i++) { - line = lines[i]; + var line, index, left, right; + for (line of lines) { line = line.trim(); if (line.length === 0) @@ -342,10 +340,9 @@ function UPNPService(options) { UPNPService.prototype.createRequest = function createRequest(action, args) { var params = ''; - var i, arg; + var arg; - for (i = 0; i < args.length; i++) { - arg = args[i]; + for (arg of args) { params += '<' + arg[0]+ '>'; if (arg.length > 1) params += arg[1]; @@ -588,11 +585,9 @@ XMLElement.prototype.collect = function collect(name) { */ XMLElement.prototype._collect = function _collect(name, result) { - var i, child; - - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; + var child; + for (child of this.children) { if (child.type === name) { result.push(child); continue; @@ -611,11 +606,9 @@ XMLElement.prototype._collect = function _collect(name, result) { */ XMLElement.prototype.find = function find(name) { - var i, child; - - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; + var child; + for (child of this.children) { if (child.type === name) return child; @@ -633,23 +626,19 @@ XMLElement.prototype.find = function find(name) { function parseServices(el) { var children = el.collect('service'); var services = []; - var i, child; + var child; - for (i = 0; i < children.length; i++) { - child = children[i]; + for (child of children) services.push(parseService(child)); - } return services; } function parseService(el) { var service = {}; - var i, child; - - for (i = 0; i < el.children.length; i++) { - child = el.children[i]; + var child; + for (child of el.children) { if (child.children.length > 0) continue; @@ -660,20 +649,18 @@ function parseService(el) { } function findService(services, name) { - var i, service; + var service; - for (i = 0; i < services.length; i++) { - service = services[i]; + for (service of services) { if (service.serviceType === name) return service; } } function extractServices(services, targets) { - var i, name, service; + var name, service; - for (i = 0; i < targets.length; i++) { - name = targets[i]; + for (name of targets) { service = findService(services, name); if (service) return service; diff --git a/lib/node/config.js b/lib/node/config.js index 6ed81bfd..824ba2b7 100644 --- a/lib/node/config.js +++ b/lib/node/config.js @@ -64,11 +64,9 @@ Config.alias = { Config.prototype.inject = function inject(options) { var keys = Object.keys(options); - var i, key, value; - - for (i = 0; i < keys.length; i++) { - key = keys[i]; + var key, value; + for (key of keys) { switch (key) { case 'hash': case 'query': @@ -198,15 +196,14 @@ Config.prototype.has = function has(key) { */ Config.prototype.get = function get(key, fallback) { - var i, keys, value; + var keys, value; if (fallback === undefined) fallback = null; if (Array.isArray(key)) { keys = key; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { value = this.get(key); if (value !== null) return value; @@ -443,7 +440,7 @@ Config.prototype.buf = function buf(key, fallback) { Config.prototype.array = function array(key, fallback) { var value = this.get(key); - var i, result, parts, part; + var result, parts, part; if (fallback === undefined) fallback = null; @@ -460,9 +457,7 @@ Config.prototype.array = function array(key, fallback) { parts = value.trim().split(/\s*,\s*/); result = []; - for (i = 0; i < parts.length; i++) { - part = parts[i]; - + for (part of parts) { if (part.length === 0) continue; @@ -655,15 +650,15 @@ Config.prototype.location = function location(file) { */ Config.prototype.parseConfig = function parseConfig(text) { - var i, parts, line, key, value, eq, col, alias; + var parts, line, key, value, eq, col, alias; assert(typeof text === 'string', 'Config must be text.'); text = text.trim(); parts = text.split(/\n+/); - for (i = 0; i < parts.length; i++) { - line = parts[i].trim(); + for (line of parts) { + line = line.trim(); if (line.length === 0) continue; @@ -708,7 +703,7 @@ Config.prototype.parseConfig = function parseConfig(text) { */ Config.prototype.parseArg = function parseArg(argv) { - var i, j, arg, key, value, alias, equals; + var i, arg, key, value, alias, equals; if (!argv || typeof argv !== 'object') argv = process.argv; @@ -755,8 +750,7 @@ Config.prototype.parseArg = function parseArg(argv) { // e.g. -abc arg = arg.substring(1); - for (j = 0; j < arg.length; j++) { - key = arg[j]; + for (key of arg) { alias = Config.alias.arg[key]; if (alias) key = alias; @@ -791,7 +785,7 @@ Config.prototype.parseArg = function parseArg(argv) { Config.prototype.parseEnv = function parseEnv(env) { var prefix = this.module; - var i, keys, key, value, alias; + var keys, key, value, alias; prefix = prefix.toUpperCase(); prefix = prefix.replace(/-/g, '_'); @@ -804,9 +798,7 @@ Config.prototype.parseEnv = function parseEnv(env) { keys = Object.keys(env); - for (i = 0; i < keys.length; i++) { - key = keys[i]; - + for (key of keys) { if (key.indexOf(prefix) !== 0) continue; @@ -878,7 +870,7 @@ Config.prototype.parseHash = function parseHash(hash) { */ Config.prototype.parseForm = function parseForm(query, map) { - var i, parts, index, pair, key, value, alias; + var parts, index, pair, key, value, alias; assert(typeof query === 'string'); @@ -890,8 +882,7 @@ Config.prototype.parseForm = function parseForm(query, map) { parts = query.split('&'); - for (i = 0; i < parts.length; i++) { - pair = parts[i]; + for (pair of parts) { index = pair.indexOf('='); if (index === -1) { diff --git a/lib/node/fullnode.js b/lib/node/fullnode.js index 648e7647..1b1b8392 100644 --- a/lib/node/fullnode.js +++ b/lib/node/fullnode.js @@ -393,18 +393,17 @@ FullNode.prototype.getCoin = function getCoin(hash, index) { /** * Get coins that pertain to an address from the mempool or chain database. * Takes into account spent coins in the mempool. - * @param {Address} addresses + * @param {Address} addrs * @returns {Promise} - Returns {@link Coin}[]. */ -FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addresses) { - var mempool = this.mempool.getCoinsByAddress(addresses); - var chain = await this.chain.db.getCoinsByAddress(addresses); +FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { + var mempool = this.mempool.getCoinsByAddress(addrs); + var chain = await this.chain.db.getCoinsByAddress(addrs); var out = []; - var i, coin, spent; + var coin, spent; - for (i = 0; i < chain.length; i++) { - coin = chain[i]; + for (coin of chain) { spent = this.mempool.isSpent(coin.hash, coin.index); if (spent) @@ -413,10 +412,8 @@ FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addresse out.push(coin); } - for (i = 0; i < mempool.length; i++) { - coin = mempool[i]; + for (coin of mempool) out.push(coin); - } return out; }; @@ -424,13 +421,13 @@ FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addresse /** * Retrieve transactions pertaining to an * address from the mempool or chain database. - * @param {Address} addresses + * @param {Address} addrs * @returns {Promise} - Returns {@link TXMeta}[]. */ -FullNode.prototype.getMetaByAddress = async function getTXByAddress(addresses) { - var mempool = this.mempool.getMetaByAddress(addresses); - var chain = await this.chain.db.getMetaByAddress(addresses); +FullNode.prototype.getMetaByAddress = async function getTXByAddress(addrs) { + var mempool = this.mempool.getMetaByAddress(addrs); + var chain = await this.chain.db.getMetaByAddress(addrs); return chain.concat(mempool); }; @@ -464,19 +461,17 @@ FullNode.prototype.getMetaView = async function getMetaView(meta) { /** * Retrieve transactions pertaining to an * address from the mempool or chain database. - * @param {Address} addresses + * @param {Address} addrs * @returns {Promise} - Returns {@link TX}[]. */ -FullNode.prototype.getTXByAddress = async function getTXByAddress(addresses) { - var mtxs = await this.getMetaByAddress(addresses); +FullNode.prototype.getTXByAddress = async function getTXByAddress(addrs) { + var mtxs = await this.getMetaByAddress(addrs); var out = []; - var i, mtx; + var mtx; - for (i = 0; i < mtxs.length; i++) { - mtx = mtxs[i]; + for (mtx of mtxs) out.push(mtx.tx); - } return out; }; diff --git a/lib/node/node.js b/lib/node/node.js index 3f821a21..fa2a055f 100644 --- a/lib/node/node.js +++ b/lib/node/node.js @@ -211,14 +211,12 @@ Node.prototype.handlePreclose = async function handlePreclose() { */ Node.prototype.handleClose = async function handleClose() { - var i, bound; + var bound; this.startTime = -1; - for (i = 0; i < this.bound.length; i++) { - bound = this.bound[i]; + for (bound of this.bound) bound[0].removeListener(bound[1], bound[2]); - } this.bound.length = 0; @@ -381,14 +379,12 @@ Node.prototype.require = function require(name) { Node.prototype.loadPlugins = function loadPlugins() { var plugins = this.config.array('plugins', []); var loader = this.config.func('loader'); - var i, plugin; + var plugin; if (!loader) return; - for (i = 0; i < plugins.length; i++) { - plugin = plugins[i]; - + for (plugin of plugins) { assert(plugin); if (typeof plugin === 'string') @@ -404,10 +400,9 @@ Node.prototype.loadPlugins = function loadPlugins() { */ Node.prototype.openPlugins = async function openPlugins() { - var i, plugin; + var plugin; - for (i = 0; i < this.stack.length; i++) { - plugin = this.stack[i]; + for (plugin of this.stack) { if (plugin.open) await plugin.open(); } @@ -419,10 +414,9 @@ Node.prototype.openPlugins = async function openPlugins() { */ Node.prototype.closePlugins = async function closePlugins() { - var i, plugin; + var plugin; - for (i = 0; i < this.stack.length; i++) { - plugin = this.stack[i]; + for (plugin of this.stack) { if (plugin.close) await plugin.close(); } diff --git a/lib/primitives/abstractblock.js b/lib/primitives/abstractblock.js index de48f20e..ef3a8411 100644 --- a/lib/primitives/abstractblock.js +++ b/lib/primitives/abstractblock.js @@ -121,7 +121,7 @@ AbstractBlock.prototype.parseJSON = function parseJSON(json) { */ AbstractBlock.prototype._refresh = function refresh(all) { - var i, tx; + var tx; this._hash = null; this._hhash = null; @@ -134,10 +134,8 @@ AbstractBlock.prototype._refresh = function refresh(all) { if (!this.txs) return; - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) tx.refresh(); - } }; /** diff --git a/lib/primitives/block.js b/lib/primitives/block.js index 3a0c9a3a..29f996d1 100644 --- a/lib/primitives/block.js +++ b/lib/primitives/block.js @@ -54,14 +54,14 @@ util.inherits(Block, AbstractBlock); */ Block.prototype.fromOptions = function fromOptions(options) { - var i; + var tx; this.parseOptions(options); if (options.txs) { assert(Array.isArray(options.txs)); - for (i = 0; i < options.txs.length; i++) - this.addTX(options.txs[i]); + for (tx of options.txs) + this.addTX(tx); } }; @@ -225,13 +225,12 @@ Block.prototype.getBaseSize = function getBaseSize() { */ Block.prototype.hasWitness = function hasWitness() { - var i, tx; + var tx; if (this._witness !== -1) return this._witness !== 0; - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) { if (tx.hasWitness()) return true; } @@ -286,12 +285,10 @@ Block.prototype.indexOf = function indexOf(hash) { Block.prototype.createMerkleRoot = function createMerkleRoot(enc) { var leaves = []; - var i, tx, root, malleated; + var tx, root, malleated; - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) leaves.push(tx.hash()); - } [root, malleated] = merkle.createRoot(leaves); @@ -524,15 +521,13 @@ Block.prototype.getClaimed = function getClaimed() { Block.prototype.getPrevout = function getPrevout() { var prevout = {}; - var i, j, tx, input; + var i, tx, input; for (i = 1; i < this.txs.length; i++) { tx = this.txs[i]; - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + for (input of tx.inputs) prevout[input.prevout.hash] = true; - } } return Object.keys(prevout); diff --git a/lib/primitives/merkleblock.js b/lib/primitives/merkleblock.js index efc40920..a6c2f8d0 100644 --- a/lib/primitives/merkleblock.js +++ b/lib/primitives/merkleblock.js @@ -52,7 +52,7 @@ util.inherits(MerkleBlock, AbstractBlock); */ MerkleBlock.prototype.fromOptions = function fromOptions(options) { - var i, hash; + var hash; this.parseOptions(options); @@ -62,8 +62,7 @@ MerkleBlock.prototype.fromOptions = function fromOptions(options) { assert(util.isUInt32(options.totalTX)); if (options.hashes) { - for (i = 0; i < options.hashes.length; i++) { - hash = options.hashes[i]; + for (hash of options.hashes) { if (typeof hash === 'string') hash = Buffer.from(hash, 'hex'); this.hashes.push(hash); @@ -353,7 +352,7 @@ MerkleBlock.prototype.getSize = function getSize() { */ MerkleBlock.prototype.toWriter = function toWriter(bw) { - var i; + var hash; this.writeAbbr(bw); @@ -361,8 +360,8 @@ MerkleBlock.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.hashes.length); - for (i = 0; i < this.hashes.length; i++) - bw.writeHash(this.hashes[i]); + for (hash of this.hashes) + bw.writeHash(hash); bw.writeVarBytes(this.flags); @@ -482,7 +481,7 @@ MerkleBlock.prototype.getJSON = function getJSON(network, view, height) { */ MerkleBlock.prototype.fromJSON = function fromJSON(json) { - var i, hash; + var hash; assert(json, 'MerkleBlock data is required.'); assert(Array.isArray(json.hashes)); @@ -491,8 +490,8 @@ MerkleBlock.prototype.fromJSON = function fromJSON(json) { this.parseJSON(json); - for (i = 0; i < json.hashes.length; i++) { - hash = util.revHex(json.hashes[i]); + for (hash of json.hashes) { + hash = util.revHex(hash); this.hashes.push(Buffer.from(hash, 'hex')); } @@ -524,12 +523,10 @@ MerkleBlock.fromJSON = function fromJSON(json) { MerkleBlock.fromBlock = function fromBlock(block, filter) { var matches = []; - var i, tx; + var tx; - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + for (tx of block.txs) matches.push(tx.isWatched(filter) ? 1 : 0); - } return MerkleBlock.fromMatches(block, matches); }; @@ -545,17 +542,15 @@ MerkleBlock.fromBlock = function fromBlock(block, filter) { MerkleBlock.fromHashes = function fromHashes(block, hashes) { var filter = {}; var matches = []; - var i, tx, hash; + var tx, hash; - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { if (Buffer.isBuffer(hash)) hash = hash.toString('hex'); filter[hash] = true; } - for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i]; + for (tx of block.txs) { hash = tx.hash('hex'); matches.push(filter[hash] ? 1 : 0); } diff --git a/lib/primitives/mtx.js b/lib/primitives/mtx.js index 9bb891a7..81a1e821 100644 --- a/lib/primitives/mtx.js +++ b/lib/primitives/mtx.js @@ -66,7 +66,7 @@ util.inherits(MTX, TX); */ MTX.prototype.fromOptions = function fromOptions(options) { - var i; + var input, output; if (options.version != null) { assert(util.isUInt32(options.version), 'Version must a be uint32.'); @@ -80,14 +80,14 @@ MTX.prototype.fromOptions = function fromOptions(options) { if (options.inputs) { assert(Array.isArray(options.inputs), 'Inputs must be an array.'); - for (i = 0; i < options.inputs.length; i++) - this.addInput(options.inputs[i]); + for (input of options.inputs) + this.addInput(input); } if (options.outputs) { assert(Array.isArray(options.outputs), 'Outputs must be an array.'); - for (i = 0; i < options.outputs.length; i++) - this.addOutput(options.outputs[i]); + for (output of options.outputs) + this.addOutput(output); } if (options.locktime != null) { @@ -906,11 +906,11 @@ MTX.prototype.isVectorSigned = function isVectorSigned(prev, vector) { MTX.prototype.template = function template(ring) { var total = 0; - var i, input, coin; + var i, key, input, coin; if (Array.isArray(ring)) { - for (i = 0; i < ring.length; i++) - total += this.template(ring[i]); + for (key of ring) + total += this.template(key); return total; } @@ -944,11 +944,11 @@ MTX.prototype.template = function template(ring) { MTX.prototype.sign = function sign(ring, type) { var total = 0; - var i, input, coin; + var i, key, input, coin; if (Array.isArray(ring)) { - for (i = 0; i < ring.length; i++) - total += this.sign(ring[i], type); + for (key of ring) + total += this.sign(key, type); return total; } @@ -999,7 +999,7 @@ MTX.prototype.signAsync = function signAsync(ring, type) { MTX.prototype.estimateSize = async function estimateSize(estimate) { var scale = consensus.WITNESS_SCALE_FACTOR; var total = 0; - var i, input, output, size, prev, coin; + var input, output, size, prev, coin; // Calculate the size, minus the input scripts. total += 4; @@ -1008,16 +1008,13 @@ MTX.prototype.estimateSize = async function estimateSize(estimate) { total += encoding.sizeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) total += output.getSize(); - } total += 4; // Add size for signatures and public keys - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = this.view.getOutput(input); size = 0; @@ -1136,7 +1133,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { */ MTX.prototype.subtractFee = function subtractFee(fee, index) { - var i, min, output; + var min, output; if (typeof index === 'number') { output = this.outputs[index]; @@ -1154,8 +1151,7 @@ MTX.prototype.subtractFee = function subtractFee(fee, index) { return; } - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) { min = fee + output.getDustThreshold(); if (output.value >= min) { @@ -1175,7 +1171,7 @@ MTX.prototype.subtractFee = function subtractFee(fee, index) { */ MTX.prototype.fund = async function fund(coins, options) { - var i, select, change; + var coin, select, change; assert(options, 'Options are required.'); assert(options.changeAddress, 'Change address is required.'); @@ -1185,8 +1181,8 @@ MTX.prototype.fund = async function fund(coins, options) { select = await this.selectCoins(coins, options); // Add coins to transaction. - for (i = 0; i < select.chosen.length; i++) - this.addCoin(select.chosen[i]); + for (coin of select.chosen) + this.addCoin(coin); // Attempt to subtract fee. if (select.shouldSubtract) @@ -1257,13 +1253,12 @@ MTX.prototype.avoidFeeSniping = function avoidFeeSniping(height) { */ MTX.prototype.setLocktime = function setLocktime(locktime) { - var i, input; + var input; assert(util.isUInt32(locktime), 'Locktime must be a uint32.'); assert(this.inputs.length > 0, 'Cannot set sequence with no inputs.'); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { if (input.sequence === 0xffffffff) input.sequence = 0xfffffffe; } diff --git a/lib/primitives/tx.js b/lib/primitives/tx.js index 541f4c6f..c575ab55 100644 --- a/lib/primitives/tx.js +++ b/lib/primitives/tx.js @@ -77,7 +77,7 @@ function TX(options) { */ TX.prototype.fromOptions = function fromOptions(options) { - var i; + var input, output; assert(options, 'TX data is required.'); @@ -93,14 +93,14 @@ TX.prototype.fromOptions = function fromOptions(options) { if (options.inputs) { assert(Array.isArray(options.inputs), 'Inputs must be an array.'); - for (i = 0; i < options.inputs.length; i++) - this.inputs.push(new Input(options.inputs[i])); + for (input of options.inputs) + this.inputs.push(new Input(input)); } if (options.outputs) { assert(Array.isArray(options.outputs), 'Outputs must be an array.'); - for (i = 0; i < options.outputs.length; i++) - this.outputs.push(new Output(options.outputs[i])); + for (output of options.outputs) + this.outputs.push(new Output(output)); } if (options.locktime != null) { @@ -139,20 +139,16 @@ TX.prototype.clone = function clone() { */ TX.prototype.inject = function inject(tx) { - var i, input, output; + var input, output; this.version = tx.version; this.flag = tx.flag; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) this.inputs.push(input.clone()); - } - for (i = 0; i < tx.outputs.length; i++) { - output = tx.outputs[i]; + for (output of tx.outputs) this.outputs.push(output.clone()); - } this.locktime = tx.locktime; @@ -404,13 +400,12 @@ TX.prototype.getBaseSize = function getBaseSize() { */ TX.prototype.hasWitness = function hasWitness() { - var i, input; + var input; if (this._witness !== -1) return this._witness !== 0; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { if (input.witness.items.length > 0) return true; } @@ -551,10 +546,8 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { default: // Regular output serialization if ALL. bw.writeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) output.toWriter(bw); - } break; } @@ -577,7 +570,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { TX.prototype.hashSize = function hashSize(index, prev, type) { var size = 0; - var i, output; + var output; size += 4; @@ -605,10 +598,8 @@ TX.prototype.hashSize = function hashSize(index, prev, type) { break; default: size += encoding.sizeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) size += output.getSize(); - } break; } @@ -631,7 +622,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type var prevouts = encoding.ZERO_HASH; var sequences = encoding.ZERO_HASH; var outputs = encoding.ZERO_HASH; - var i, bw, size, input, output; + var bw, size, input, output; if (!(type & Script.hashType.ANYONECANPAY)) { if (this._hashPrevouts) { @@ -639,10 +630,8 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type } else { bw = new StaticWriter(this.inputs.length * 36); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) input.prevout.toWriter(bw); - } prevouts = digest.hash256(bw.render()); @@ -659,10 +648,8 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type } else { bw = new StaticWriter(this.inputs.length * 4); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) bw.writeU32(input.sequence); - } sequences = digest.hash256(bw.render()); @@ -678,17 +665,13 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type } else { size = 0; - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) size += output.getSize(); - } bw = new StaticWriter(size); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) output.toWriter(bw); - } outputs = digest.hash256(bw.render()); @@ -916,15 +899,13 @@ TX.prototype.isCoinbase = function isCoinbase() { */ TX.prototype.isRBF = function isRBF() { - var i, input; + var input; // Core doesn't do this, but it should: if (this.version === 2) return false; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; - + for (input of this.inputs) { if (input.isRBF()) return true; } @@ -953,10 +934,9 @@ TX.prototype.getFee = function getFee(view) { TX.prototype.getInputValue = function getInputValue(view) { var total = 0; - var i, input, coin; + var input, coin; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -975,12 +955,10 @@ TX.prototype.getInputValue = function getInputValue(view) { TX.prototype.getOutputValue = function getOutputValue() { var total = 0; - var i, output; + var output; - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) total += output.value; - } return total; }; @@ -995,24 +973,23 @@ TX.prototype.getOutputValue = function getOutputValue() { TX.prototype._getInputAddresses = function getInputAddresses(view) { var table = {}; var addrs = []; - var i, address, hash, input, coin; + var addr, hash, input, coin; if (this.isCoinbase()) return [addrs, table]; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view ? view.getOutput(input) : null; - address = input.getAddress(coin); + addr = input.getAddress(coin); - if (!address) + if (!addr) continue; - hash = address.getHash('hex'); + hash = addr.getHash('hex'); if (!table[hash]) { table[hash] = true; - addrs.push(address); + addrs.push(addr); } } @@ -1028,20 +1005,19 @@ TX.prototype._getInputAddresses = function getInputAddresses(view) { TX.prototype._getOutputAddresses = function getOutputAddresses() { var table = {}; var addrs = []; - var i, output, address, hash; + var output, addr, hash; - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; - address = output.getAddress(); + for (output of this.outputs) { + addr = output.getAddress(); - if (!address) + if (!addr) continue; - hash = address.getHash('hex'); + hash = addr.getHash('hex'); if (!table[hash]) { table[hash] = true; - addrs.push(address); + addrs.push(addr); } } @@ -1058,15 +1034,14 @@ TX.prototype._getOutputAddresses = function getOutputAddresses() { TX.prototype._getAddresses = function getAddresses(view) { var [addrs, table] = this._getInputAddresses(view); var output = this.getOutputAddresses(); - var i, address, hash; + var addr, hash; - for (i = 0; i < output.length; i++) { - address = output[i]; - hash = address.getHash('hex'); + for (addr of output) { + hash = addr.getHash('hex'); if (!table[hash]) { table[hash] = true; - addrs.push(address); + addrs.push(addr); } } @@ -1113,19 +1088,17 @@ TX.prototype.getAddresses = function getAddresses(view) { TX.prototype.getInputHashes = function getInputHashes(view, enc) { var hashes = []; - var i, table, input, address; + var table, addrs, addr; if (enc === 'hex') { [, table] = this._getInputAddresses(view); return Object.keys(table); } - input = this.getInputAddresses(view); + addrs = this.getInputAddresses(view); - for (i = 0; i < input.length; i++) { - address = input[i]; - hashes.push(address.getHash()); - } + for (addr of addrs) + hashes.push(addr.getHash()); return hashes; }; @@ -1137,19 +1110,17 @@ TX.prototype.getInputHashes = function getInputHashes(view, enc) { TX.prototype.getOutputHashes = function getOutputHashes(enc) { var hashes = []; - var i, table, output, address; + var table, addrs, addr; if (enc === 'hex') { [, table] = this._getOutputAddresses(); return Object.keys(table); } - output = this.getOutputAddresses(); + addrs = this.getOutputAddresses(); - for (i = 0; i < output.length; i++) { - address = output[i]; - hashes.push(address.getHash()); - } + for (addr of addrs) + hashes.push(addr.getHash()); return hashes; }; @@ -1162,19 +1133,17 @@ TX.prototype.getOutputHashes = function getOutputHashes(enc) { TX.prototype.getHashes = function getHashes(view, enc) { var hashes = []; - var i, table, result, address; + var table, addrs, addr; if (enc === 'hex') { [, table] = this._getAddresses(view); return Object.keys(table); } - result = this.getAddresses(view); + addrs = this.getAddresses(view); - for (i = 0; i < result.length; i++) { - address = result[i]; - hashes.push(address.getHash()); - } + for (addr of addrs) + hashes.push(addr.getHash()); return hashes; }; @@ -1187,13 +1156,12 @@ TX.prototype.getHashes = function getHashes(view, enc) { */ TX.prototype.hasCoins = function hasCoins(view) { - var i, input; + var input; if (this.inputs.length === 0) return false; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { if (!view.hasEntry(input)) return false; } @@ -1219,7 +1187,7 @@ TX.prototype.hasCoins = function hasCoins(view) { TX.prototype.isFinal = function isFinal(height, ts) { var THRESHOLD = consensus.LOCKTIME_THRESHOLD; - var i, input; + var input; if (this.locktime === 0) return true; @@ -1227,8 +1195,7 @@ TX.prototype.isFinal = function isFinal(height, ts) { if (this.locktime < (this.locktime < THRESHOLD ? height : ts)) return true; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { if (input.sequence !== 0xffffffff) return false; } @@ -1314,17 +1281,13 @@ TX.prototype.verifySequence = function verifySequence(index, locktime) { TX.prototype.getLegacySigops = function getLegacySigops() { var total = 0; - var i, input, output; + var input, output; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) total += input.script.getSigops(false); - } - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) total += output.script.getSigops(false); - } return total; }; @@ -1337,13 +1300,12 @@ TX.prototype.getLegacySigops = function getLegacySigops() { TX.prototype.getScripthashSigops = function getScripthashSigops(view) { var total = 0; - var i, input, coin; + var input, coin; if (this.isCoinbase()) return 0; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -1368,7 +1330,7 @@ TX.prototype.getScripthashSigops = function getScripthashSigops(view) { TX.prototype.getSigopsCost = function getSigopsCost(view, flags) { var scale = consensus.WITNESS_SCALE_FACTOR; var cost = this.getLegacySigops() * scale; - var i, input, coin; + var input, coin; if (flags == null) flags = Script.flags.STANDARD_VERIFY_FLAGS; @@ -1382,8 +1344,7 @@ TX.prototype.getSigopsCost = function getSigopsCost(view, flags) { if ((flags & Script.flags.VERIFY_WITNESS) === 0) return cost; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -1429,7 +1390,7 @@ TX.prototype.isSane = function isSane() { TX.prototype.checkSanity = function checkSanity() { var prevout = {}; var total = 0; - var i, input, output, size, key; + var input, output, size, key; if (this.inputs.length === 0) return [false, 'bad-txns-vin-empty', 100]; @@ -1440,9 +1401,7 @@ TX.prototype.checkSanity = function checkSanity() { if (this.getBaseSize() > consensus.MAX_BLOCK_SIZE) return [false, 'bad-txns-oversize', 100]; - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; - + for (output of this.outputs) { if (output.value < 0) return [false, 'bad-txns-vout-negative', 100]; @@ -1455,8 +1414,7 @@ TX.prototype.checkSanity = function checkSanity() { return [false, 'bad-txns-txouttotal-toolarge', 100]; } - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { key = input.prevout.toKey(); if (prevout[key]) return [false, 'bad-txns-inputs-duplicate', 100]; @@ -1468,8 +1426,7 @@ TX.prototype.checkSanity = function checkSanity() { if (size < 2 || size > 100) return [false, 'bad-cb-length', 100]; } else { - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { if (input.prevout.isNull()) return [false, 'bad-txns-prevout-null', 10]; } @@ -1504,7 +1461,7 @@ TX.prototype.isStandard = function isStandard() { */ TX.prototype.checkStandard = function checkStandard() { - var i, input, output; + var input, output; var nulldata = 0; if (this.version < 1 || this.version > policy.MAX_TX_VERSION) @@ -1514,9 +1471,7 @@ TX.prototype.checkStandard = function checkStandard() { return [false, 'tx-size', 0]; } - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; - + for (input of this.inputs) { if (input.script.getSize() > 1650) return [false, 'scriptsig-size', 0]; @@ -1524,9 +1479,7 @@ TX.prototype.checkStandard = function checkStandard() { return [false, 'scriptsig-not-pushonly', 0]; } - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; - + for (output of this.outputs) { if (!output.script.isStandard()) return [false, 'scriptpubkey', 0]; @@ -1558,13 +1511,12 @@ TX.prototype.checkStandard = function checkStandard() { */ TX.prototype.hasStandardInputs = function hasStandardInputs(view) { - var i, input, coin, redeem; + var input, coin, redeem; if (this.isCoinbase()) return true; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -1600,13 +1552,12 @@ TX.prototype.hasStandardInputs = function hasStandardInputs(view) { */ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { - var i, j, input, witness, coin, prev, redeem, m; + var i, input, witness, coin, prev, redeem, m; if (this.isCoinbase()) return true; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { witness = input.witness; coin = view.getOutput(input); @@ -1644,8 +1595,8 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { if (witness.items.length - 1 > policy.MAX_P2WSH_STACK) return false; - for (j = 0; j < witness.items.length - 1; j++) { - if (witness.items[j].length > policy.MAX_P2WSH_PUSH) + for (i = 0; i < witness.items.length - 1; i++) { + if (witness.items[i].length > policy.MAX_P2WSH_PUSH) return false; } @@ -1688,8 +1639,8 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { if (witness.items[0].length !== 0) return false; - for (j = 1; j < witness.items.length - 1; j++) { - if (witness.items[j].length > 73) + for (i = 1; i < witness.items.length - 1; i++) { + if (witness.items[i].length > 73) return false; } } @@ -1700,8 +1651,8 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { if (witness.items.length > policy.MAX_P2WSH_STACK) return false; - for (j = 0; j < witness.items.length; j++) { - if (witness.items[j].length > policy.MAX_P2WSH_PUSH) + for (i = 0; i < witness.items.length; i++) { + if (witness.items[i].length > policy.MAX_P2WSH_PUSH) return false; } } @@ -1742,12 +1693,11 @@ TX.prototype.checkInputs = function checkInputs(view, height) { TX.prototype.checkContext = function checkContext(view, height) { var total = 0; - var i, input, coins, coin, fee, value; + var input, coins, coin, fee, value; assert(typeof height === 'number'); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coins = view.get(input.prevout.hash); if (!coins) @@ -1798,13 +1748,12 @@ TX.prototype.checkContext = function checkContext(view, height) { */ TX.prototype.getModifiedSize = function getModifiedSize(size) { - var i, input, offset; + var input, offset; if (size == null) size = this.getVirtualSize(); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { offset = 41 + Math.min(110, input.script.getSize()); if (size > offset) size -= offset; @@ -1824,7 +1773,7 @@ TX.prototype.getModifiedSize = function getModifiedSize(size) { TX.prototype.getPriority = function getPriority(view, height, size) { var sum = 0; - var i, input, age, coin, coinHeight; + var input, age, coin, coinHeight; assert(typeof height === 'number', 'Must pass in height.'); @@ -1834,8 +1783,7 @@ TX.prototype.getPriority = function getPriority(view, height, size) { if (size == null) size = this.getVirtualSize(); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -1863,13 +1811,12 @@ TX.prototype.getPriority = function getPriority(view, height, size) { TX.prototype.getChainValue = function getChainValue(view) { var value = 0; - var i, input, coin, coinHeight; + var input, coin, coinHeight; if (this.isCoinbase()) return value; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { coin = view.getOutput(input); if (!coin) @@ -1964,15 +1911,13 @@ TX.prototype.getRate = function getRate(view, size) { TX.prototype.getPrevout = function getPrevout() { var prevout = {}; - var i, input; + var input; if (this.isCoinbase()) return []; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) prevout[input.prevout.hash] = true; - } return Object.keys(prevout); }; @@ -2020,8 +1965,7 @@ TX.prototype.isWatched = function isWatched(filter) { // 3. Test prev_out structure // 4. Test data elements in input scripts - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { prevout = input.prevout; // Test the COutPoint structure @@ -2234,7 +2178,7 @@ TX.prototype.getJSON = function getJSON(network, view, entry, index) { */ TX.prototype.fromJSON = function fromJSON(json) { - var i, input, output; + var input, output; assert(json, 'TX data is required.'); assert(util.isUInt32(json.version), 'Version must be a uint32.'); @@ -2246,15 +2190,11 @@ TX.prototype.fromJSON = function fromJSON(json) { this.version = json.version; this.flag = json.flag; - for (i = 0; i < json.inputs.length; i++) { - input = json.inputs[i]; + for (input of json.inputs) this.inputs.push(Input.fromJSON(input)); - } - for (i = 0; i < json.outputs.length; i++) { - output = json.outputs[i]; + for (output of json.outputs) this.outputs.push(Output.fromJSON(output)); - } this.locktime = json.locktime; @@ -2384,8 +2324,7 @@ TX.prototype.fromWitnessReader = function fromWitnessReader(br) { witness = br.offset; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { input.witness.fromReader(br); if (input.witness.items.length > 0) hasWitness = true; @@ -2453,7 +2392,7 @@ TX.prototype.frameWitness = function frameWitness() { */ TX.prototype.writeNormal = function writeNormal(bw) { - var i, input, output; + var input, output; if (this.inputs.length === 0 && this.outputs.length !== 0) throw new Error('Cannot serialize zero-input tx.'); @@ -2462,17 +2401,13 @@ TX.prototype.writeNormal = function writeNormal(bw) { bw.writeVarint(this.inputs.length); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) input.toWriter(bw); - } bw.writeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) output.toWriter(bw); - } bw.writeU32(this.locktime); @@ -2488,7 +2423,7 @@ TX.prototype.writeNormal = function writeNormal(bw) { */ TX.prototype.writeWitness = function writeWitness(bw) { - var i, witness, input, output; + var witness, input, output; if (this.inputs.length === 0 && this.outputs.length !== 0) throw new Error('Cannot serialize zero-input tx.'); @@ -2499,24 +2434,18 @@ TX.prototype.writeWitness = function writeWitness(bw) { bw.writeVarint(this.inputs.length); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) input.toWriter(bw); - } bw.writeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) output.toWriter(bw); - } witness = bw.written; - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) input.witness.toWriter(bw); - } witness = bw.written - witness; @@ -2536,23 +2465,19 @@ TX.prototype.writeWitness = function writeWitness(bw) { TX.prototype.getNormalSizes = function getNormalSizes() { var base = 0; - var i, input, output; + var input, output; base += 4; base += encoding.sizeVarint(this.inputs.length); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) base += input.getSize(); - } base += encoding.sizeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) base += output.getSize(); - } base += 4; @@ -2568,25 +2493,22 @@ TX.prototype.getNormalSizes = function getNormalSizes() { TX.prototype.getWitnessSizes = function getWitnessSizes() { var base = 0; var witness = 0; - var i, input, output; + var input, output; base += 4; witness += 2; base += encoding.sizeVarint(this.inputs.length); - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + for (input of this.inputs) { base += input.getSize(); witness += input.witness.getVarSize(); } base += encoding.sizeVarint(this.outputs.length); - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) base += output.getSize(); - } base += 4; diff --git a/lib/protocol/network.js b/lib/protocol/network.js index d987f53b..6366d0b8 100644 --- a/lib/protocol/network.js +++ b/lib/protocol/network.js @@ -90,12 +90,10 @@ Network.simnet = null; Network.prototype._init = function _init() { var bits = 0; - var i, deployment, keys, key, hash, height; + var deployment, keys, key, hash, height; - for (i = 0; i < this.deploys.length; i++) { - deployment = this.deploys[i]; + for (deployment of this.deploys) bits |= 1 << deployment.bit; - } bits |= consensus.VERSION_TOP_MASK; @@ -103,8 +101,7 @@ Network.prototype._init = function _init() { keys = Object.keys(this.checkpointMap); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { hash = this.checkpointMap[key]; height = +key; @@ -244,7 +241,7 @@ Network.ensure = function ensure(type) { */ Network.by = function by(value, compare, network, name) { - var i, type; + var type; if (network) { network = Network.get(network); @@ -253,8 +250,7 @@ Network.by = function by(value, compare, network, name) { throw new Error('Network mismatch for ' + name + '.'); } - for (i = 0; i < networks.types.length; i++) { - type = networks.types[i]; + for (type of networks.types) { network = networks[type]; if (compare(network, value)) return Network.get(type); diff --git a/lib/protocol/timedata.js b/lib/protocol/timedata.js index 64256a23..4e5969c0 100644 --- a/lib/protocol/timedata.js +++ b/lib/protocol/timedata.js @@ -50,7 +50,7 @@ util.inherits(TimeData, EventEmitter); TimeData.prototype.add = function add(id, time) { var sample = time - util.now(); - var i, median, match, offset; + var median, match, offset; if (this.samples.length >= this.limit) return; @@ -73,8 +73,7 @@ TimeData.prototype.add = function add(id, time) { this.offset = 0; if (!this._checked) { match = false; - for (i = 0; i < this.samples.length; i++) { - offset = this.samples[i]; + for (offset of this.samples) { if (offset !== 0 && Math.abs(offset) < 5 * 60) { match = true; break; diff --git a/lib/script/common.js b/lib/script/common.js index e1fec33c..132f6a0a 100644 --- a/lib/script/common.js +++ b/lib/script/common.js @@ -542,10 +542,10 @@ exports.isSignatureEncoding = function isSignatureEncoding(sig) { exports.formatStack = function formatStack(items) { var out = []; - var i; + var item; - for (i = 0; i < items.length; i++) - out.push(items[i].toString('hex')); + for (item of items) + out.push(item.toString('hex')); return out.join(' '); }; @@ -558,10 +558,9 @@ exports.formatStack = function formatStack(items) { exports.formatCode = function formatCode(code) { var out = []; - var i, op, data, value, size; + var op, data, value, size; - for (i = 0; i < code.length; i++) { - op = code[i]; + for (op of code) { data = op.data; value = op.value; @@ -653,13 +652,12 @@ exports.formatItem = function formatItem(data, decode) { exports.formatASM = function formatASM(code, decode) { var out = []; - var i, op, data, value; + var op, data, value; if (code.length > 0 && code[0].value === exports.opcodes.OP_RETURN) decode = false; - for (i = 0; i < code.length; i++) { - op = code[i]; + for (op of code) { data = op.data; value = op.value; @@ -691,10 +689,9 @@ exports.formatASM = function formatASM(code, decode) { exports.formatStackASM = function formatStackASM(items, decode) { var out = []; - var i, item, data; + var item, data; - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { data = exports.formatItem(item, decode); out.push(data); } diff --git a/lib/script/script.js b/lib/script/script.js index 78fc7947..e227bcd4 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -180,12 +180,10 @@ Script.fromOptions = function fromOptions(options) { Script.prototype.toArray = function toArray() { var code = []; - var i, op; + var op; - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + for (op of this.code) code.push(op.data || op.value); - } return code; }; @@ -199,7 +197,7 @@ Script.prototype.toArray = function toArray() { */ Script.prototype.fromArray = function fromArray(code) { - var i, op; + var op; assert(Array.isArray(code)); @@ -209,8 +207,7 @@ Script.prototype.fromArray = function fromArray(code) { if (code[0] instanceof Opcode) return this.fromCode(code); - for (i = 0; i < code.length; i++) { - op = code[i]; + for (op of code) { if (Buffer.isBuffer(op)) { this.code.push(Opcode.fromData(op)); continue; @@ -336,12 +333,10 @@ Script.prototype.toASM = function toASM(decode) { Script.prototype.getCodeSize = function getCodeSize() { var size = 0; - var i, op; + var op; - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + for (op of this.code) size += op.getSize(); - } return size; }; @@ -354,12 +349,10 @@ Script.prototype.getCodeSize = function getCodeSize() { Script.prototype.compile = function compile() { var size = this.getCodeSize(); var bw = new StaticWriter(size); - var i, op; + var op; - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + for (op of this.code) op.toWriter(bw); - } this.raw = bw.render(); @@ -451,13 +444,11 @@ Script.prototype.getSubscript = function getSubscript(lastSep) { Script.prototype.removeSeparators = function removeSeparators() { var found = false; - var i, op, code; + var op, code; // Optimizing for the common case: // Check for any separators first. - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; - + for (op of this.code) { if (op.value === -1) break; @@ -475,9 +466,7 @@ Script.prototype.removeSeparators = function removeSeparators() { // and remove them all. code = []; - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; - + for (op of this.code) { if (op.value === -1) break; @@ -1396,11 +1385,9 @@ Script.prototype.indexOf = function indexOf(data) { */ Script.prototype.isCode = function isCode() { - var i, op; - - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + var op; + for (op of this.code) { if (op.data) continue; @@ -1493,7 +1480,7 @@ Script.fromPubkeyhash = function fromPubkeyhash(hash) { */ Script.prototype.fromMultisig = function fromMultisig(m, n, keys) { - var i; + var key; assert(util.isNumber(m) && util.isNumber(n)); assert(Array.isArray(keys)); @@ -1505,8 +1492,8 @@ Script.prototype.fromMultisig = function fromMultisig(m, n, keys) { this.push(Opcode.fromSmall(m)); - for (i = 0; i < keys.length; i++) - this.push(keys[i]); + for (key of keys) + this.push(key); this.push(Opcode.fromSmall(n)); this.push(opcodes.OP_CHECKMULTISIG); @@ -2362,11 +2349,9 @@ Script.getCoinbaseHeight = function getCoinbaseHeight(raw) { */ Script.prototype.test = function test(filter) { - var i, op; - - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + var op; + for (op of this.code) { if (op.value === -1) break; @@ -2566,11 +2551,9 @@ Script.isSignature = function isSignature(sig) { */ Script.prototype.isPushOnly = function isPushOnly() { - var i, op; - - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + var op; + for (op of this.code) { if (op.data) continue; @@ -2594,11 +2577,9 @@ Script.prototype.isPushOnly = function isPushOnly() { Script.prototype.getSigops = function getSigops(accurate) { var total = 0; var lastOp = -1; - var i, op; - - for (i = 0; i < this.code.length; i++) { - op = this.code[i]; + var op; + for (op of this.code) { if (op.data) continue; @@ -2632,7 +2613,7 @@ Script.prototype.getSigops = function getSigops(accurate) { */ Script.prototype.getScripthashSigops = function getScripthashSigops(input) { - var i, op, redeem; + var op, redeem; if (!this.isScripthash()) return this.getSigops(true); @@ -2640,9 +2621,7 @@ Script.prototype.getScripthashSigops = function getScripthashSigops(input) { if (input.code.length === 0) return 0; - for (i = 0; i < input.code.length; i++) { - op = input.code[i]; - + for (op of input.code) { if (op.data) continue; @@ -2721,7 +2700,7 @@ Script.prototype.getWitnessSigops = function getWitnessSigops(input, witness) { */ Script.prototype.fromString = function fromString(code) { - var i, op, symbol, bw; + var op, symbol, bw; assert(typeof code === 'string'); @@ -2734,8 +2713,7 @@ Script.prototype.fromString = function fromString(code) { bw = new BufferWriter(); - for (i = 0; i < code.length; i++) { - op = code[i]; + for (op of code) { symbol = op; if (!util.isUpperCase(symbol)) diff --git a/lib/script/witness.js b/lib/script/witness.js index 8f3051db..9c413563 100644 --- a/lib/script/witness.js +++ b/lib/script/witness.js @@ -278,15 +278,13 @@ Witness.prototype.isUnknownInput = function isUnknownInput() { */ Witness.prototype.test = function test(filter) { - var i, chunk; + var item; - for (i = 0; i < this.items.length; i++) { - chunk = this.items[i]; - - if (chunk.length === 0) + for (item of this.items) { + if (item.length === 0) continue; - if (filter.test(chunk)) + if (filter.test(item)) return true; } @@ -338,12 +336,10 @@ Witness.prototype.indexOf = function indexOf(data) { Witness.prototype.getSize = function getSize() { var size = 0; - var i, item; + var item; - for (i = 0; i < this.items.length; i++) { - item = this.items[i]; + for (item of this.items) size += encoding.sizeVarBytes(item); - } return size; }; @@ -364,12 +360,12 @@ Witness.prototype.getVarSize = function getVarSize() { */ Witness.prototype.toWriter = function toWriter(bw) { - var i; + var item; bw.writeVarint(this.items.length); - for (i = 0; i < this.items.length; i++) - bw.writeVarBytes(this.items[i]); + for (item of this.items) + bw.writeVarBytes(item); return bw; }; @@ -633,7 +629,7 @@ Witness.fromRaw = function fromRaw(data, enc) { */ Witness.prototype.fromString = function fromString(items) { - var i; + var item; if (!Array.isArray(items)) { assert(typeof items === 'string'); @@ -646,8 +642,8 @@ Witness.prototype.fromString = function fromString(items) { items = items.split(/\s+/); } - for (i = 0; i < items.length; i++) - this.items.push(Buffer.from(items[i], 'hex')); + for (item of items) + this.items.push(Buffer.from(item, 'hex')); return this; }; diff --git a/lib/utils/asyncemitter.js b/lib/utils/asyncemitter.js index ce63f5eb..ee1f6711 100644 --- a/lib/utils/asyncemitter.js +++ b/lib/utils/asyncemitter.js @@ -179,7 +179,7 @@ AsyncEmitter.prototype.removeAllListeners = function removeAllListeners(type) { */ AsyncEmitter.prototype.listeners = function listeners(type) { - var i, listeners, listener; + var listeners, listener; var result = []; assert(typeof type === 'string', '`type` must be a string.'); @@ -189,10 +189,8 @@ AsyncEmitter.prototype.listeners = function listeners(type) { if (!listeners) return result; - for (i = 0; i < listeners.length; i++) { - listener = listeners[i]; + for (listener of listeners) result.push(listener.handler); - } return result; }; diff --git a/lib/utils/asyncobject.js b/lib/utils/asyncobject.js index bad401be..eeae8903 100644 --- a/lib/utils/asyncobject.js +++ b/lib/utils/asyncobject.js @@ -190,7 +190,7 @@ AsyncObject.prototype.fire = async function fire() { */ AsyncObject.prototype.fireHook = async function fireHook(type) { - var i, j, listeners, args, handler; + var i, listeners, args, handler; assert(typeof type === 'string', '`type` must be a string.'); @@ -199,9 +199,7 @@ AsyncObject.prototype.fireHook = async function fireHook(type) { if (!listeners || listeners.length === 0) return; - for (i = 0; i < listeners.length; i++) { - handler = listeners[i]; - + for (handler of listeners) { switch (arguments.length) { case 1: await handler(); @@ -218,8 +216,8 @@ AsyncObject.prototype.fireHook = async function fireHook(type) { default: if (!args) { args = new Array(arguments.length - 1); - for (j = 1; j < arguments.length; j++) - args[j - 1] = arguments[j]; + for (i = 1; i < arguments.length; i++) + args[i - 1] = arguments[i]; } await handler.apply(null, args); break; diff --git a/lib/utils/fs.js b/lib/utils/fs.js index dc36265a..b96d8a8f 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -86,13 +86,13 @@ exports.writeFileSync = fs.writeFileSync; exports.mkdirpSync = function mkdirpSync(dir, mode) { var [path, parts] = getParts(dir); - var i, stat; + var part, stat; if (mode == null) mode = 0o750; - for (i = 0; i < parts.length; i++) { - path += parts[i]; + for (part of parts) { + path += part; try { stat = exports.statSync(path); @@ -111,13 +111,13 @@ exports.mkdirpSync = function mkdirpSync(dir, mode) { exports.mkdirp = async function mkdirp(dir, mode) { var [path, parts] = getParts(dir); - var i, stat; + var part, stat; if (mode == null) mode = 0o750; - for (i = 0; i < parts.length; i++) { - path += parts[i]; + for (part of parts) { + path += part; try { stat = await exports.stat(path); diff --git a/lib/utils/gcs.js b/lib/utils/gcs.js index 0235bd85..e0fbe876 100644 --- a/lib/utils/gcs.js +++ b/lib/utils/gcs.js @@ -71,8 +71,7 @@ GCSFilter.prototype.matchAny = function matchAny(key, items) { assert(items.length > 0); - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { hash = siphash(item, key).imod(this.m); values.push(hash); } @@ -166,7 +165,7 @@ GCSFilter.prototype.fromItems = function fromItems(P, key, items) { var bw = new BitWriter(); var last = new Int64(0); var values = []; - var i, item, hash, value, rem; + var item, hash, value, rem; assert(typeof P === 'number' && isFinite(P)); assert(P >= 0 && P <= 32); @@ -182,8 +181,7 @@ GCSFilter.prototype.fromItems = function fromItems(P, key, items) { this.p = P; this.m = Int64(this.n).ishln(this.p); - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { assert(Buffer.isBuffer(item)); hash = siphash(item, key).imod(this.m); values.push(hash); @@ -191,8 +189,7 @@ GCSFilter.prototype.fromItems = function fromItems(P, key, items) { values.sort(compare); - for (i = 0; i < values.length; i++) { - hash = values[i]; + for (hash of values) { rem = hash.sub(last).imaskn(this.p); value = hash.sub(last).isub(rem).ishrn(this.p); last = hash; @@ -270,22 +267,18 @@ GCSFilter.prototype.fromBlock = function fromBlock(block) { var hash = block.hash(); var key = hash.slice(0, 16); var items = []; - var i, j, tx, input, output; + var i, tx, input, output; for (i = 0; i < block.txs.length; i++) { tx = block.txs[i]; if (i > 0) { - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + for (input of tx.inputs) items.push(input.prevout.toRaw()); - } } - for (j = 0; j < tx.outputs.length; j++) { - output = tx.outputs[j]; + for (output of tx.outputs) getPushes(items, output.script); - } } return this.fromItems(20, key, items); @@ -295,7 +288,7 @@ GCSFilter.prototype.fromExtended = function fromExtended(block) { var hash = block.hash(); var key = hash.slice(0, 16); var items = []; - var i, j, tx, input; + var i, tx, input; for (i = 0; i < block.txs.length; i++) { tx = block.txs[i]; @@ -303,8 +296,7 @@ GCSFilter.prototype.fromExtended = function fromExtended(block) { items.push(tx.hash()); if (i > 0) { - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + for (input of tx.inputs) { getWitness(items, input.witness); getPushes(items, input.script); } @@ -548,11 +540,9 @@ function siphash(data, key) { } function getPushes(items, script) { - var i, op; - - for (i = 0; i < script.code.length; i++) { - op = script.code[i]; + var op; + for (op of script.code) { if (!op.data || op.data.length === 0) continue; @@ -561,15 +551,13 @@ function getPushes(items, script) { } function getWitness(items, witness) { - var i, data; + var item; - for (i = 0; i < witness.items.length; i++) { - data = witness.items[i]; - - if (data.length === 0) + for (item of witness.items) { + if (item.length === 0) continue; - items.push(data); + items.push(item); } } diff --git a/lib/utils/ip.js b/lib/utils/ip.js index 979396de..3462194e 100644 --- a/lib/utils/ip.js +++ b/lib/utils/ip.js @@ -308,12 +308,11 @@ IP.toBuffer = function toBuffer(str) { IP.parseV4 = function parseV4(str, raw, offset) { var parts = str.split('.'); - var i, ch; + var ch; assert(parts.length === 4); - for (i = 0; i < parts.length; i++) { - ch = parts[i]; + for (ch of parts) { assert(ch.length > 0); assert(ch.length <= 3); ch = parseInt(ch, 10); @@ -342,8 +341,7 @@ IP.parseV6 = function parseV6(str, raw, offset) { assert(parts.length >= 2, 'Not an IPv6 address.'); - for (i = 0; i < parts.length; i++) { - word = parts[i]; + for (word of parts) { if (IP.isV4String(word)) missing--; } @@ -993,15 +991,12 @@ IP.getInterfaces = function _getInterfaces(name, family) { var interfaces = os.networkInterfaces(); var keys = Object.keys(interfaces); var result = []; - var i, j, key, items, details, type, raw; + var key, items, details, type, raw; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { items = interfaces[key]; - for (j = 0; j < items.length; j++) { - details = items[j]; - + for (details of items) { type = details.family.toLowerCase(); if (family && type !== family) diff --git a/lib/utils/lock.js b/lib/utils/lock.js index 58931658..c72351a8 100644 --- a/lib/utils/lock.js +++ b/lib/utils/lock.js @@ -159,7 +159,7 @@ Lock.prototype.unlock = function unlock() { Lock.prototype.destroy = function destroy() { var err = new Error('Lock was destroyed.'); - var i, jobs, job; + var jobs, job; assert(!this.destroyed, 'Lock is already destroyed.'); @@ -172,10 +172,8 @@ Lock.prototype.destroy = function destroy() { this.map = Object.create(null); this.current = null; - for (i = 0; i < jobs.length; i++) { - job = jobs[i]; + for (job of jobs) job.reject(err); - } }; /** diff --git a/lib/utils/lru.js b/lib/utils/lru.js index ac91848d..8755a6f8 100644 --- a/lib/utils/lru.js +++ b/lib/utils/lru.js @@ -480,10 +480,9 @@ LRUBatch.prototype.clear = function clear() { */ LRUBatch.prototype.commit = function commit() { - var i, op; + var op; - for (i = 0; i < this.ops.length; i++) { - op = this.ops[i]; + for (op of this.ops) { if (op.remove) { this.lru.remove(op.key); continue; diff --git a/lib/utils/util.js b/lib/utils/util.js index c113f5b3..d4ffd23f 100644 --- a/lib/utils/util.js +++ b/lib/utils/util.js @@ -526,23 +526,21 @@ util.inherits = function inherits(child, parent) { /** * Find index of a buffer in an array of buffers. - * @param {Buffer[]} obj + * @param {Buffer[]} items * @param {Buffer} data - Target buffer to find. * @returns {Number} Index (-1 if not found). */ -util.indexOf = function indexOf(obj, data) { - var i, chunk; +util.indexOf = function indexOf(items, data) { + var i, item; - assert(Array.isArray(obj)); + assert(Array.isArray(items)); assert(Buffer.isBuffer(data)); - for (i = 0; i < obj.length; i++) { - chunk = obj[i]; - - assert(Buffer.isBuffer(chunk)); - - if (chunk.equals(data)) + for (i = 0; i < items.length; i++) { + item = items[i]; + assert(Buffer.isBuffer(item)); + if (item.equals(data)) return i; } @@ -660,18 +658,16 @@ util.hex32 = function hex32(num) { /** * Convert an array to a map. - * @param {String[]} obj + * @param {String[]} items * @returns {Object} Map. */ -util.toMap = function toMap(obj) { +util.toMap = function toMap(items) { var map = {}; - var i, value; + var value; - for (i = 0; i < obj.length; i++) { - value = obj[i]; + for (value of items) map[value] = true; - } return map; }; @@ -685,12 +681,10 @@ util.toMap = function toMap(obj) { util.revMap = function revMap(map) { var reversed = {}; var keys = Object.keys(map); - var i, key; + var key; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) reversed[map[key]] = key; - } return reversed; }; @@ -704,12 +698,10 @@ util.revMap = function revMap(map) { util.values = function values(map) { var keys = Object.keys(map); var out = []; - var i, key; + var key; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) out.push(map[key]); - } return out; }; diff --git a/lib/utils/validator.js b/lib/utils/validator.js index 77b913a8..047bb66a 100644 --- a/lib/utils/validator.js +++ b/lib/utils/validator.js @@ -47,13 +47,12 @@ Validator.prototype.init = function init(data) { */ Validator.prototype.has = function has(key) { - var i, map, value; + var map, value; assert(typeof key === 'string' || typeof key === 'number', 'Key must be a string.'); - for (i = 0; i < this.data.length; i++) { - map = this.data[i]; + for (map of this.data) { value = map[key]; if (value != null) return true; @@ -70,15 +69,14 @@ Validator.prototype.has = function has(key) { */ Validator.prototype.get = function get(key, fallback) { - var i, keys, value, map; + var keys, value, map; if (fallback === undefined) fallback = null; if (Array.isArray(key)) { keys = key; - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { value = this.get(key); if (value !== null) return value; @@ -89,9 +87,7 @@ Validator.prototype.get = function get(key, fallback) { assert(typeof key === 'string' || typeof key === 'number', 'Key must be a string.'); - for (i = 0; i < this.data.length; i++) { - map = this.data[i]; - + for (map of this.data) { if (!map || typeof map !== 'object') throw new ValidationError('Data is not an object.'); @@ -515,7 +511,7 @@ Validator.prototype.buf = function buf(key, fallback, enc) { Validator.prototype.array = function array(key, fallback) { var value = this.get(key); - var i, result, parts, part; + var result, parts, part; if (fallback === undefined) fallback = null; @@ -532,9 +528,7 @@ Validator.prototype.array = function array(key, fallback) { parts = value.trim().split(/\s*,\s*/); result = []; - for (i = 0; i < parts.length; i++) { - part = parts[i]; - + for (part of parts) { if (part.length === 0) continue; diff --git a/lib/utils/writer.js b/lib/utils/writer.js index c9d8c709..89298c7b 100644 --- a/lib/utils/writer.js +++ b/lib/utils/writer.js @@ -72,10 +72,9 @@ function BufferWriter() { BufferWriter.prototype.render = function render(keep) { var data = Buffer.allocUnsafe(this.written); var off = 0; - var i, op; + var op; - for (i = 0; i < this.ops.length; i++) { - op = this.ops[i]; + for (op of this.ops) { switch (op.type) { case SEEK: off += op.value; break; case UI8: off = data.writeUInt8(op.value, off, true); break; diff --git a/lib/wallet/account.js b/lib/wallet/account.js index 03053143..0ced4a20 100644 --- a/lib/wallet/account.js +++ b/lib/wallet/account.js @@ -104,7 +104,7 @@ Account.typesByVal = { */ Account.prototype.fromOptions = function fromOptions(options) { - var i; + var key; assert(options, 'Options are required.'); assert(util.isNumber(options.wid)); @@ -196,8 +196,8 @@ Account.prototype.fromOptions = function fromOptions(options) { if (options.keys) { assert(Array.isArray(options.keys)); - for (i = 0; i < options.keys.length; i++) - this.pushKey(options.keys[i]); + for (key of options.keys) + this.pushKey(key); } return this; @@ -539,7 +539,7 @@ Account.prototype.derivePath = function derivePath(path, master) { Account.prototype.deriveKey = function deriveKey(branch, index, master) { var keys = []; - var i, key, shared, ring; + var key, shared, ring; assert(typeof branch === 'number'); @@ -558,8 +558,7 @@ Account.prototype.deriveKey = function deriveKey(branch, index, master) { case Account.types.MULTISIG: keys.push(key.publicKey); - for (i = 0; i < this.keys.length; i++) { - shared = this.keys[i]; + for (shared of this.keys) { shared = shared.derive(branch).derive(index); keys.push(shared.publicKey); } @@ -926,7 +925,7 @@ Account.prototype.getSize = function getSize() { Account.prototype.toRaw = function toRaw() { var size = this.getSize(); var bw = new StaticWriter(size); - var i, key; + var key; bw.writeVarString(this.name, 'ascii'); bw.writeU8(this.initialized ? 1 : 0); @@ -942,10 +941,8 @@ Account.prototype.toRaw = function toRaw() { bw.writeBytes(this.accountKey.toRaw()); bw.writeU8(this.keys.length); - for (i = 0; i < this.keys.length; i++) { - key = this.keys[i]; + for (key of this.keys) bw.writeBytes(key.toRaw()); - } return bw.render(); }; diff --git a/lib/wallet/client.js b/lib/wallet/client.js index ca0d8290..5464b680 100644 --- a/lib/wallet/client.js +++ b/lib/wallet/client.js @@ -272,13 +272,13 @@ WalletClient.prototype.setFilter = function setFilter(filter) { WalletClient.prototype.addFilter = function addFilter(chunks) { var self = this; var out = []; - var i; + var chunk; if (!Array.isArray(chunks)) chunks = [chunks]; - for (i = 0; i < chunks.length; i++) - out.push(chunks[i]); + for (chunk of chunks) + out.push(chunk); return new Promise(function(resolve, reject) { self.socket.emit('add filter', out, wrap(resolve, reject)); @@ -352,10 +352,9 @@ function parseEntry(data, enc) { function parseBlock(entry, txs) { var block = parseEntry(entry); var out = []; - var i, tx; + var tx; - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) { tx = parseTX(tx); out.push(tx); } diff --git a/lib/wallet/common.js b/lib/wallet/common.js index 6445b56c..e9f6594c 100644 --- a/lib/wallet/common.js +++ b/lib/wallet/common.js @@ -85,28 +85,22 @@ common.sortDeps = function sortDeps(txs) { var count = {}; var result = []; var top = []; - var map = txs; - var i, j, tx, hash, input; + var map = {}; + var tx, hash, input; var prev, hasDeps, deps; - if (Array.isArray(txs)) { - map = {}; - for (i = 0; i < txs.length; i++) { - tx = txs[i]; - hash = tx.hash('hex'); - map[hash] = tx; - } + for (tx of txs) { + hash = tx.hash('hex'); + map[hash] = tx; } - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) { hash = tx.hash('hex'); hasDeps = false; count[hash] = 0; - for (j = 0; j < tx.inputs.length; j++) { - input = tx.inputs[j]; + for (input of tx.inputs) { prev = input.prevout.hash; if (!map[prev]) @@ -127,8 +121,7 @@ common.sortDeps = function sortDeps(txs) { top.push(tx); } - for (i = 0; i < top.length; i++) { - tx = top[i]; + for (tx of top) { hash = tx.hash('hex'); result.push(tx); @@ -138,8 +131,7 @@ common.sortDeps = function sortDeps(txs) { if (!deps) continue; - for (j = 0; j < deps.length; j++) { - tx = deps[j]; + for (tx of deps) { hash = tx.hash('hex'); if (--count[hash] === 0) diff --git a/lib/wallet/http.js b/lib/wallet/http.js index ab214962..5519f1aa 100644 --- a/lib/wallet/http.js +++ b/lib/wallet/http.js @@ -382,7 +382,7 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var passphrase = valid.str('passphrase'); var outputs = valid.array('outputs'); - var i, options, tx, details, output, script; + var options, tx, details, output, script; options = { rate: valid.amt('rate'), @@ -395,9 +395,8 @@ HTTPServer.prototype.initRouter = function initRouter() { outputs: [] }; - for (i = 0; i < outputs.length; i++) { - output = outputs[i]; - valid = new Validator(output); + for (output of outputs) { + valid = new Validator([output]); script = null; if (valid.has('script')) { @@ -424,7 +423,7 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var passphrase = valid.str('passphrase'); var outputs = valid.array('outputs'); - var i, options, tx, output, script; + var options, tx, output, script; options = { rate: valid.amt('rate'), @@ -436,9 +435,8 @@ HTTPServer.prototype.initRouter = function initRouter() { outputs: [] }; - for (i = 0; i < outputs.length; i++) { - output = outputs[i]; - valid = new Validator(output); + for (output of outputs) { + valid = new Validator([output]); script = null; if (valid.has('script')) { @@ -618,14 +616,12 @@ HTTPServer.prototype.initRouter = function initRouter() { var acct = valid.str('account'); var coins = await req.wallet.getCoins(acct); var result = []; - var i, coin; + var coin; common.sortCoins(coins); - for (i = 0; i < coins.length; i++) { - coin = coins[i]; + for (coin of coins) result.push(coin.getJSON(this.network)); - } res.send(200, result); }); @@ -634,12 +630,10 @@ HTTPServer.prototype.initRouter = function initRouter() { this.get('/:id/locked', async function(req, res) { var locked = this.wallet.getLocked(); var result = []; - var i, outpoint; + var outpoint; - for (i = 0; i < locked.length; i++) { - outpoint = locked[i]; + for (outpoint of locked) result.push(outpoint.toJSON()); - } res.send(200, result); }); @@ -700,16 +694,14 @@ HTTPServer.prototype.initRouter = function initRouter() { var acct = valid.str('account'); var txs = await req.wallet.getHistory(acct); var result = []; - var i, details, item; + var details, item; common.sortTX(txs); details = await req.wallet.toDetails(txs); - for (i = 0; i < details.length; i++) { - item = details[i]; + for (item of details) result.push(item.toJSON()); - } res.send(200, result); }); @@ -720,16 +712,14 @@ HTTPServer.prototype.initRouter = function initRouter() { var acct = valid.str('account'); var txs = await req.wallet.getPending(acct); var result = []; - var i, details, item; + var details, item; common.sortTX(txs); details = await req.wallet.toDetails(txs); - for (i = 0; i < details.length; i++) { - item = details[i]; + for (item of details) result.push(item.toJSON()); - } res.send(200, result); }); @@ -739,7 +729,7 @@ HTTPServer.prototype.initRouter = function initRouter() { var valid = req.valid(); var acct = valid.str('account'); var result = []; - var i, options, txs, details, item; + var options, txs, details, item; options = { start: valid.u32('start'), @@ -752,10 +742,8 @@ HTTPServer.prototype.initRouter = function initRouter() { details = await req.wallet.toDetails(txs); - for (i = 0; i < details.length; i++) { - item = details[i]; + for (item of details) result.push(item.toJSON()); - } res.send(200, result); }); @@ -768,12 +756,10 @@ HTTPServer.prototype.initRouter = function initRouter() { var txs = await req.wallet.getLast(acct, limit); var details = await req.wallet.toDetails(txs); var result = []; - var i, item; + var item; - for (i = 0; i < details.length; i++) { - item = details[i]; + for (item of details) result.push(item.toJSON()); - } res.send(200, result); }); @@ -858,12 +844,10 @@ HTTPServer.prototype.initSockets = function initSockets() { this.walletdb.on('address', function(id, receive) { var channel = 'w:' + id; var json = []; - var i, address; + var addr; - for (i = 0; i < receive.length; i++) { - address = receive[i]; - json.push(address.toJSON()); - } + for (addr of receive) + json.push(addr.toJSON()); self.to(channel, 'wallet address', json); self.to('!all', 'wallet address', id, json); diff --git a/lib/wallet/records.js b/lib/wallet/records.js index 881e0a39..84c5fc1e 100644 --- a/lib/wallet/records.js +++ b/lib/wallet/records.js @@ -281,12 +281,11 @@ BlockMapRecord.fromRaw = function fromRaw(height, data) { BlockMapRecord.prototype.getSize = function getSize() { var size = 0; - var i, tx; + var tx; size += 4; - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) { size += 32; size += tx.getSize(); } @@ -303,12 +302,11 @@ BlockMapRecord.prototype.getSize = function getSize() { BlockMapRecord.prototype.toRaw = function toRaw() { var size = this.getSize(); var bw = new StaticWriter(size); - var i, tx; + var tx; bw.writeU32(this.txs.length); - for (i = 0; i < this.txs.length; i++) { - tx = this.txs[i]; + for (tx of this.txs) { bw.writeHash(tx.hash); tx.toWriter(bw); } @@ -731,14 +729,12 @@ function sizeWallets(wids) { } function serializeWallets(bw, wids) { - var i, wid; + var wid; bw.writeU32(wids.length); - for (i = 0; i < wids.length; i++) { - wid = wids[i]; + for (wid of wids) bw.writeU32(wid); - } return bw; } diff --git a/lib/wallet/rpc.js b/lib/wallet/rpc.js index fd381e63..4cc05ac4 100644 --- a/lib/wallet/rpc.js +++ b/lib/wallet/rpc.js @@ -186,17 +186,15 @@ RPC.prototype.fundRawTransaction = async function fundRawTransaction(args, help) RPC.prototype.resendWalletTransactions = async function resendWalletTransactions(args, help) { var wallet = this.wallet; var hashes = []; - var i, tx, txs; + var tx, txs; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'resendwallettransactions'); txs = await wallet.resend(); - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) hashes.push(tx.txid()); - } return hashes; }; @@ -254,7 +252,7 @@ RPC.prototype.dumpWallet = async function dumpWallet(args, help) { var valid = new Validator([args]); var file = valid.str(0); var time = util.date(); - var i, tip, addr, fmt, str, out, hash, hashes, ring; + var tip, addr, fmt, str, out, hash, hashes, ring; if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'dumpwallet "filename"'); @@ -275,8 +273,7 @@ RPC.prototype.dumpWallet = async function dumpWallet(args, help) { hashes = await wallet.getAddressHashes(); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { ring = await wallet.getPrivateKey(hash); if (!ring) @@ -374,7 +371,7 @@ RPC.prototype.getAddressesByAccount = async function getAddressesByAccount(args, var wallet = this.wallet; var valid = new Validator([args]); var name = valid.str(0, ''); - var i, path, address, addrs, paths; + var path, addr, addrs, paths; if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'getaddressesbyaccount "account"'); @@ -386,10 +383,9 @@ RPC.prototype.getAddressesByAccount = async function getAddressesByAccount(args, paths = await wallet.getPaths(name); - for (i = 0; i < paths.length; i++) { - path = paths[i]; - address = path.toAddress(); - addrs.push(address.toString(this.network)); + for (path of paths) { + addr = path.toAddress(); + addrs.push(addr.toString(this.network)); } return addrs; @@ -465,7 +461,7 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h var total = 0; var filter = {}; var lastConf = -1; - var i, j, path, wtx, output, conf, hash, paths, txs; + var path, wtx, output, conf, hash, paths, txs; if (help || args.length < 1 || args.length > 2) { throw new RPCError(errs.MISC_ERROR, @@ -477,16 +473,12 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h paths = await wallet.getPaths(name); - for (i = 0; i < paths.length; i++) { - path = paths[i]; + for (path of paths) filter[path.hash] = true; - } txs = await wallet.getHistory(name); - for (i = 0; i < txs.length; i++) { - wtx = txs[i]; - + for (wtx of txs) { conf = wtx.getDepth(height); if (conf < minconf) @@ -495,8 +487,7 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h if (lastConf === -1 || conf < lastConf) lastConf = conf; - for (j = 0; j < wtx.tx.outputs.length; j++) { - output = wtx.tx.outputs[j]; + for (output of wtx.tx.outputs) { hash = output.getHash('hex'); if (hash && filter[hash]) total += output.value; @@ -513,7 +504,7 @@ RPC.prototype.getReceivedByAddress = async function getReceivedByAddress(args, h var minconf = valid.u32(1, 0); var height = this.wdb.state.height; var total = 0; - var i, j, hash, wtx, output, txs; + var hash, wtx, output, txs; if (help || args.length < 1 || args.length > 2) { throw new RPCError(errs.MISC_ERROR, @@ -523,14 +514,11 @@ RPC.prototype.getReceivedByAddress = async function getReceivedByAddress(args, h hash = parseHash(addr, this.network); txs = await wallet.getHistory(); - for (i = 0; i < txs.length; i++) { - wtx = txs[i]; - + for (wtx of txs) { if (wtx.getDepth(height) < minconf) continue; - for (j = 0; j < wtx.tx.outputs.length; j++) { - output = wtx.tx.outputs[j]; + for (output of wtx.tx.outputs) { if (output.getHash('hex') === hash) total += output.value; } @@ -551,8 +539,7 @@ RPC.prototype._toWalletTX = async function _toWalletTX(wtx) { if (!details) throw new RPCError(errs.WALLET_ERROR, 'TX not found.'); - for (i = 0; i < details.inputs.length; i++) { - member = details.inputs[i]; + for (member of details.inputs) { if (member.path) { receive = false; break; @@ -720,7 +707,7 @@ RPC.prototype.importWallet = async function importWallet(args, help) { var file = valid.str(0); var rescan = valid.bool(1, false); var keys = []; - var i, lines, line, parts; + var lines, line, parts; var secret, data, key; if (help || args.length !== 1) @@ -733,8 +720,8 @@ RPC.prototype.importWallet = async function importWallet(args, help) { lines = data.split(/\n+/); - for (i = 0; i < lines.length; i++) { - line = lines[i].trim(); + for (line of lines) { + line = line.trim(); if (line.length === 0) continue; @@ -752,10 +739,8 @@ RPC.prototype.importWallet = async function importWallet(args, help) { keys.push(secret); } - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) await wallet.importKey(0, key); - } if (rescan) await this.wdb.rescan(0); @@ -835,7 +820,7 @@ RPC.prototype.listAccounts = async function listAccounts(args, help) { var minconf = valid.u32(0, 0); var watchOnly = valid.bool(1, false); var map = {}; - var i, accounts, account, balance, value; + var accounts, account, balance, value; if (help || args.length > 2) { throw new RPCError(errs.MISC_ERROR, @@ -844,8 +829,7 @@ RPC.prototype.listAccounts = async function listAccounts(args, help) { accounts = await wallet.getAccounts(); - for (i = 0; i < accounts.length; i++) { - account = accounts[i]; + for (account of accounts) { balance = await wallet.getBalance(account); value = balance.unconfirmed; @@ -870,7 +854,7 @@ RPC.prototype.listAddressGroupings = async function listAddressGroupings(args, h RPC.prototype.listLockUnspent = async function listLockUnspent(args, help) { var wallet = this.wallet; - var i, outpoints, outpoint, out; + var outpoints, outpoint, out; if (help || args.length > 0) throw new RPCError(errs.MISC_ERROR, 'listlockunspent'); @@ -878,8 +862,7 @@ RPC.prototype.listLockUnspent = async function listLockUnspent(args, help) { outpoints = wallet.getLocked(); out = []; - for (i = 0; i < outpoints.length; i++) { - outpoint = outpoints[i]; + for (outpoint of outpoints) { out.push({ txid: outpoint.txid(), vout: outpoint.index @@ -924,11 +907,10 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch var out = []; var result = []; var map = {}; - var i, j, path, wtx, output, conf, hash; + var path, wtx, output, conf, hash; var entry, address, keys, key, item, txs; - for (i = 0; i < paths.length; i++) { - path = paths[i]; + for (path of paths) { address = path.toAddress(); map[path.hash] = { involvesWatchonly: wallet.watchOnly, @@ -942,16 +924,13 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch txs = await wallet.getHistory(); - for (i = 0; i < txs.length; i++) { - wtx = txs[i]; - + for (wtx of txs) { conf = wtx.getDepth(height); if (conf < minconf) continue; - for (j = 0; j < wtx.tx.outputs.length; j++) { - output = wtx.tx.outputs[j]; + for (output of wtx.tx.outputs) { address = output.getAddress(); if (!address) @@ -971,8 +950,7 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch keys = Object.keys(map); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { entry = map[key]; out.push(entry); } @@ -980,8 +958,7 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch if (account) { map = {}; - for (i = 0; i < out.length; i++) { - entry = out[i]; + for (entry of out) { item = map[entry.account]; if (!item) { map[entry.account] = entry; @@ -994,16 +971,13 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch out = []; keys = Object.keys(map); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { entry = map[key]; out.push(entry); } } - for (i = 0; i < out.length; i++) { - entry = out[i]; - + for (entry of out) { if (!empty && entry.amount === 0) continue; @@ -1026,7 +1000,7 @@ RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { var watchOnly = valid.bool(2, false); var height = -1; var out = []; - var i, entry, highest, txs, wtx, json; + var entry, highest, txs, wtx, json; if (help) { throw new RPCError(errs.MISC_ERROR, @@ -1047,9 +1021,7 @@ RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { txs = await wallet.getHistory(); - for (i = 0; i < txs.length; i++) { - wtx = txs[i]; - + for (wtx of txs) { if (wtx.height < height) continue; @@ -1084,8 +1056,7 @@ RPC.prototype._toListTX = async function _toListTX(wtx) { if (!details) throw new RPCError(errs.WALLET_ERROR, 'TX not found.'); - for (i = 0; i < details.inputs.length; i++) { - member = details.inputs[i]; + for (member of details.inputs) { if (member.path) { receive = false; break; @@ -1191,7 +1162,7 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { var height = this.wdb.state.height; var out = []; var map = {}; - var i, depth, address, hash, coins, coin, ring; + var i, depth, addr, hash, coins, coin, ring; if (help || args.length > 3) { throw new RPCError(errs.MISC_ERROR, @@ -1201,8 +1172,8 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { if (addrs) { valid = new Validator([addrs]); for (i = 0; i < addrs.length; i++) { - address = valid.str(i, ''); - hash = parseHash(address, this.network); + addr = valid.str(i, ''); + hash = parseHash(addr, this.network); if (map[hash]) throw new RPCError(errs.INVALID_PARAMETER, 'Duplicate address.'); @@ -1215,16 +1186,15 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { common.sortCoins(coins); - for (i = 0; i < coins.length; i++ ) { - coin = coins[i]; + for (coin of coins) { depth = coin.getDepth(height); if (!(depth >= minDepth && depth <= maxDepth)) continue; - address = coin.getAddress(); + addr = coin.getAddress(); - if (!address) + if (!addr) continue; hash = coin.getHash('hex'); @@ -1239,7 +1209,7 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { out.push({ txid: coin.txid(), vout: coin.index, - address: address ? address.toString(this.network) : null, + address: addr ? addr.toString(this.network) : null, account: ring ? ring.name : undefined, redeemScript: ring && ring.script ? ring.script.toJSON() @@ -1260,7 +1230,7 @@ RPC.prototype.lockUnspent = async function lockUnspent(args, help) { var valid = new Validator([args]); var unlock = valid.bool(0, false); var outputs = valid.array(1); - var i, output, outpoint, hash, index; + var output, outpoint, hash, index; if (help || args.length < 1 || args.length > 2) { throw new RPCError(errs.MISC_ERROR, @@ -1276,8 +1246,7 @@ RPC.prototype.lockUnspent = async function lockUnspent(args, help) { if (!outputs) throw new RPCError(errs.TYPE_ERROR, 'Invalid parameter.'); - for (i = 0; i < outputs.length; i++) { - output = outputs[i]; + for (output of outputs) { valid = new Validator([output]); hash = valid.hash('txid'); index = valid.u32('vout'); @@ -1353,7 +1322,7 @@ RPC.prototype.sendMany = async function sendMany(args, help) { var subtractFee = valid.bool(4, false); var outputs = []; var uniq = {}; - var i, keys, tx, key, value, address; + var keys, tx, key, value, address; var hash, output, options; if (help || args.length < 2 || args.length > 5) { @@ -1371,8 +1340,7 @@ RPC.prototype.sendMany = async function sendMany(args, help) { keys = Object.keys(sendTo); valid = new Validator([sendTo]); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { value = valid.btc(key); address = parseAddress(key, this.network); hash = address.getHash('hex'); diff --git a/lib/wallet/txdb.js b/lib/wallet/txdb.js index cdddea94..f44b8390 100644 --- a/lib/wallet/txdb.js +++ b/lib/wallet/txdb.js @@ -124,7 +124,7 @@ TXDB.prototype.clear = function clear() { */ TXDB.prototype.commit = async function commit() { - var i, item; + var item; try { await this.wallet.commit(); @@ -142,8 +142,7 @@ TXDB.prototype.commit = async function commit() { // Emit buffered events now that // we know everything is written. - for (i = 0; i < this.events.length; i++) { - item = this.events[i]; + for (item of this.events) { this.walletdb.emit(item[0], this.wallet.id, item[1], item[2]); this.wallet.emit(item[0], item[1], item[2]); } @@ -432,10 +431,9 @@ TXDB.prototype.resolveInput = async function resolveInput(tx, index, height, pat */ TXDB.prototype.isDoubleSpend = async function isDoubleSpend(tx) { - var i, input, prevout, spent; + var input, prevout, spent; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; spent = await this.isSpent(prevout.hash, prevout.index); if (spent) @@ -453,13 +451,12 @@ TXDB.prototype.isDoubleSpend = async function isDoubleSpend(tx) { */ TXDB.prototype.isRBF = async function isRBF(tx) { - var i, input, prevout; + var input, prevout; if (tx.isRBF()) return true; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (await this.has(layout.r(prevout.hash))) return true; @@ -940,9 +937,7 @@ TXDB.prototype.insert = async function insert(wtx, block) { // Do some secondary indexing for account-based // queries. This saves us a lot of time for // queries later. - for (i = 0; i < details.accounts.length; i++) { - account = details.accounts[i]; - + for (account of details.accounts) { this.put(layout.T(account, hash), DUMMY); this.put(layout.M(account, wtx.ps, hash), DUMMY); @@ -1121,8 +1116,7 @@ TXDB.prototype._confirm = async function confirm(wtx, block) { this.put(layout.h(height, hash), DUMMY); // Secondary indexing also needs to change. - for (i = 0; i < details.accounts.length; i++) { - account = details.accounts[i]; + for (account of details.accounts) { this.del(layout.P(account, hash)); this.put(layout.H(account, height, hash), DUMMY); } @@ -1248,9 +1242,7 @@ TXDB.prototype.erase = async function erase(wtx, block) { this.del(layout.h(height, hash)); // Remove all secondary indexing. - for (i = 0; i < details.accounts.length; i++) { - account = details.accounts[i]; - + for (account of details.accounts) { this.del(layout.T(account, hash)); this.del(layout.M(account, wtx.ps, hash)); @@ -1450,8 +1442,7 @@ TXDB.prototype.disconnect = async function disconnect(wtx, block) { this.del(layout.h(height, hash)); // Secondary indexing also needs to change. - for (i = 0; i < details.accounts.length; i++) { - account = details.accounts[i]; + for (account of details.accounts) { this.put(layout.P(account, hash), DUMMY); this.del(layout.H(account, height, hash)); } @@ -1542,9 +1533,7 @@ TXDB.prototype.removeConflicts = async function removeConflicts(tx, conf) { // Once we know we're not going to // screw things up, remove the double // spenders. - for (i = 0; i < tx.inputs.length; i++) { - spender = spends[i]; - + for (spender of spends) { if (!spender) continue; @@ -1577,15 +1566,13 @@ TXDB.prototype.verifyInput = async function verifyInput(tx, index, coin) { */ TXDB.prototype.lockTX = function lockTX(tx) { - var i, input; + var input; if (tx.isCoinbase()) return; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) this.lockCoin(input.prevout); - } }; /** @@ -1594,15 +1581,13 @@ TXDB.prototype.lockTX = function lockTX(tx) { */ TXDB.prototype.unlockTX = function unlockTX(tx) { - var i, input; + var input; if (tx.isCoinbase()) return; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) this.unlockCoin(input.prevout); - } }; /** @@ -1644,10 +1629,9 @@ TXDB.prototype.isLocked = function isLocked(coin) { TXDB.prototype.filterLocked = function filterLocked(coins) { var out = []; - var i, coin; + var coin; - for (i = 0; i < coins.length; i++) { - coin = coins[i]; + for (coin of coins) { if (!this.isLocked(coin)) out.push(coin); } @@ -1930,7 +1914,7 @@ TXDB.prototype.getRangeHashes = function getRangeHashes(account, options) { TXDB.prototype.getRange = async function getRange(account, options) { var txs = []; - var i, hashes, hash, tx; + var hashes, hash, tx; if (account && typeof account === 'object') { options = account; @@ -1939,13 +1923,9 @@ TXDB.prototype.getRange = async function getRange(account, options) { hashes = await this.getRangeHashes(account, options); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { tx = await this.getTX(hash); - - if (!tx) - continue; - + assert(tx); txs.push(tx); } @@ -1996,15 +1976,11 @@ TXDB.prototype.getHistory = function getHistory(account) { TXDB.prototype.getAccountHistory = async function getAccountHistory(account) { var hashes = await this.getHistoryHashes(account); var txs = []; - var i, hash, tx; + var hash, tx; - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { tx = await this.getTX(hash); - - if (!tx) - continue; - + assert(tx); txs.push(tx); } @@ -2020,15 +1996,11 @@ TXDB.prototype.getAccountHistory = async function getAccountHistory(account) { TXDB.prototype.getPending = async function getPending(account) { var hashes = await this.getPendingHashes(account); var txs = []; - var i, hash, tx; + var hash, tx; - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { tx = await this.getTX(hash); - - if (!tx) - continue; - + assert(tx); txs.push(tx); } @@ -2075,15 +2047,11 @@ TXDB.prototype.getCredits = function getCredits(account) { TXDB.prototype.getAccountCredits = async function getAccountCredits(account) { var outpoints = await this.getOutpoints(account); var credits = []; - var i, prevout, credit; + var prevout, credit; - for (i = 0; i < outpoints.length; i++) { - prevout = outpoints[i]; + for (prevout of outpoints) { credit = await this.getCredit(prevout.hash, prevout.index); - - if (!credit) - continue; - + assert(credit); credits.push(credit); } @@ -2134,11 +2102,9 @@ TXDB.prototype.getSpentCredits = async function getSpentCredits(tx) { TXDB.prototype.getCoins = async function getCoins(account) { var credits = await this.getCredits(account); var coins = []; - var i, credit; - - for (i = 0; i < credits.length; i++) { - credit = credits[i]; + var credit; + for (credit of credits) { if (credit.spent) continue; @@ -2157,11 +2123,9 @@ TXDB.prototype.getCoins = async function getCoins(account) { TXDB.prototype.getAccountCoins = async function getAccountCoins(account) { var credits = await this.getAccountCredits(account); var coins = []; - var i, credit; - - for (i = 0; i < credits.length; i++) { - credit = credits[i]; + var credit; + for (credit of credits) { if (credit.spent) continue; @@ -2179,16 +2143,14 @@ TXDB.prototype.getAccountCoins = async function getAccountCoins(account) { TXDB.prototype.getSpentCoins = async function getSpentCoins(tx) { var coins = []; - var i, credits, credit; + var credits, credit; if (tx.isCoinbase()) return coins; credits = await this.getSpentCredits(tx); - for (i = 0; i < tx.inputs.length; i++) { - credit = credits[i]; - + for (credit of credits) { if (!credit) { coins.push(null); continue; @@ -2208,13 +2170,12 @@ TXDB.prototype.getSpentCoins = async function getSpentCoins(tx) { TXDB.prototype.getCoinView = async function getCoinView(tx) { var view = new CoinView(); - var i, input, prevout, coin; + var input, prevout, coin; if (tx.isCoinbase()) return view; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; coin = await this.getCoin(prevout.hash, prevout.index); @@ -2235,16 +2196,14 @@ TXDB.prototype.getCoinView = async function getCoinView(tx) { TXDB.prototype.getSpentView = async function getSpentView(tx) { var view = new CoinView(); - var i, coins, coin; + var coins, coin; if (tx.isCoinbase()) return view; coins = await this.getSpentCoins(tx); - for (i = 0; i < coins.length; i++) { - coin = coins[i]; - + for (coin of coins) { if (!coin) continue; @@ -2305,15 +2264,14 @@ TXDB.prototype.getDetails = async function getDetails(hash) { */ TXDB.prototype.toDetails = async function toDetails(wtxs) { - var i, out, wtx, details; + var out, wtx, details; if (!Array.isArray(wtxs)) return await this._toDetails(wtxs); out = []; - for (i = 0; i < wtxs.length; i++) { - wtx = wtxs[i]; + for (wtx of wtxs) { details = await this._toDetails(wtx); if (!details) @@ -2515,10 +2473,9 @@ TXDB.prototype.getBalance = async function getBalance(account) { TXDB.prototype.getWalletBalance = async function getWalletBalance() { var credits = await this.getCredits(); var balance = new Balance(this.wallet.wid, this.wallet.id, -1); - var i, credit, coin; + var credit, coin; - for (i = 0; i < credits.length; i++) { - credit = credits[i]; + for (credit of credits) { coin = credit.coin; if (coin.height !== -1) @@ -2540,10 +2497,9 @@ TXDB.prototype.getWalletBalance = async function getWalletBalance() { TXDB.prototype.getAccountBalance = async function getAccountBalance(account) { var credits = await this.getAccountCredits(account); var balance = new Balance(this.wallet.wid, this.wallet.id, account); - var i, credit, coin; + var credit, coin; - for (i = 0; i < credits.length; i++) { - credit = credits[i]; + for (credit of credits) { coin = credit.coin; if (coin.height !== -1) @@ -2566,7 +2522,7 @@ TXDB.prototype.getAccountBalance = async function getAccountBalance(account) { TXDB.prototype.zap = async function zap(account, age) { var hashes = []; var now = util.now(); - var i, txs, wtx; + var txs, wtx; assert(util.isUInt32(age)); @@ -2575,9 +2531,7 @@ TXDB.prototype.zap = async function zap(account, age) { end: now - age }); - for (i = 0; i < txs.length; i++) { - wtx = txs[i]; - + for (wtx of txs) { if (wtx.height !== -1) continue; @@ -2946,17 +2900,15 @@ function Details(txdb, wtx, block) { */ Details.prototype.init = function init() { - var i, input, output, member; + var input, output, member; - for (i = 0; i < this.tx.inputs.length; i++) { - input = this.tx.inputs[i]; + for (input of this.tx.inputs) { member = new DetailsMember(); member.address = input.getAddress(); this.inputs.push(member); } - for (i = 0; i < this.tx.outputs.length; i++) { - output = this.tx.outputs[i]; + for (output of this.tx.outputs) { member = new DetailsMember(); member.value = output.value; member.address = output.getAddress(); @@ -3028,21 +2980,17 @@ Details.prototype.getDepth = function getDepth() { Details.prototype.getFee = function getFee() { var inputValue = 0; var outputValue = 0; - var i, input, output; - - for (i = 0; i < this.inputs.length; i++) { - input = this.inputs[i]; + var input, output; + for (input of this.inputs) { if (!input.path) return 0; inputValue += input.value; } - for (i = 0; i < this.outputs.length; i++) { - output = this.outputs[i]; + for (output of this.outputs) outputValue += output.value; - } return inputValue - outputValue; }; @@ -3259,7 +3207,7 @@ BlockRecord.prototype.getSize = function getSize() { BlockRecord.prototype.toRaw = function toRaw() { var size = this.getSize(); var bw = new StaticWriter(size); - var i; + var hash; bw.writeHash(this.hash); bw.writeU32(this.height); @@ -3267,8 +3215,8 @@ BlockRecord.prototype.toRaw = function toRaw() { bw.writeU32(this.hashes.length); - for (i = 0; i < this.hashes.length; i++) - bw.writeHash(this.hashes[i]); + for (hash of this.hashes) + bw.writeHash(hash); return bw.render(); }; diff --git a/lib/wallet/wallet.js b/lib/wallet/wallet.js index b2a32480..57d8f34d 100644 --- a/lib/wallet/wallet.js +++ b/lib/wallet/wallet.js @@ -540,7 +540,7 @@ Wallet.prototype.renameAccount = async function renameAccount(acct, name) { */ Wallet.prototype._renameAccount = async function _renameAccount(acct, name) { - var i, account, old, paths, path; + var account, old, paths, path; if (!common.isName(name)) throw new Error('Bad account name.'); @@ -568,9 +568,7 @@ Wallet.prototype._renameAccount = async function _renameAccount(acct, name) { paths = this.pathCache.values(); - for (i = 0; i < paths.length; i++) { - path = paths[i]; - + for (path of paths) { if (path.account !== account.accountIndex) continue; @@ -1132,7 +1130,7 @@ Wallet.prototype.hasPath = async function hasPath(address) { */ Wallet.prototype.getPaths = async function getPaths(acct) { - var i, paths, path, result; + var paths, path, result; if (acct != null) return await this.getAccountPaths(acct); @@ -1140,8 +1138,7 @@ Wallet.prototype.getPaths = async function getPaths(acct) { paths = await this.db.getWalletPaths(this.wid); result = []; - for (i = 0; i < paths.length; i++) { - path = paths[i]; + for (path of paths) { path.id = this.id; path.name = await this.getAccountName(path.account); @@ -1166,12 +1163,11 @@ Wallet.prototype.getAccountPaths = async function getAccountPaths(acct) { var hashes = await this.getAccountHashes(index); var name = await this.getAccountName(acct); var result = []; - var i, hash, path; + var hash, path; assert(name); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { path = await this.readPath(hash); assert(path); @@ -1541,14 +1537,14 @@ Wallet.prototype.estimateSize = async function estimateSize(prev) { Wallet.prototype.createTX = async function createTX(options, force) { var outputs = options.outputs; var mtx = new MTX(); - var i, output, addr, total; + var output, addr, total; assert(Array.isArray(outputs), 'Outputs must be an array.'); assert(outputs.length > 0, 'No outputs available.'); // Add the outputs - for (i = 0; i < outputs.length; i++) { - output = new Output(outputs[i]); + for (output of outputs) { + output = new Output(output); addr = output.getAddress(); if (output.isDust()) @@ -1685,8 +1681,7 @@ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase mtx = MTX.fromTX(tx); mtx.view = view; - for (i = 0; i < mtx.inputs.length; i++) { - input = mtx.inputs[i]; + for (input of mtx.inputs) { input.script.length = 0; input.script.compile(); input.witness.length = 0; @@ -1755,20 +1750,18 @@ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase Wallet.prototype.resend = async function resend() { var wtxs = await this.getPending(); var txs = []; - var i, wtx; + var wtx, tx; if (wtxs.length > 0) this.logger.info('Rebroadcasting %d transactions.', wtxs.length); - for (i = 0; i < wtxs.length; i++) { - wtx = wtxs[i]; + for (wtx of wtxs) txs.push(wtx.tx); - } txs = common.sortDeps(txs); - for (i = 0; i < txs.length; i++) - await this.db.send(txs[i]); + for (tx of txs) + await this.db.send(tx); return txs; }; @@ -1782,14 +1775,13 @@ Wallet.prototype.resend = async function resend() { Wallet.prototype.deriveInputs = async function deriveInputs(mtx) { var rings = []; - var i, paths, path, account, ring; + var paths, path, account, ring; assert(mtx.mutable); paths = await this.getInputPaths(mtx); - for (i = 0; i < paths.length; i++) { - path = paths[i]; + for (path of paths) { account = await this.getAccount(path.account); if (!account) @@ -1865,7 +1857,7 @@ Wallet.prototype.getPrivateKey = async function getPrivateKey(address, passphras Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { var paths = []; - var i, hashes, hash, path; + var hashes, hash, path; assert(mtx.mutable); @@ -1874,8 +1866,7 @@ Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { hashes = mtx.getInputHashes('hex'); - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { path = await this.getPath(hash); if (path) paths.push(path); @@ -1893,10 +1884,9 @@ Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { Wallet.prototype.getOutputPaths = async function getOutputPaths(tx) { var paths = []; var hashes = tx.getOutputHashes('hex'); - var i, hash, path; + var hash, path; - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; + for (hash of hashes) { path = await this.getPath(hash); if (path) paths.push(path); @@ -1968,14 +1958,15 @@ Wallet.prototype._setLookahead = async function setLookahead(acct, lookahead) { Wallet.prototype.syncOutputDepth = async function syncOutputDepth(details) { var derived = []; var accounts = {}; - var i, j, path, paths, acct, account; + var path, paths, acct, account; var receive, change, nested, ring; + var output; if (!details) return derived; - for (i = 0; i < details.outputs.length; i++) { - path = details.outputs[i].path; + for (output of details.outputs) { + path = output.path; if (!path) continue; @@ -1991,16 +1982,13 @@ Wallet.prototype.syncOutputDepth = async function syncOutputDepth(details) { accounts = util.values(accounts); - for (i = 0; i < accounts.length; i++) { - paths = accounts[i]; + for (paths of accounts) { acct = paths[0].account; receive = -1; change = -1; nested = -1; - for (j = 0; j < paths.length; j++) { - path = paths[j]; - + for (path of paths) { switch (path.branch) { case 0: if (path.index > receive) @@ -2378,10 +2366,9 @@ Wallet.prototype.getCredits = async function getCredits(acct) { Wallet.prototype.getSmartCoins = async function getSmartCoins(acct) { var credits = await this.getCredits(acct); var coins = []; - var i, credit, coin; + var credit, coin; - for (i = 0; i < credits.length; i++) { - credit = credits[i]; + for (credit of credits) { coin = credit.coin; if (credit.spent) diff --git a/lib/wallet/walletdb.js b/lib/wallet/walletdb.js index 8e9b4ac2..a5f1b661 100644 --- a/lib/wallet/walletdb.js +++ b/lib/wallet/walletdb.js @@ -944,7 +944,7 @@ WalletDB.prototype.rename = async function rename(wallet, id) { WalletDB.prototype._rename = async function _rename(wallet, id) { var old = wallet.id; - var i, paths, path, batch; + var paths, path, batch; if (!common.isName(id)) throw new Error('WDB: Bad wallet ID.'); @@ -965,10 +965,8 @@ WalletDB.prototype._rename = async function _rename(wallet, id) { paths = wallet.pathCache.values(); - for (i = 0; i < paths.length; i++) { - path = paths[i]; + for (path of paths) path.id = id; - } }; /** @@ -1361,25 +1359,25 @@ WalletDB.prototype.getAccountHashes = function getAccountHashes(wid, account) { */ WalletDB.prototype.getWalletPaths = async function getWalletPaths(wid) { - var i, item, items, hash, path; + var paths = []; + var item, items, hash, path; items = await this.db.range({ gte: layout.P(wid, encoding.NULL_HASH), lte: layout.P(wid, encoding.HIGH_HASH) }); - for (i = 0; i < items.length; i++) { - item = items[i]; + for (item of items) { hash = layout.Pp(item.key); path = Path.fromRaw(item.value); path.hash = hash; path.wid = wid; - items[i] = path; + paths.push(path); } - return items; + return paths; }; /** @@ -1406,11 +1404,9 @@ WalletDB.prototype.encryptKeys = async function encryptKeys(wallet, key) { var wid = wallet.wid; var paths = await wallet.getPaths(); var batch = this.batch(wallet); - var i, path, iv; - - for (i = 0; i < paths.length; i++) { - path = paths[i]; + var path, iv; + for (path of paths) { if (!path.data) continue; @@ -1440,11 +1436,9 @@ WalletDB.prototype.decryptKeys = async function decryptKeys(wallet, key) { var wid = wallet.wid; var paths = await wallet.getPaths(); var batch = this.batch(wallet); - var i, path, iv; - - for (i = 0; i < paths.length; i++) { - path = paths[i]; + var path, iv; + for (path of paths) { if (!path.data) continue; @@ -1469,15 +1463,14 @@ WalletDB.prototype.decryptKeys = async function decryptKeys(wallet, key) { */ WalletDB.prototype.resend = async function resend() { - var i, keys, key, wid; + var keys, key, wid; keys = await this.db.keys({ gte: layout.w(0x00000000), lte: layout.w(0xffffffff) }); - for (i = 0; i < keys.length; i++) { - key = keys[i]; + for (key of keys) { wid = layout.ww(key); await this.resendPending(wid); } @@ -1493,7 +1486,7 @@ WalletDB.prototype.resend = async function resend() { WalletDB.prototype.resendPending = async function resendPending(wid) { var layout = layouts.txdb; var txs = []; - var i, key, keys, hash, data, wtx, tx; + var key, keys, hash, data, wtx, tx; keys = await this.db.keys({ gte: layout.prefix(wid, layout.p(encoding.NULL_HASH)), @@ -1508,9 +1501,7 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { keys.length, wid); - for (i = 0; i < keys.length; i++) { - key = keys[i]; - + for (key of keys) { hash = layout.pp(key); key = layout.prefix(wid, layout.t(hash)); @@ -1529,10 +1520,8 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { txs = common.sortDeps(txs); - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) await this.send(tx); - } }; /** @@ -1544,11 +1533,10 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { var hashes = tx.getOutputHashes('hex'); var result = []; - var i, j, input, prevout, hash, map; + var input, prevout, hash, map, wid; if (!tx.isCoinbase()) { - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { prevout = input.prevout; if (!this.testFilter(prevout.toRaw())) @@ -1559,14 +1547,12 @@ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { if (!map) continue; - for (j = 0; j < map.wids.length; j++) - util.binaryInsert(result, map.wids[j], cmp, true); + for (wid of map.wids) + util.binaryInsert(result, wid, cmp, true); } } - for (i = 0; i < hashes.length; i++) { - hash = hashes[i]; - + for (hash of hashes) { if (!this.testFilter(hash)) continue; @@ -1575,8 +1561,8 @@ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { if (!map) continue; - for (j = 0; j < map.wids.length; j++) - util.binaryInsert(result, map.wids[j], cmp, true); + for (wid of map.wids) + util.binaryInsert(result, wid, cmp, true); } if (result.length === 0) @@ -1941,7 +1927,7 @@ WalletDB.prototype.addBlock = async function addBlock(entry, txs) { WalletDB.prototype._addBlock = async function addBlock(entry, txs) { var tip = BlockMeta.fromEntry(entry); var total = 0; - var i, tx; + var tx; if (tip.height < this.state.height) { this.logger.warning( @@ -1970,8 +1956,7 @@ WalletDB.prototype._addBlock = async function addBlock(entry, txs) { return total; } - for (i = 0; i < txs.length; i++) { - tx = txs[i]; + for (tx of txs) { if (await this._insert(tx, tip)) total++; } @@ -2098,7 +2083,7 @@ WalletDB.prototype.addTX = async function addTX(tx) { WalletDB.prototype._insert = async function insert(tx, block) { var result = false; - var i, wids, wid, wallet; + var wids, wid, wallet; assert(!tx.mutable, 'WDB: Cannot add mutable TX.'); @@ -2118,8 +2103,7 @@ WalletDB.prototype._insert = async function insert(tx, block) { // Insert the transaction // into every matching wallet. - for (i = 0; i < wids.length; i++) { - wid = wids[i]; + for (wid of wids) { wallet = await this.get(wid); assert(wallet); @@ -2147,10 +2131,9 @@ WalletDB.prototype._insert = async function insert(tx, block) { */ WalletDB.prototype._unconfirm = async function unconfirm(tx) { - var i, wid, wallet; + var wid, wallet; - for (i = 0; i < tx.wids.length; i++) { - wid = tx.wids[i]; + for (wid of tx.wids) { wallet = await this.get(wid); assert(wallet); await wallet.unconfirm(tx.hash); diff --git a/lib/workers/packets.js b/lib/workers/packets.js index 3d3e30b3..4ad6171a 100644 --- a/lib/workers/packets.js +++ b/lib/workers/packets.js @@ -283,16 +283,14 @@ SignPacket.prototype.cmd = packetTypes.SIGN; SignPacket.prototype.getSize = function getSize() { var size = 0; - var i, ring; + var ring; size += this.tx.getSize(); size += this.tx.view.getFastSize(this.tx); size += encoding.sizeVarint(this.rings.length); - for (i = 0; i < this.rings.length; i++) { - ring = this.rings[i]; + for (ring of this.rings) size += ring.getSize(); - } size += 1; @@ -300,17 +298,15 @@ SignPacket.prototype.getSize = function getSize() { }; SignPacket.prototype.toWriter = function toWriter(bw) { - var i, ring; + var ring; this.tx.toWriter(bw); this.tx.view.toFast(bw, this.tx); bw.writeVarint(this.rings.length); - for (i = 0; i < this.rings.length; i++) { - ring = this.rings[i]; + for (ring of this.rings) ring.toWriter(bw); - } bw.writeU8(this.type); }; @@ -353,10 +349,9 @@ SignResultPacket.prototype.cmd = packetTypes.SIGNRESULT; SignResultPacket.fromTX = function fromTX(tx, total) { var packet = new SignResultPacket(total); - var i, input; + var input; - for (i = 0; i < tx.inputs.length; i++) { - input = tx.inputs[i]; + for (input of tx.inputs) { packet.script.push(input.script); packet.witness.push(input.witness); } diff --git a/lib/workers/workerpool.js b/lib/workers/workerpool.js index 15d043f5..16da5b94 100644 --- a/lib/workers/workerpool.js +++ b/lib/workers/workerpool.js @@ -266,11 +266,9 @@ WorkerPool.prototype.alloc = function alloc() { WorkerPool.prototype.sendEvent = function sendEvent() { var result = true; - var i, child; - - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; + var child; + for (child of this.children) { if (!child) continue; @@ -286,11 +284,9 @@ WorkerPool.prototype.sendEvent = function sendEvent() { */ WorkerPool.prototype.destroy = function destroy() { - var i, child; - - for (i = 0; i < this.children.length; i++) { - child = this.children[i]; + var child; + for (child of this.children) { if (!child) continue;