From 9cc5c393b4341a81a89990e4551b508698926457 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 27 Jul 2017 09:27:00 -0700 Subject: [PATCH] eslint: use prefer-const. --- .eslintrc.json | 6 +- bench/bech32.js | 2 +- bench/bench.js | 8 +- bench/coins.js | 2 +- bench/merkle.js | 4 +- bench/mnemonic.js | 4 +- bench/tx.js | 18 +- bench/walletdb.js | 2 +- bin/cli | 126 +++++----- examples/client.js | 4 +- examples/plugin.js | 2 +- examples/tx.js | 16 +- examples/wallet.js | 2 +- lib/bip70/payment.js | 24 +- lib/bip70/paymentack.js | 4 +- lib/bip70/paymentdetails.js | 16 +- lib/bip70/paymentrequest.js | 14 +- lib/bip70/x509.js | 60 ++--- lib/blockchain/chain.js | 190 +++++++------- lib/blockchain/chaindb.js | 250 +++++++++--------- lib/blockchain/chainentry.js | 22 +- lib/blockchain/layout.js | 8 +- lib/btc/amount.js | 6 +- lib/btc/uri.js | 10 +- lib/coins/coinentry.js | 2 +- lib/coins/coins.js | 12 +- lib/coins/coinview.js | 70 +++--- lib/coins/compress.js | 8 +- lib/coins/undocoins.js | 16 +- lib/crypto/aead.js | 4 +- lib/crypto/aes-browser.js | 22 +- lib/crypto/aes.js | 4 +- lib/crypto/chacha20.js | 4 +- lib/crypto/digest-browser.js | 4 +- lib/crypto/digest.js | 4 +- lib/crypto/hkdf.js | 4 +- lib/crypto/hmac-drbg.js | 8 +- lib/crypto/merkle.js | 20 +- lib/crypto/pbkdf2-browser.js | 14 +- lib/crypto/poly1305.js | 44 ++-- lib/crypto/random-browser.js | 6 +- lib/crypto/random.js | 2 +- lib/crypto/rsa-browser.js | 6 +- lib/crypto/schnorr.js | 34 +-- lib/crypto/scrypt.js | 18 +- lib/crypto/secp256k1-browser.js | 16 +- lib/crypto/secp256k1-native.js | 2 +- lib/crypto/sha256.js | 6 +- lib/crypto/siphash.js | 26 +- lib/db/ldb.js | 10 +- lib/db/level.js | 2 +- lib/db/lowlevelup.js | 46 ++-- lib/db/memdb.js | 16 +- lib/hd/common.js | 8 +- lib/hd/mnemonic.js | 40 +-- lib/hd/private.js | 12 +- lib/hd/public.js | 6 +- lib/http/base.js | 80 +++--- lib/http/client.js | 20 +- lib/http/request.js | 18 +- lib/http/rpc.js | 432 ++++++++++++++++---------------- lib/http/rpcbase.js | 6 +- lib/http/rpcclient.js | 2 +- lib/http/server.js | 136 +++++----- lib/http/wallet.js | 2 +- lib/mempool/fees.js | 64 ++--- lib/mempool/layout.js | 2 +- lib/mempool/mempool.js | 314 +++++++++++------------ lib/mempool/mempoolentry.js | 34 +-- lib/mining/common.js | 12 +- lib/mining/cpuminer.js | 52 ++-- lib/mining/miner.js | 32 +-- lib/mining/template.js | 72 +++--- lib/net/bip150.js | 56 ++--- lib/net/bip151.js | 24 +- lib/net/bip152.js | 42 ++-- lib/net/dns.js | 6 +- lib/net/hostlist.js | 168 ++++++------- lib/net/packets.js | 40 +-- lib/net/parser.js | 4 +- lib/net/peer.js | 104 ++++---- lib/net/pool.js | 238 +++++++++--------- lib/net/proxysocket.js | 10 +- lib/net/socks.js | 44 ++-- lib/net/tcp-browser.js | 2 +- lib/net/tcp.js | 4 +- lib/net/upnp.js | 82 +++--- lib/node/config.js | 28 +-- lib/node/fullnode.js | 28 +-- lib/node/logger.js | 46 ++-- lib/node/node.js | 14 +- lib/node/spvnode.js | 6 +- lib/primitives/address.js | 28 +-- lib/primitives/block.js | 64 ++--- lib/primitives/coin.js | 2 +- lib/primitives/headers.js | 6 +- lib/primitives/input.js | 6 +- lib/primitives/keyring.js | 14 +- lib/primitives/memblock.js | 6 +- lib/primitives/merkleblock.js | 62 ++--- lib/primitives/mtx.js | 86 +++---- lib/primitives/netaddress.js | 8 +- lib/primitives/output.js | 8 +- lib/primitives/tx.js | 260 +++++++++---------- lib/primitives/txmeta.js | 10 +- lib/protocol/consensus.js | 14 +- lib/protocol/network.js | 14 +- lib/protocol/timedata.js | 4 +- lib/script/common.js | 22 +- lib/script/opcode.js | 4 +- lib/script/program.js | 6 +- lib/script/script.js | 102 ++++---- lib/script/sigcache.js | 6 +- lib/script/witness.js | 18 +- lib/utils/asn1.js | 46 ++-- lib/utils/asyncemitter.js | 2 +- lib/utils/asyncobject.js | 6 +- lib/utils/base32.js | 2 +- lib/utils/bech32.js | 8 +- lib/utils/bloom.js | 8 +- lib/utils/co.js | 14 +- lib/utils/encoding.js | 22 +- lib/utils/fs.js | 8 +- lib/utils/gcs.js | 82 +++--- lib/utils/heap.js | 12 +- lib/utils/ip.js | 28 +-- lib/utils/list.js | 8 +- lib/utils/lock.js | 4 +- lib/utils/lru.js | 8 +- lib/utils/mappedlock.js | 12 +- lib/utils/murmur3.js | 14 +- lib/utils/pem.js | 8 +- lib/utils/protoreader.js | 18 +- lib/utils/protowriter.js | 6 +- lib/utils/rbt.js | 22 +- lib/utils/reader.js | 18 +- lib/utils/rollingfilter.js | 34 +-- lib/utils/staticwriter.js | 8 +- lib/utils/util.js | 18 +- lib/utils/validator.js | 40 +-- lib/utils/writer.js | 4 +- lib/wallet/account.js | 50 ++-- lib/wallet/client.js | 4 +- lib/wallet/common.js | 32 +-- lib/wallet/http.js | 276 ++++++++++---------- lib/wallet/layout.js | 40 +-- lib/wallet/masterkey.js | 26 +- lib/wallet/nodeclient.js | 2 +- lib/wallet/path.js | 8 +- lib/wallet/plugin.js | 4 +- lib/wallet/records.js | 50 ++-- lib/wallet/rpc.js | 404 ++++++++++++++--------------- lib/wallet/server.js | 2 +- lib/wallet/txdb.js | 396 ++++++++++++++--------------- lib/wallet/wallet.js | 186 +++++++------- lib/wallet/walletdb.js | 210 ++++++++-------- lib/wallet/walletkey.js | 2 +- lib/workers/child.js | 16 +- lib/workers/framer.js | 4 +- lib/workers/jobs.js | 12 +- lib/workers/master.js | 2 +- lib/workers/packets.js | 106 ++++---- lib/workers/parser.js | 8 +- lib/workers/workerpool.js | 50 ++-- migrate/chaindb0to1.js | 6 +- migrate/chaindb1to2.js | 10 +- migrate/chaindb2to3.js | 72 +++--- migrate/coins-old.js | 24 +- migrate/coins/coins.js | 48 ++-- migrate/coins/coinview.js | 48 ++-- migrate/coins/compress.js | 4 +- migrate/coins/undocoins.js | 26 +- migrate/coinview-old.js | 10 +- migrate/compress-old.js | 2 +- migrate/ensure-tip-index.js | 22 +- migrate/walletdb2to3.js | 30 +-- migrate/walletdb3to4.js | 10 +- migrate/walletdb4to5.js | 2 +- migrate/walletdb5to6.js | 20 +- scripts/dump.js | 12 +- scripts/fuzz.js | 42 ++-- test/aes-test.js | 32 +-- test/bech32-test.js | 16 +- test/bip150-test.js | 34 +-- test/bip151-test.js | 28 +-- test/bip70-test.js | 10 +- test/block-test.js | 116 ++++----- test/bloom-test.js | 14 +- test/chachapoly-test.js | 8 +- test/chain-test.js | 136 +++++----- test/coins-test.js | 18 +- test/gcs-test.js | 16 +- test/hd-test.js | 10 +- test/http-test.js | 36 +-- test/key-address-test.js | 4 +- test/mempool-test.js | 36 +-- test/mnemonic-test.js | 22 +- test/node-test.js | 38 +-- test/protocol-test.js | 6 +- test/script-test.js | 20 +- test/scrypt-test.js | 18 +- test/siphash-test.js | 12 +- test/tx-test.js | 122 ++++----- test/util/common.js | 16 +- test/util/memwallet.js | 40 +-- test/util/node-context.js | 18 +- test/utils-test.js | 28 +-- test/wallet-test.js | 98 ++++---- 208 files changed, 3982 insertions(+), 3978 deletions(-) diff --git a/.eslintrc.json b/.eslintrc.json index 7b6ba3b8c..565748a37 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -36,6 +36,10 @@ "no-extra-semi": 0, "handle-callback-err": 0, "no-buffer-constructor": 2, - "no-tabs": 2 + "no-tabs": 2, + "prefer-const": ["error", { + "destructuring": "all", + "ignoreReadBeforeAssign": true + }] } } diff --git a/bench/bech32.js b/bench/bech32.js index 18a90b9e3..9021d1747 100644 --- a/bench/bech32.js +++ b/bench/bech32.js @@ -6,7 +6,7 @@ const bench = require('./bench'); let i, end, addr; -let addrs = []; +const addrs = []; end = bench('serialize'); for (i = 0; i < 100000; i++) { diff --git a/bench/bench.js b/bench/bench.js index bcccbe722..8e486c082 100644 --- a/bench/bench.js +++ b/bench/bench.js @@ -1,11 +1,11 @@ 'use strict'; module.exports = function bench(name) { - let start = process.hrtime(); + const start = process.hrtime(); return function end(ops) { - let elapsed = process.hrtime(start); - let time = elapsed[0] + elapsed[1] / 1e9; - let rate = ops / time; + const elapsed = process.hrtime(start); + const time = elapsed[0] + elapsed[1] / 1e9; + const rate = ops / time; console.log('%s: ops=%d, time=%d, rate=%s', name, ops, time, rate.toFixed(5)); diff --git a/bench/coins.js b/bench/coins.js index 3392b05f4..4201b9dd7 100644 --- a/bench/coins.js +++ b/bench/coins.js @@ -6,7 +6,7 @@ const TX = require('../lib/primitives/tx'); const bench = require('./bench'); let raw = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); -let wtx = TX.fromRaw(raw.trim(), 'hex'); +const wtx = TX.fromRaw(raw.trim(), 'hex'); let coins = Coins.fromTX(wtx, 1); let i, j, end, hash; diff --git a/bench/merkle.js b/bench/merkle.js index bcbe090a8..c171a68bb 100644 --- a/bench/merkle.js +++ b/bench/merkle.js @@ -11,10 +11,10 @@ for (let i = 0; i < 3000; i++) leaves.push(random.randomBytes(32)); { - let end = bench('tree'); + const end = bench('tree'); let i; for (i = 0; i < 1000; i++) { - let [n, m] = merkle.createTree(leaves.slice()); + const [n, m] = merkle.createTree(leaves.slice()); assert(n); assert(!m); } diff --git a/bench/mnemonic.js b/bench/mnemonic.js index e37e5953a..afd730659 100644 --- a/bench/mnemonic.js +++ b/bench/mnemonic.js @@ -5,10 +5,10 @@ const bench = require('./bench'); const HD = require('../lib/hd'); const Mnemonic = require('../lib/hd/mnemonic'); -let mnemonic = new Mnemonic(); +const mnemonic = new Mnemonic(); HD.fromMnemonic(mnemonic); -let phrase = mnemonic.getPhrase(); +const phrase = mnemonic.getPhrase(); let i, end; assert.equal(Mnemonic.fromPhrase(phrase).getPhrase(), phrase); diff --git a/bench/tx.js b/bench/tx.js index 348780cb2..8e5c70aa2 100644 --- a/bench/tx.js +++ b/bench/tx.js @@ -12,11 +12,11 @@ const encoding = require('../lib/utils/encoding'); const random = require('../lib/crypto/random'); const bench = require('./bench'); -let json = require('../test/data/block300025.json'); -let block = Block.fromJSON(json); -let btx = { tx: block.txs[397], view: new CoinView() }; +const json = require('../test/data/block300025.json'); +const block = Block.fromJSON(json); +const btx = { tx: block.txs[397], view: new CoinView() }; -let tx3 = parseTX('../test/data/tx3.hex'); +const tx3 = parseTX('../test/data/tx3.hex'); let wtx = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); let i, tx, end, flags, input; @@ -29,11 +29,11 @@ for (i = 0; i < tx.inputs.length; i++) { } function parseTX(file) { - let data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); - let parts = data.trim().split(/\n+/); + const data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); + const parts = data.trim().split(/\n+/); let raw = parts[0]; - let tx = TX.fromRaw(raw.trim(), 'hex'); - let view = new CoinView(); + const tx = TX.fromRaw(raw.trim(), 'hex'); + const view = new CoinView(); let i, prev; for (i = 1; i < parts.length; i++) { @@ -97,7 +97,7 @@ for (i = 0; i < 3000; i++) end(i * tx3.tx.inputs.length); end = bench('verify2'); -let script = tx3.view.getOutputFor(tx3.tx.inputs[0]).script; +const script = tx3.view.getOutputFor(tx3.tx.inputs[0]).script; for (i = 0; i < 100000; i++) tx3.tx.signatureHashV0(0, script, Script.hashType.ALL); end(i); diff --git a/bench/walletdb.js b/bench/walletdb.js index 2d7c04930..99f858268 100644 --- a/bench/walletdb.js +++ b/bench/walletdb.js @@ -8,7 +8,7 @@ const Outpoint = require('../lib/primitives/outpoint'); let walletdb; function dummy() { - let hash = random.randomBytes(32).toString('hex'); + const hash = random.randomBytes(32).toString('hex'); return new Outpoint(hash, 0); } diff --git a/bin/cli b/bin/cli index 353237ee3..043f4e43f 100755 --- a/bin/cli +++ b/bin/cli @@ -29,12 +29,12 @@ CLI.prototype.log = function log(json) { }; CLI.prototype.getInfo = async function getInfo() { - let info = await this.client.getInfo(); + const info = await this.client.getInfo(); this.log(info); }; CLI.prototype.getWallets = async function getWallets() { - let wallets = await this.client.getWallets(); + const wallets = await this.client.getWallets(); this.log(wallets); }; @@ -65,51 +65,51 @@ CLI.prototype.createWallet = async function createWallet() { }; CLI.prototype.getMaster = async function getMaster() { - let master = await this.wallet.getMaster(); + const master = await this.wallet.getMaster(); this.log(master); }; CLI.prototype.getKey = async function getKey() { - let address = this.config.str(0); - let key = await this.wallet.getKey(address); + const address = this.config.str(0); + const key = await this.wallet.getKey(address); this.log(key); }; CLI.prototype.getWIF = async function getWIF() { - let address = this.config.str(0); - let passphrase = this.config.str('passphrase'); - let key = await this.wallet.getWIF(address, passphrase); + const address = this.config.str(0); + const passphrase = this.config.str('passphrase'); + const key = await this.wallet.getWIF(address, passphrase); this.log(key.privateKey); }; CLI.prototype.addSharedKey = async function addSharedKey() { - let key = this.config.str(0); - let account = this.config.str('account'); + const key = this.config.str(0); + const account = this.config.str('account'); await this.wallet.addSharedKey(account, key); this.log('Added key.'); }; CLI.prototype.removeSharedKey = async function removeSharedKey() { - let key = this.config.str(0); - let account = this.config.str('account'); + const key = this.config.str(0); + const account = this.config.str('account'); await this.wallet.removeSharedKey(account, key); this.log('Removed key.'); }; CLI.prototype.getSharedKeys = async function getSharedKeys() { - let acct = this.config.str([0, 'account']); - let account = await this.wallet.getAccount(acct); + const acct = this.config.str([0, 'account']); + const account = await this.wallet.getAccount(acct); this.log(account.keys); }; CLI.prototype.getAccount = async function getAccount() { - let acct = this.config.str([0, 'account']); - let account = await this.wallet.getAccount(acct); + const acct = this.config.str([0, 'account']); + const account = await this.wallet.getAccount(acct); this.log(account); }; CLI.prototype.createAccount = async function createAccount() { - let name = this.config.str([0, 'name']); + const name = this.config.str([0, 'name']); let options, account; options = { @@ -126,35 +126,35 @@ CLI.prototype.createAccount = async function createAccount() { }; CLI.prototype.createAddress = async function createAddress() { - let account = this.config.str([0, 'account']); - let addr = await this.wallet.createAddress(account); + const account = this.config.str([0, 'account']); + const addr = await this.wallet.createAddress(account); this.log(addr); }; CLI.prototype.createChange = async function createChange() { - let account = this.config.str([0, 'account']); - let addr = await this.wallet.createChange(account); + const account = this.config.str([0, 'account']); + const addr = await this.wallet.createChange(account); this.log(addr); }; CLI.prototype.createNested = async function createNested() { - let account = this.config.str([0, 'account']); - let addr = await this.wallet.createNested(account); + const account = this.config.str([0, 'account']); + const addr = await this.wallet.createNested(account); this.log(addr); }; CLI.prototype.getAccounts = async function getAccounts() { - let accounts = await this.wallet.getAccounts(); + const accounts = await this.wallet.getAccounts(); this.log(accounts); }; CLI.prototype.getWallet = async function getWallet() { - let info = await this.wallet.getInfo(); + const info = await this.wallet.getInfo(); this.log(info); }; CLI.prototype.getTX = async function getTX() { - let hash = this.config.str(0); + const hash = this.config.str(0); let txs, tx; if (util.isBase58(hash)) { @@ -191,8 +191,8 @@ CLI.prototype.getBlock = async function getBlock() { }; CLI.prototype.getCoin = async function getCoin() { - let hash = this.config.str(0); - let index = this.config.num(1); + const hash = this.config.str(0); + const index = this.config.num(1); let coins, coin; if (util.isBase58(hash)) { @@ -212,20 +212,20 @@ CLI.prototype.getCoin = async function getCoin() { }; CLI.prototype.getWalletHistory = async function getWalletHistory() { - let account = this.config.str('account'); - let txs = await this.wallet.getHistory(account); + const account = this.config.str('account'); + const txs = await this.wallet.getHistory(account); this.log(txs); }; CLI.prototype.getWalletPending = async function getWalletPending() { - let account = this.config.str('account'); - let txs = await this.wallet.getPending(account); + const account = this.config.str('account'); + const txs = await this.wallet.getPending(account); this.log(txs); }; CLI.prototype.getWalletCoins = async function getWalletCoins() { - let account = this.config.str('account'); - let coins = await this.wallet.getCoins(account); + const account = this.config.str('account'); + const coins = await this.wallet.getCoins(account); this.log(coins); }; @@ -266,13 +266,13 @@ CLI.prototype.listenWallet = async function listenWallet() { }; CLI.prototype.getBalance = async function getBalance() { - let account = this.config.str('account'); - let balance = await this.wallet.getBalance(account); + const account = this.config.str('account'); + const balance = await this.wallet.getBalance(account); this.log(balance); }; CLI.prototype.getMempool = async function getMempool() { - let txs = await this.client.getMempool(); + const txs = await this.client.getMempool(); this.log(txs); }; @@ -334,56 +334,56 @@ CLI.prototype.createTX = async function createTX() { }; CLI.prototype.signTX = async function signTX() { - let passphrase = this.config.str('passphrase'); - let raw = this.config.str([0, 'tx']); - let tx = await this.wallet.sign(raw, { passphrase }); + const passphrase = this.config.str('passphrase'); + const raw = this.config.str([0, 'tx']); + const tx = await this.wallet.sign(raw, { passphrase }); this.log(tx); }; CLI.prototype.zapWallet = async function zapWallet() { - let age = this.config.num([0, 'age'], 72 * 60 * 60); + const age = this.config.num([0, 'age'], 72 * 60 * 60); await this.wallet.zap(this.config.str('account'), age); this.log('Zapped!'); }; CLI.prototype.broadcast = async function broadcast() { - let raw = this.config.str([0, 'tx']); - let tx = await this.client.broadcast(raw); + const raw = this.config.str([0, 'tx']); + const tx = await this.client.broadcast(raw); this.log('Broadcasted:'); this.log(tx); }; CLI.prototype.viewTX = async function viewTX() { - let raw = this.config.str([0, 'tx']); - let tx = await this.wallet.fill(raw); + const raw = this.config.str([0, 'tx']); + const tx = await this.wallet.fill(raw); this.log(tx); }; CLI.prototype.getDetails = async function getDetails() { - let hash = this.config.str(0); - let details = await this.wallet.getTX(hash); + const hash = this.config.str(0); + const details = await this.wallet.getTX(hash); this.log(details); }; CLI.prototype.getWalletBlocks = async function getWalletBlocks() { - let blocks = await this.wallet.getBlocks(); + const blocks = await this.wallet.getBlocks(); this.log(blocks); }; CLI.prototype.getWalletBlock = async function getWalletBlock() { - let height = this.config.num(0); - let block = await this.wallet.getBlock(height); + const height = this.config.num(0); + const block = await this.wallet.getBlock(height); this.log(block); }; CLI.prototype.retoken = async function retoken() { - let result = await this.wallet.retoken(); + const result = await this.wallet.retoken(); this.log(result); }; CLI.prototype.rescan = async function rescan() { - let height = this.config.num(0); + const height = this.config.num(0); await this.client.rescan(height); this.log('Rescanning...'); }; @@ -410,7 +410,7 @@ CLI.prototype.resendWallet = async function resendWallet() { }; CLI.prototype.backup = async function backup() { - let path = this.config.str(0); + const path = this.config.str(0); await this.client.backup(path); @@ -418,8 +418,8 @@ CLI.prototype.backup = async function backup() { }; CLI.prototype.importKey = async function importKey() { - let key = this.config.str(0); - let account = this.config.str('account'); + const key = this.config.str(0); + const account = this.config.str('account'); if (!key) throw new Error('No key for import.'); @@ -440,8 +440,8 @@ CLI.prototype.importKey = async function importKey() { }; CLI.prototype.importAddress = async function importKey() { - let address = this.config.str(0); - let account = this.config.str('account'); + const address = this.config.str(0); + const account = this.config.str('account'); await this.wallet.importAddress(account, address); this.log('Imported address.'); }; @@ -452,18 +452,18 @@ CLI.prototype.lock = async function lock() { }; CLI.prototype.unlock = async function unlock() { - let passphrase = this.config.str(0); - let timeout = this.config.num(1); + const passphrase = this.config.str(0); + const timeout = this.config.num(1); await this.wallet.unlock(passphrase, timeout); this.log('Unlocked.'); }; CLI.prototype.rpc = async function rpc() { - let method = this.argv.shift(); - let params = []; + const method = this.argv.shift(); + const params = []; let result; - for (let arg of this.argv) { + for (const arg of this.argv) { let param; try { param = JSON.parse(arg); @@ -691,7 +691,7 @@ CLI.prototype.destroy = function destroy() { }; async function main() { - let cli = new CLI(); + const cli = new CLI(); await cli.open(); await cli.destroy(); } diff --git a/examples/client.js b/examples/client.js index bce7efae8..423fd6ff3 100644 --- a/examples/client.js +++ b/examples/client.js @@ -71,7 +71,7 @@ async function sendTX(addr, value) { } async function callNodeApi() { - let info = await wallet.client.getInfo(); + const info = await wallet.client.getInfo(); let json; console.log('Server Info:'); @@ -84,7 +84,7 @@ async function callNodeApi() { } (async () => { - let wdb = node.require('walletdb'); + const wdb = node.require('walletdb'); let w, acct, hash, balance, tx; await node.open(); diff --git a/examples/plugin.js b/examples/plugin.js index 3f9361bec..78f4371dc 100644 --- a/examples/plugin.js +++ b/examples/plugin.js @@ -35,7 +35,7 @@ const node = new FullNode({ node.use(MyPlugin); (async () => { - let plugin = node.require('my-plugin'); + const plugin = node.require('my-plugin'); await node.open(); diff --git a/examples/tx.js b/examples/tx.js index 42cfed458..5058d028e 100644 --- a/examples/tx.js +++ b/examples/tx.js @@ -4,10 +4,10 @@ const bcoin = require('bcoin'); const assert = require('assert'); (async () => { - let master = bcoin.hd.generate(); - let key = master.derivePath('m/44/0/0/0/0'); - let keyring = new bcoin.keyring(key.privateKey); - let cb = new bcoin.mtx(); + const master = bcoin.hd.generate(); + const key = master.derivePath('m/44/0/0/0/0'); + const keyring = new bcoin.keyring(key.privateKey); + const cb = new bcoin.mtx(); cb.addInput({ prevout: new bcoin.outpoint(), @@ -22,16 +22,16 @@ const assert = require('assert'); }); // Our available coins. - let coins = []; + const coins = []; // Convert the coinbase output to a Coin // object and add it to our available coins. // In reality you might get these coins from a wallet. - let coin = bcoin.coin.fromTX(cb, 0, -1); + const coin = bcoin.coin.fromTX(cb, 0, -1); coins.push(coin); // Create our redeeming transaction. - let mtx = new bcoin.mtx(); + const mtx = new bcoin.mtx(); // Send 10,000 satoshis to ourself. mtx.addOutput({ @@ -63,7 +63,7 @@ const assert = require('assert'); // Commit our transaction and make it immutable. // This turns it from an MTX into a TX. - let tx = mtx.toTX(); + const tx = mtx.toTX(); // The transaction should still verify. // Regular transactions require a coin diff --git a/examples/wallet.js b/examples/wallet.js index 7268dfe79..2727969e7 100644 --- a/examples/wallet.js +++ b/examples/wallet.js @@ -6,7 +6,7 @@ const MTX = require('bcoin/lib/primitives/mtx'); const Outpoint = require('bcoin/lib/primitives/outpoint'); function dummy() { - let hash = random.randomBytes(32).toString('hex'); + const hash = random.randomBytes(32).toString('hex'); return new Outpoint(hash, 0); } diff --git a/lib/bip70/payment.js b/lib/bip70/payment.js index 7c0ff6e12..d5ab654b9 100644 --- a/lib/bip70/payment.js +++ b/lib/bip70/payment.js @@ -51,16 +51,16 @@ Payment.prototype.fromOptions = function fromOptions(options) { if (options.transactions) { assert(Array.isArray(options.transactions)); - for (let item of options.transactions) { - let tx = new TX(item); + for (const item of options.transactions) { + const tx = new TX(item); this.transactions.push(tx); } } if (options.refundTo) { assert(Array.isArray(options.refundTo)); - for (let item of options.refundTo) { - let output = new Output(item); + for (const item of options.refundTo) { + const output = new Output(item); this.refundTo.push(output); } } @@ -111,18 +111,18 @@ Payment.prototype.getData = PaymentDetails.prototype.getData; */ Payment.prototype.fromRaw = function fromRaw(data) { - let br = new ProtoReader(data); + const br = new ProtoReader(data); this.merchantData = br.readFieldBytes(1, true); while (br.nextTag() === 2) { - let tx = TX.fromRaw(br.readFieldBytes(2)); + const tx = TX.fromRaw(br.readFieldBytes(2)); this.transactions.push(tx); } while (br.nextTag() === 3) { - let op = new ProtoReader(br.readFieldBytes(3)); - let output = new Output(); + const op = new ProtoReader(br.readFieldBytes(3)); + const output = new Output(); output.value = op.readFieldU64(1, true); output.script = Script.fromRaw(op.readFieldBytes(2, true)); this.refundTo.push(output); @@ -151,16 +151,16 @@ Payment.fromRaw = function fromRaw(data, enc) { */ Payment.prototype.toRaw = function toRaw() { - let bw = new ProtoWriter(); + const bw = new ProtoWriter(); if (this.merchantData) bw.writeFieldBytes(1, this.merchantData); - for (let tx of this.transactions) + for (const tx of this.transactions) bw.writeFieldBytes(2, tx.toRaw()); - for (let output of this.refundTo) { - let op = new ProtoWriter(); + for (const output of this.refundTo) { + const op = new ProtoWriter(); op.writeFieldU64(1, output.value); op.writeFieldBytes(2, output.script.toRaw()); bw.writeFieldBytes(3, op.render()); diff --git a/lib/bip70/paymentack.js b/lib/bip70/paymentack.js index 0ded9bcc6..b755ee848 100644 --- a/lib/bip70/paymentack.js +++ b/lib/bip70/paymentack.js @@ -68,7 +68,7 @@ PaymentACK.fromOptions = function fromOptions(options) { */ PaymentACK.prototype.fromRaw = function fromRaw(data) { - let br = new ProtoReader(data); + const br = new ProtoReader(data); this.payment.fromRaw(br.readFieldBytes(1)); this.memo = br.readFieldString(2, true); @@ -94,7 +94,7 @@ PaymentACK.fromRaw = function fromRaw(data, enc) { */ PaymentACK.prototype.toRaw = function toRaw() { - let bw = new ProtoWriter(); + const bw = new ProtoWriter(); bw.writeFieldBytes(1, this.payment.toRaw()); diff --git a/lib/bip70/paymentdetails.js b/lib/bip70/paymentdetails.js index 94904c3ba..746ca5b84 100644 --- a/lib/bip70/paymentdetails.js +++ b/lib/bip70/paymentdetails.js @@ -57,8 +57,8 @@ PaymentDetails.prototype.fromOptions = function fromOptions(options) { if (options.outputs) { assert(Array.isArray(options.outputs)); - for (let item of options.outputs) { - let output = new Output(item); + for (const item of options.outputs) { + const output = new Output(item); this.outputs.push(output); } } @@ -167,13 +167,13 @@ PaymentDetails.prototype.getData = function getData(enc) { */ PaymentDetails.prototype.fromRaw = function fromRaw(data) { - let br = new ProtoReader(data); + const br = new ProtoReader(data); this.network = br.readFieldString(1, true); while (br.nextTag() === 2) { - let op = new ProtoReader(br.readFieldBytes(2)); - let output = new Output(); + const op = new ProtoReader(br.readFieldBytes(2)); + const output = new Output(); output.value = op.readFieldU64(1, true); output.script.fromRaw(op.readFieldBytes(2, true)); this.outputs.push(output); @@ -206,13 +206,13 @@ PaymentDetails.fromRaw = function fromRaw(data, enc) { */ PaymentDetails.prototype.toRaw = function toRaw() { - let bw = new ProtoWriter(); + const bw = new ProtoWriter(); if (this.network != null) bw.writeFieldString(1, this.network); - for (let output of this.outputs) { - let op = new ProtoWriter(); + for (const output of this.outputs) { + const op = new ProtoWriter(); op.writeFieldU64(1, output.value); op.writeFieldBytes(2, output.script.toRaw()); bw.writeFieldBytes(2, op.render()); diff --git a/lib/bip70/paymentrequest.js b/lib/bip70/paymentrequest.js index d76fc9a7d..52a1e305a 100644 --- a/lib/bip70/paymentrequest.js +++ b/lib/bip70/paymentrequest.js @@ -96,7 +96,7 @@ PaymentRequest.fromOptions = function fromOptions(options) { */ PaymentRequest.prototype.fromRaw = function fromRaw(data) { - let br = new ProtoReader(data); + const br = new ProtoReader(data); this.version = br.readFieldU32(1, true); this.pkiType = br.readFieldString(2, true); @@ -125,7 +125,7 @@ PaymentRequest.fromRaw = function fromRaw(data, enc) { */ PaymentRequest.prototype.toRaw = function toRaw() { - let bw = new ProtoWriter(); + const bw = new ProtoWriter(); if (this.version !== -1) bw.writeFieldU32(1, this.version); @@ -175,7 +175,7 @@ PaymentRequest.prototype.getAlgorithm = function getAlgorithm() { */ PaymentRequest.prototype.signatureData = function signatureData() { - let signature = this.signature; + const signature = this.signature; let data; this.signature = Buffer.alloc(0); @@ -193,7 +193,7 @@ PaymentRequest.prototype.signatureData = function signatureData() { */ PaymentRequest.prototype.signatureHash = function signatureHash() { - let alg = this.getAlgorithm(); + const alg = this.getAlgorithm(); return digest.hash(alg.hash, this.signatureData()); }; @@ -203,13 +203,13 @@ PaymentRequest.prototype.signatureHash = function signatureHash() { */ PaymentRequest.prototype.setChain = function setChain(chain) { - let bw = new ProtoWriter(); + const bw = new ProtoWriter(); assert(Array.isArray(chain), 'Chain must be an array.'); for (let cert of chain) { if (typeof cert === 'string') { - let pem = PEM.decode(cert); + const pem = PEM.decode(cert); assert(pem.type === 'certificate', 'Bad certificate PEM.'); cert = pem.data; } @@ -226,7 +226,7 @@ PaymentRequest.prototype.setChain = function setChain(chain) { */ PaymentRequest.prototype.getChain = function getChain() { - let chain = []; + const chain = []; let br; if (!this.pkiData) diff --git a/lib/bip70/x509.js b/lib/bip70/x509.js index f7e0f3980..baf5258b5 100644 --- a/lib/bip70/x509.js +++ b/lib/bip70/x509.js @@ -86,9 +86,9 @@ x509.curves = { */ x509.getSubjectOID = function getSubjectOID(cert, oid) { - let subject = cert.tbs.subject; + const subject = cert.tbs.subject; - for (let entry of subject) { + for (const entry of subject) { if (entry.type === oid) return entry.value; } @@ -125,8 +125,8 @@ x509.getCAName = function getCAName(cert) { */ x509.isTrusted = function isTrusted(cert) { - let fingerprint = digest.sha256(cert.raw); - let hash = fingerprint.toString('hex'); + const fingerprint = digest.sha256(cert.raw); + const hash = fingerprint.toString('hex'); return x509.trusted.has(hash); }; @@ -142,7 +142,7 @@ x509.setTrust = function setTrust(certs) { let hash; if (typeof cert === 'string') { - let pem = PEM.decode(cert); + const pem = PEM.decode(cert); assert(pem.type === 'certificate', 'Must add certificates to trust.'); cert = pem.data; } @@ -185,8 +185,8 @@ x509.setFingerprints = function setFingerprints(hashes) { */ x509.getKeyAlgorithm = function getKeyAlgorithm(cert) { - let oid = cert.tbs.pubkey.alg.alg; - let alg = x509.oid[oid]; + const oid = cert.tbs.pubkey.alg.alg; + const alg = x509.oid[oid]; if (!alg) throw new Error(`Unknown key algorithm: ${oid}.`); @@ -201,8 +201,8 @@ x509.getKeyAlgorithm = function getKeyAlgorithm(cert) { */ x509.getSigAlgorithm = function getSigAlgorithm(cert) { - let oid = cert.sigAlg.alg; - let alg = x509.oid[oid]; + const oid = cert.sigAlg.alg; + const alg = x509.oid[oid]; if (!alg || !alg.hash) throw new Error(`Unknown signature algorithm: ${oid}.`); @@ -254,9 +254,9 @@ x509.parse = function parse(der) { */ x509.getPublicKey = function getPublicKey(cert) { - let alg = x509.getKeyAlgorithm(cert); - let key = cert.tbs.pubkey.pubkey; - let params = cert.tbs.pubkey.alg.params; + const alg = x509.getKeyAlgorithm(cert); + const key = cert.tbs.pubkey.pubkey; + const params = cert.tbs.pubkey.alg.params; let curve; if (alg.key === 'ecdsa') { @@ -281,8 +281,8 @@ x509.getPublicKey = function getPublicKey(cert) { */ x509.verifyTime = function verifyTime(cert) { - let time = cert.tbs.validity; - let now = util.now(); + const time = cert.tbs.validity; + const now = util.now(); return now > time.notBefore && now < time.notAfter; }; @@ -315,8 +315,8 @@ x509.getSigningKey = function getSigningKey(key, chain) { curve: curve }; } else { - let cert = x509.parse(chain[0]); - let pub = x509.getPublicKey(cert); + const cert = x509.parse(chain[0]); + const pub = x509.getPublicKey(cert); key = { alg: pub.alg, @@ -339,7 +339,7 @@ x509.getSigningKey = function getSigningKey(key, chain) { */ x509.signSubject = function signSubject(hash, msg, key, chain) { - let priv = x509.getSigningKey(key, chain); + const priv = x509.getSigningKey(key, chain); return pk.sign(hash, msg, priv); }; @@ -371,7 +371,7 @@ x509.getVerifyKey = function getVerifyKey(chain) { */ x509.verifySubject = function verifySubject(hash, msg, sig, chain) { - let key = x509.getVerifyKey(chain); + const key = x509.getVerifyKey(chain); return pk.verify(hash, msg, sig, key); }; @@ -382,10 +382,10 @@ x509.verifySubject = function verifySubject(hash, msg, sig, chain) { */ x509.parseChain = function parseChain(chain) { - let certs = []; + const certs = []; - for (let item of chain) { - let cert = x509.parse(item); + for (const item of chain) { + const cert = x509.parse(item); certs.push(cert); } @@ -399,7 +399,7 @@ x509.parseChain = function parseChain(chain) { */ x509.verifyTimes = function verifyTimes(chain) { - for (let cert of chain) { + for (const cert of chain) { if (!x509.verifyTime(cert)) return false; } @@ -422,7 +422,7 @@ x509.verifyTrust = function verifyTrust(chain) { // Make sure we trust one // of the certs in the chain. - for (let cert of chain) { + for (const cert of chain) { // If any certificate in the chain // is trusted, assume we also trust // the parent. @@ -440,7 +440,7 @@ x509.verifyTrust = function verifyTrust(chain) { */ x509.verifyChain = function verifyChain(certs) { - let chain = x509.parseChain(certs); + const chain = x509.parseChain(certs); // Parse certificates and // check validity time. @@ -449,12 +449,12 @@ x509.verifyChain = function verifyChain(certs) { // Verify signatures. for (let i = 1; i < chain.length; i++) { - let child = chain[i - 1]; - let parent = chain[i]; - let alg = x509.getSigAlgorithm(child); - let key = x509.getPublicKey(parent); - let msg = child.tbs.raw; - let sig = child.sig; + const child = chain[i - 1]; + const parent = chain[i]; + const alg = x509.getSigAlgorithm(child); + const key = x509.getPublicKey(parent); + const msg = child.tbs.raw; + const sig = child.sig; if (!pk.verify(alg.hash, msg, sig, key)) throw new Error(`${alg.key} verification failed for chain.`); diff --git a/lib/blockchain/chain.js b/lib/blockchain/chain.js index 232e963b7..149cebb17 100644 --- a/lib/blockchain/chain.js +++ b/lib/blockchain/chain.js @@ -181,7 +181,7 @@ Chain.prototype.verifyContext = async function verifyContext(block, prev, flags) */ Chain.prototype.verifyBlock = async function verifyBlock(block) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._verifyBlock(block); } finally { @@ -199,7 +199,7 @@ Chain.prototype.verifyBlock = async function verifyBlock(block) { */ Chain.prototype._verifyBlock = async function verifyBlock(block) { - let flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; + const flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; return await this.verifyContext(block, this.tip, flags); }; @@ -226,10 +226,10 @@ Chain.prototype.isGenesis = function isGenesis(block) { */ Chain.prototype.verify = async function verify(block, prev, flags) { - let deployments = this.network.deployments; - let hash = block.hash('hex'); - let now = this.network.now(); - let height = prev.height + 1; + const deployments = this.network.deployments; + const hash = block.hash('hex'); + const now = this.network.now(); + const height = prev.height + 1; let time, mtp, commit, state, bits; assert(typeof flags === 'number'); @@ -264,7 +264,7 @@ Chain.prototype.verify = async function verify(block, prev, flags) { // Non-contextual checks. if (flags & common.flags.VERIFY_BODY) { - let [valid, reason, score] = block.checkBody(); + const [valid, reason, score] = block.checkBody(); if (!valid) throw new VerifyError(block, 'invalid', reason, score, true); @@ -334,7 +334,7 @@ Chain.prototype.verify = async function verify(block, prev, flags) { // Transactions must be finalized with // regards to nSequence and nLockTime. - for (let tx of block.txs) { + for (const tx of block.txs) { if (!tx.isFinal(height, time)) { throw new VerifyError(block, 'invalid', @@ -415,9 +415,9 @@ Chain.prototype.verify = async function verify(block, prev, flags) { */ Chain.prototype.getDeployments = async function getDeployments(time, prev) { - let deployments = this.network.deployments; - let height = prev.height + 1; - let state = new DeploymentState(); + const deployments = this.network.deployments; + const height = prev.height + 1; + const state = new DeploymentState(); let witness; // For some reason bitcoind has p2sh in the @@ -480,7 +480,7 @@ Chain.prototype.getDeployments = async function getDeployments(time, prev) { // assumption that deployment checks should // only ever examine the values of the // previous block (necessary for mining). - let mtp = await prev.getMedianTime(time); + const mtp = await prev.getMedianTime(time); if (mtp >= 1501545600 && mtp <= 1510704000) state.bip148 = true; } @@ -547,11 +547,11 @@ Chain.prototype.verifyDuplicates = async function verifyDuplicates(block, prev, return; // Check all transactions. - for (let tx of block.txs) { - let result = await this.db.hasCoins(tx); + for (const tx of block.txs) { + const result = await this.db.hasCoins(tx); if (result) { - let height = prev.height + 1; + const height = prev.height + 1; // Blocks 91842 and 91880 created duplicate // txids by using the same exact output script @@ -586,11 +586,11 @@ Chain.prototype.verifyDuplicates = async function verifyDuplicates(block, prev, */ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { - let interval = this.network.halvingInterval; - let view = new CoinView(); - let height = prev.height + 1; - let historical = prev.isHistorical(); - let jobs = []; + const interval = this.network.halvingInterval; + const view = new CoinView(); + const height = prev.height + 1; + const historical = prev.isHistorical(); + const jobs = []; let sigops = 0; let reward = 0; @@ -599,7 +599,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { // Check all transactions for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; // Ensure tx is not double spending an output. if (i > 0) { @@ -621,7 +621,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { // Verify sequence locks. if (i > 0 && tx.version >= 2) { - let valid = await this.verifyLocks(prev, tx, view, state.lockFlags); + const valid = await this.verifyLocks(prev, tx, view, state.lockFlags); if (!valid) { throw new VerifyError(block, @@ -643,7 +643,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { // Contextual sanity checks. if (i > 0) { - let [fee, reason, score] = tx.checkInputs(view, height); + const [fee, reason, score] = tx.checkInputs(view, height); if (fee === -1) { throw new VerifyError(block, @@ -682,7 +682,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { // Push onto verification queue. for (let i = 1; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; jobs.push(tx.verifyAsync(view, state.flags, this.workers)); } @@ -705,7 +705,7 @@ Chain.prototype.verifyInputs = async function verifyInputs(block, prev, state) { */ Chain.prototype.checkHeight = function checkHeight(hash) { - let entry = this.db.getCache(hash); + const entry = this.db.getCache(hash); if (!entry) return -1; @@ -753,10 +753,10 @@ Chain.prototype.findFork = async function findFork(fork, longer) { */ Chain.prototype.reorganize = async function reorganize(competitor) { - let tip = this.tip; - let fork = await this.findFork(tip, competitor); - let disconnect = []; - let connect = []; + const tip = this.tip; + const fork = await this.findFork(tip, competitor); + const disconnect = []; + const connect = []; let entry; assert(fork, 'No free space or data corruption.'); @@ -779,7 +779,7 @@ Chain.prototype.reorganize = async function reorganize(competitor) { // Disconnect blocks/txs. for (let i = 0; i < disconnect.length; i++) { - let entry = disconnect[i]; + const entry = disconnect[i]; await this.disconnect(entry); } @@ -787,7 +787,7 @@ Chain.prototype.reorganize = async function reorganize(competitor) { // We don't want to connect the new tip here. // That will be done outside in setBestChain. for (let i = connect.length - 1; i >= 1; i--) { - let entry = connect[i]; + const entry = connect[i]; await this.reconnect(entry); } @@ -812,9 +812,9 @@ Chain.prototype.reorganize = async function reorganize(competitor) { */ Chain.prototype.reorganizeSPV = async function reorganizeSPV(competitor) { - let tip = this.tip; - let fork = await this.findFork(tip, competitor); - let disconnect = []; + const tip = this.tip; + const fork = await this.findFork(tip, competitor); + const disconnect = []; let entry = tip; assert(fork, 'No free space or data corruption.'); @@ -834,9 +834,9 @@ Chain.prototype.reorganizeSPV = async function reorganizeSPV(competitor) { // Emit disconnection events now that // the chain has successfully reset. - for (let entry of disconnect) { - let headers = entry.toHeaders(); - let view = new CoinView(); + for (const entry of disconnect) { + const headers = entry.toHeaders(); + const view = new CoinView(); await this.fire('disconnect', entry, headers, view); } @@ -897,7 +897,7 @@ Chain.prototype.disconnect = async function disconnect(entry) { */ Chain.prototype.reconnect = async function reconnect(entry) { - let flags = common.flags.VERIFY_NONE; + const flags = common.flags.VERIFY_NONE; let block = await this.db.getBlock(entry.hash); let prev, view, state; @@ -1067,7 +1067,7 @@ Chain.prototype.saveAlternate = async function saveAlternate(entry, block, prev, */ Chain.prototype.reset = async function reset(block) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._reset(block, false); } finally { @@ -1084,7 +1084,7 @@ Chain.prototype.reset = async function reset(block) { */ Chain.prototype._reset = async function reset(block, silent) { - let tip = await this.db.reset(block); + const tip = await this.db.reset(block); let state; // Reset state. @@ -1118,7 +1118,7 @@ Chain.prototype._reset = async function reset(block, silent) { */ Chain.prototype.replay = async function replay(block) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._replay(block, true); } finally { @@ -1136,7 +1136,7 @@ Chain.prototype.replay = async function replay(block) { */ Chain.prototype._replay = async function replay(block, silent) { - let entry = await this.db.getEntry(block); + const entry = await this.db.getEntry(block); if (!entry) throw new Error('Block not found.'); @@ -1158,7 +1158,7 @@ Chain.prototype._replay = async function replay(block, silent) { */ Chain.prototype.invalidate = async function invalidate(hash) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._invalidate(hash); } finally { @@ -1185,7 +1185,7 @@ Chain.prototype._invalidate = async function _invalidate(hash) { */ Chain.prototype.prune = async function prune() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this.db.prune(this.tip.hash); } finally { @@ -1203,7 +1203,7 @@ Chain.prototype.prune = async function prune() { */ Chain.prototype.scan = async function scan(start, filter, iter) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this.db.scan(start, filter, iter); } finally { @@ -1221,8 +1221,8 @@ Chain.prototype.scan = async function scan(start, filter, iter) { */ Chain.prototype.add = async function add(block, flags, id) { - let hash = block.hash('hex'); - let unlock = await this.locker.lock(hash); + const hash = block.hash('hex'); + const unlock = await this.locker.lock(hash); try { return await this._add(block, flags, id); } finally { @@ -1241,7 +1241,7 @@ Chain.prototype.add = async function add(block, flags, id) { */ Chain.prototype._add = async function add(block, flags, id) { - let hash = block.hash('hex'); + const hash = block.hash('hex'); let entry, prev; if (flags == null) @@ -1318,7 +1318,7 @@ Chain.prototype._add = async function add(block, flags, id) { */ Chain.prototype.connect = async function connect(prev, block, flags) { - let start = util.hrtime(); + const start = util.hrtime(); let entry; // Sanity check. @@ -1383,7 +1383,7 @@ Chain.prototype.handleOrphans = async function handleOrphans(entry) { let orphan = this.resolveOrphan(entry.hash); while (orphan) { - let {block, flags, id} = orphan; + const {block, flags, id} = orphan; try { entry = await this.connect(entry, block, flags); @@ -1518,8 +1518,8 @@ Chain.prototype.verifyCheckpoint = function verifyCheckpoint(prev, hash) { */ Chain.prototype.storeOrphan = function storeOrphan(block, flags, id) { - let hash = block.hash('hex'); - let height = block.getCoinbaseHeight(); + const hash = block.hash('hex'); + const height = block.getCoinbaseHeight(); let orphan = this.orphanPrev.get(block.prevBlock); // The orphan chain forked. @@ -1555,8 +1555,8 @@ Chain.prototype.storeOrphan = function storeOrphan(block, flags, id) { */ Chain.prototype.addOrphan = function addOrphan(orphan) { - let block = orphan.block; - let hash = block.hash('hex'); + const block = orphan.block; + const hash = block.hash('hex'); assert(!this.orphanMap.has(hash)); assert(!this.orphanPrev.has(block.prevBlock)); @@ -1576,8 +1576,8 @@ Chain.prototype.addOrphan = function addOrphan(orphan) { */ Chain.prototype.removeOrphan = function removeOrphan(orphan) { - let block = orphan.block; - let hash = block.hash('hex'); + const block = orphan.block; + const hash = block.hash('hex'); assert(this.orphanMap.has(hash)); assert(this.orphanPrev.has(block.prevBlock)); @@ -1608,7 +1608,7 @@ Chain.prototype.hasNextOrphan = function hasNextOrphan(hash) { */ Chain.prototype.resolveOrphan = function resolveOrphan(hash) { - let orphan = this.orphanPrev.get(hash); + const orphan = this.orphanPrev.get(hash); if (!orphan) return; @@ -1621,7 +1621,7 @@ Chain.prototype.resolveOrphan = function resolveOrphan(hash) { */ Chain.prototype.purgeOrphans = function purgeOrphans() { - let count = this.orphanMap.size; + const count = this.orphanMap.size; if (count === 0) return; @@ -1638,10 +1638,10 @@ Chain.prototype.purgeOrphans = function purgeOrphans() { */ Chain.prototype.limitOrphans = function limitOrphans() { - let now = util.now(); + const now = util.now(); let oldest; - for (let orphan of this.orphanMap.values()) { + for (const orphan of this.orphanMap.values()) { if (now < orphan.time + 60 * 60) { if (!oldest || orphan.time < oldest.time) oldest = orphan; @@ -1668,7 +1668,7 @@ Chain.prototype.limitOrphans = function limitOrphans() { */ Chain.prototype.hasInvalid = function hasInvalid(block) { - let hash = block.hash('hex'); + const hash = block.hash('hex'); if (this.invalid.has(hash)) return true; @@ -1780,7 +1780,7 @@ Chain.prototype.hasPending = function hasPending(hash) { */ Chain.prototype.getSpentView = async function getSpentView(tx) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this.db.getSpentView(tx); } finally { @@ -1841,9 +1841,9 @@ Chain.prototype.hasChainwork = function hasChainwork() { */ Chain.prototype.getProgress = function getProgress() { - let start = this.network.genesis.time; - let current = this.tip.time - start; - let end = util.now() - start - 40 * 60; + const start = this.network.genesis.time; + const current = this.tip.time - start; + const end = util.now() - start - 40 * 60; return Math.min(1, current / end); }; @@ -1857,7 +1857,7 @@ Chain.prototype.getProgress = function getProgress() { */ Chain.prototype.getLocator = async function getLocator(start) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._getLocator(start); } finally { @@ -1874,7 +1874,7 @@ Chain.prototype.getLocator = async function getLocator(start) { */ Chain.prototype._getLocator = async function getLocator(start) { - let hashes = []; + const hashes = []; let step = 1; let height, entry, main, hash; @@ -1911,7 +1911,7 @@ Chain.prototype._getLocator = async function getLocator(start) { hash = await this.db.getHash(height); assert(hash); } else { - let entry = await entry.getAncestor(height); + const entry = await entry.getAncestor(height); assert(entry); hash = entry.hash; } @@ -1934,7 +1934,7 @@ Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) { assert(hash); for (;;) { - let orphan = this.orphanMap.get(hash); + const orphan = this.orphanMap.get(hash); if (!orphan) break; @@ -1955,7 +1955,7 @@ Chain.prototype.getOrphanRoot = function getOrphanRoot(hash) { */ Chain.prototype.getProofTime = function getProofTime(to, from) { - let pow = this.network.pow; + const pow = this.network.pow; let sign, work; if (to.chainwork.cmp(from.chainwork) > 0) { @@ -1996,7 +1996,7 @@ Chain.prototype.getCurrentTarget = async function getCurrentTarget() { */ Chain.prototype.getTarget = async function getTarget(time, prev) { - let pow = this.network.pow; + const pow = this.network.pow; let first, height; // Genesis @@ -2015,7 +2015,7 @@ Chain.prototype.getTarget = async function getTarget(time, prev) { while (prev.height !== 0 && prev.height % pow.retargetInterval !== 0 && prev.bits === pow.bits) { - let cache = prev.getPrevCache(); + const cache = prev.getPrevCache(); if (cache) { prev = cache; @@ -2048,8 +2048,8 @@ Chain.prototype.getTarget = async function getTarget(time, prev) { */ Chain.prototype.retarget = function retarget(prev, first) { - let pow = this.network.pow; - let targetTimespan = pow.targetTimespan; + const pow = this.network.pow; + const targetTimespan = pow.targetTimespan; let actualTimespan, target; if (pow.noRetargeting) @@ -2082,7 +2082,7 @@ Chain.prototype.retarget = function retarget(prev, first) { */ Chain.prototype.findLocator = async function findLocator(locator) { - for (let hash of locator) { + for (const hash of locator) { if (await this.db.isMainChain(hash)) return hash; } @@ -2102,7 +2102,7 @@ Chain.prototype.findLocator = async function findLocator(locator) { */ Chain.prototype.isActive = async function isActive(prev, deployment) { - let state = await this.getState(prev, deployment); + const state = await this.getState(prev, deployment); return state === thresholdStates.ACTIVE; }; @@ -2120,8 +2120,8 @@ Chain.prototype.isActive = async function isActive(prev, deployment) { Chain.prototype.getState = async function getState(prev, deployment) { let window = this.network.minerWindow; let threshold = this.network.activationThreshold; - let bit = deployment.bit; - let compute = []; + const bit = deployment.bit; + const compute = []; let entry, state; if (deployment.threshold !== -1) @@ -2131,7 +2131,7 @@ Chain.prototype.getState = async function getState(prev, deployment) { window = deployment.window; if (((prev.height + 1) % window) !== 0) { - let height = prev.height - ((prev.height + 1) % window); + const height = prev.height - ((prev.height + 1) % window); prev = await prev.getAncestor(height); if (!prev) @@ -2145,7 +2145,7 @@ Chain.prototype.getState = async function getState(prev, deployment) { state = thresholdStates.DEFINED; while (entry) { - let cached = this.db.stateCache.get(bit, entry); + const cached = this.db.stateCache.get(bit, entry); let time, height; if (cached !== -1) { @@ -2168,11 +2168,11 @@ Chain.prototype.getState = async function getState(prev, deployment) { } while (compute.length) { - let entry = compute.pop(); + const entry = compute.pop(); switch (state) { case thresholdStates.DEFINED: { - let time = await entry.getMedianTime(); + const time = await entry.getMedianTime(); if (time >= deployment.timeout) { state = thresholdStates.FAILED; @@ -2187,7 +2187,7 @@ Chain.prototype.getState = async function getState(prev, deployment) { break; } case thresholdStates.STARTED: { - let time = await entry.getMedianTime(); + const time = await entry.getMedianTime(); let block = entry; let count = 0; @@ -2242,8 +2242,8 @@ Chain.prototype.getState = async function getState(prev, deployment) { Chain.prototype.computeBlockVersion = async function computeBlockVersion(prev) { let version = 0; - for (let deployment of this.network.deploys) { - let state = await this.getState(prev, deployment); + for (const deployment of this.network.deploys) { + const state = await this.getState(prev, deployment); if (state === thresholdStates.LOCKED_IN || state === thresholdStates.STARTED) { @@ -2265,7 +2265,7 @@ Chain.prototype.computeBlockVersion = async function computeBlockVersion(prev) { */ Chain.prototype.getDeploymentState = async function getDeploymentState() { - let prev = await this.tip.getPrevious(); + const prev = await this.tip.getPrevious(); if (!prev) { assert(this.tip.isGenesis()); @@ -2289,14 +2289,14 @@ Chain.prototype.getDeploymentState = async function getDeploymentState() { */ Chain.prototype.verifyFinal = async function verifyFinal(prev, tx, flags) { - let height = prev.height + 1; + const height = prev.height + 1; // We can skip MTP if the locktime is height. if (tx.locktime < consensus.LOCKTIME_THRESHOLD) return tx.isFinal(height, -1); if (flags & common.lockFlags.MEDIAN_TIME_PAST) { - let time = await prev.getMedianTime(); + const time = await prev.getMedianTime(); return tx.isFinal(height, time); } @@ -2314,18 +2314,18 @@ Chain.prototype.verifyFinal = async function verifyFinal(prev, tx, flags) { */ Chain.prototype.getLocks = async function getLocks(prev, tx, view, flags) { - let mask = consensus.SEQUENCE_MASK; - let granularity = consensus.SEQUENCE_GRANULARITY; - let disableFlag = consensus.SEQUENCE_DISABLE_FLAG; - let typeFlag = consensus.SEQUENCE_TYPE_FLAG; - let hasFlag = flags & common.lockFlags.VERIFY_SEQUENCE; + const mask = consensus.SEQUENCE_MASK; + const granularity = consensus.SEQUENCE_GRANULARITY; + const disableFlag = consensus.SEQUENCE_DISABLE_FLAG; + const typeFlag = consensus.SEQUENCE_TYPE_FLAG; + const hasFlag = flags & common.lockFlags.VERIFY_SEQUENCE; let minHeight = -1; let minTime = -1; if (tx.isCoinbase() || tx.version < 2 || !hasFlag) return [minHeight, minTime]; - for (let {prevout, sequence} of tx.inputs) { + for (const {prevout, sequence} of tx.inputs) { let height, time, entry; if (sequence & disableFlag) @@ -2365,7 +2365,7 @@ Chain.prototype.getLocks = async function getLocks(prev, tx, view, flags) { */ Chain.prototype.verifyLocks = async function verifyLocks(prev, tx, view, flags) { - let [height, time] = await this.getLocks(prev, tx, view, flags); + const [height, time] = await this.getLocks(prev, tx, view, flags); let mtp; // Also catches case where diff --git a/lib/blockchain/chaindb.js b/lib/blockchain/chaindb.js index dbe2e0d74..d62be9732 100644 --- a/lib/blockchain/chaindb.js +++ b/lib/blockchain/chaindb.js @@ -185,7 +185,7 @@ ChainDB.prototype.batch = function batch() { */ ChainDB.prototype.drop = function drop() { - let batch = this.current; + const batch = this.current; assert(this.current); assert(this.pending); @@ -427,7 +427,7 @@ ChainDB.prototype.getEntry = function getEntry(block) { */ ChainDB.prototype.hasEntry = async function hasEntry(hash) { - let height = await this.getHeight(hash); + const height = await this.getHeight(hash); return height !== -1; }; @@ -447,7 +447,7 @@ ChainDB.prototype.getTip = function getTip() { */ ChainDB.prototype.getState = async function getState() { - let data = await this.db.get(layout.R); + const data = await this.db.get(layout.R); if (!data) return; @@ -462,9 +462,9 @@ ChainDB.prototype.getState = async function getState() { */ ChainDB.prototype.saveGenesis = async function saveGenesis() { - let genesis = this.network.genesisBlock; - let block = Block.fromRaw(genesis, 'hex'); - let entry = ChainEntry.fromBlock(this.chain, block); + const genesis = this.network.genesisBlock; + const block = Block.fromRaw(genesis, 'hex'); + const entry = ChainEntry.fromBlock(this.chain, block); this.logger.info('Writing genesis block to ChainDB.'); @@ -478,7 +478,7 @@ ChainDB.prototype.saveGenesis = async function saveGenesis() { */ ChainDB.prototype.getFlags = async function getFlags() { - let data = await this.db.get(layout.O); + const data = await this.db.get(layout.O); if (!data) return; @@ -494,8 +494,8 @@ ChainDB.prototype.getFlags = async function getFlags() { */ ChainDB.prototype.verifyFlags = async function verifyFlags(state) { - let options = this.options; - let flags = await this.getFlags(); + const options = this.options; + const flags = await this.getFlags(); let needsSave = false; let needsPrune = false; @@ -568,17 +568,17 @@ ChainDB.prototype.verifyFlags = async function verifyFlags(state) { */ ChainDB.prototype.getStateCache = async function getStateCache() { - let stateCache = new StateCache(this.network); + const stateCache = new StateCache(this.network); - let items = await this.db.range({ + const items = await this.db.range({ gte: layout.v(0, encoding.ZERO_HASH), lte: layout.v(255, encoding.MAX_HASH), values: true }); - for (let item of items) { - let [bit, hash] = layout.vv(item.key); - let state = item.value[0]; + for (const item of items) { + const [bit, hash] = layout.vv(item.key); + const state = item.value[0]; stateCache.insert(bit, hash, state); } @@ -591,7 +591,7 @@ ChainDB.prototype.getStateCache = async function getStateCache() { */ ChainDB.prototype.saveDeployments = function saveDeployments() { - let batch = this.db.batch(); + const batch = this.db.batch(); this.writeDeployments(batch); return batch.write(); }; @@ -602,11 +602,11 @@ ChainDB.prototype.saveDeployments = function saveDeployments() { */ ChainDB.prototype.writeDeployments = function writeDeployments(batch) { - let bw = new StaticWriter(1 + 17 * this.network.deploys.length); + const bw = new StaticWriter(1 + 17 * this.network.deploys.length); bw.writeU8(this.network.deploys.length); - for (let deployment of this.network.deploys) { + for (const deployment of this.network.deploys) { bw.writeU8(deployment.bit); bw.writeU32(deployment.startTime); bw.writeU32(deployment.timeout); @@ -625,8 +625,8 @@ ChainDB.prototype.writeDeployments = function writeDeployments(batch) { */ ChainDB.prototype.checkDeployments = async function checkDeployments() { - let raw = await this.db.get(layout.V); - let invalid = []; + const raw = await this.db.get(layout.V); + const invalid = []; let br, count; assert(raw, 'No deployment table found.'); @@ -635,12 +635,12 @@ ChainDB.prototype.checkDeployments = async function checkDeployments() { count = br.readU8(); for (let i = 0; i < count; i++) { - let bit = br.readU8(); - let start = br.readU32(); - let timeout = br.readU32(); - let threshold = br.read32(); - let window = br.read32(); - let deployment = this.network.byBit(bit); + const bit = br.readU8(); + const start = br.readU32(); + const timeout = br.readU32(); + const threshold = br.read32(); + const window = br.read32(); + const deployment = this.network.byBit(bit); if (deployment && start === deployment.startTime @@ -671,7 +671,7 @@ ChainDB.prototype.verifyDeployments = async function verifyDeployments() { if (e.type !== 'EncodingError') throw e; invalid = []; - for (let {bit} of this.network.deploys) + for (const {bit} of this.network.deploys) invalid.push(bit); } @@ -680,7 +680,7 @@ ChainDB.prototype.verifyDeployments = async function verifyDeployments() { batch = this.db.batch(); - for (let bit of invalid) { + for (const bit of invalid) { this.logger.warning('Versionbit deployment params modified.'); this.logger.warning('Invalidating cache for bit %d.', bit); await this.invalidateCache(bit, batch); @@ -701,12 +701,12 @@ ChainDB.prototype.verifyDeployments = async function verifyDeployments() { */ ChainDB.prototype.invalidateCache = async function invalidateCache(bit, batch) { - let keys = await this.db.keys({ + const keys = await this.db.keys({ gte: layout.v(bit, encoding.ZERO_HASH), lte: layout.v(bit, encoding.MAX_HASH) }); - for (let key of keys) + for (const key of keys) batch.del(key); }; @@ -718,11 +718,11 @@ ChainDB.prototype.invalidateCache = async function invalidateCache(bit, batch) { */ ChainDB.prototype.prune = async function prune(tip) { - let options = this.options; - let keepBlocks = this.network.block.keepBlocks; - let pruneAfter = this.network.block.pruneAfterHeight; + const options = this.options; + const keepBlocks = this.network.block.keepBlocks; + const pruneAfter = this.network.block.pruneAfterHeight; let flags = await this.getFlags(); - let height = await this.getHeight(tip); + const height = await this.getHeight(tip); let start, end, batch; if (flags.prune) @@ -736,7 +736,7 @@ ChainDB.prototype.prune = async function prune(tip) { batch = this.db.batch(); for (let i = start; i <= end; i++) { - let hash = await this.getHash(i); + const hash = await this.getHash(i); if (!hash) throw new Error(`Cannot find hash for ${i}.`); @@ -772,7 +772,7 @@ ChainDB.prototype.prune = async function prune(tip) { */ ChainDB.prototype.getNextHash = async function getNextHash(hash) { - let data = await this.db.get(layout.n(hash)); + const data = await this.db.get(layout.n(hash)); if (!data) return; @@ -849,9 +849,9 @@ ChainDB.prototype.getTips = function getTips() { */ ChainDB.prototype.readCoin = async function readCoin(prevout) { - let {hash, index} = prevout; - let key = prevout.toKey(); - let state = this.state; + const {hash, index} = prevout; + const key = prevout.toKey(); + const state = this.state; let raw; if (this.options.spv) @@ -882,8 +882,8 @@ ChainDB.prototype.readCoin = async function readCoin(prevout) { */ ChainDB.prototype.getCoin = async function getCoin(hash, index) { - let prevout = new Outpoint(hash, index); - let coin = await this.readCoin(prevout); + const prevout = new Outpoint(hash, index); + const coin = await this.readCoin(prevout); if (!coin) return; @@ -900,7 +900,7 @@ ChainDB.prototype.getCoin = async function getCoin(hash, index) { ChainDB.prototype.hasCoins = async function hasCoins(tx) { for (let i = 0; i < tx.outputs.length; i++) { - let key = layout.c(tx.hash(), i); + const key = layout.c(tx.hash(), i); if (await this.db.has(key)) return true; } @@ -915,13 +915,13 @@ ChainDB.prototype.hasCoins = async function hasCoins(tx) { */ ChainDB.prototype.getCoinView = async function getCoinView(tx) { - let view = new CoinView(); + const view = new CoinView(); - for (let {prevout} of tx.inputs) { - let coin = await this.readCoin(prevout); + for (const {prevout} of tx.inputs) { + const coin = await this.readCoin(prevout); if (!coin) { - let coins = new Coins(); + const coins = new Coins(); view.add(prevout.hash, coins); continue; } @@ -940,9 +940,9 @@ ChainDB.prototype.getCoinView = async function getCoinView(tx) { */ ChainDB.prototype.getSpentView = async function getSpentView(tx) { - let view = await this.getCoinView(tx); + const view = await this.getCoinView(tx); - for (let [hash, coins] of view.map) { + for (const [hash, coins] of view.map) { let meta; if (!coins.isEmpty()) @@ -967,7 +967,7 @@ ChainDB.prototype.getSpentView = async function getSpentView(tx) { */ ChainDB.prototype.getUndoCoins = async function getUndoCoins(hash) { - let data = await this.db.get(layout.u(hash)); + const data = await this.db.get(layout.u(hash)); if (!data) return new UndoCoins(); return UndoCoins.fromRaw(data); @@ -981,7 +981,7 @@ ChainDB.prototype.getUndoCoins = async function getUndoCoins(hash) { */ ChainDB.prototype.getBlock = async function getBlock(hash) { - let data = await this.getRawBlock(hash); + const data = await this.getRawBlock(hash); if (!data) return; @@ -1018,17 +1018,17 @@ ChainDB.prototype.getRawBlock = async function getRawBlock(block) { */ ChainDB.prototype.getBlockView = async function getBlockView(block) { - let view = new CoinView(); - let undo = await this.getUndoCoins(block.hash()); + const view = new CoinView(); + const undo = await this.getUndoCoins(block.hash()); if (undo.isEmpty()) return view; for (let i = block.txs.length - 1; i > 0; i--) { - let tx = block.txs[i]; + const tx = block.txs[i]; for (let j = tx.inputs.length - 1; j >= 0; j--) { - let input = tx.inputs[j]; + const input = tx.inputs[j]; undo.apply(view, input.prevout); } } @@ -1068,7 +1068,7 @@ ChainDB.prototype.getMeta = async function getMeta(hash) { */ ChainDB.prototype.getTX = async function getTX(hash) { - let meta = await this.getMeta(hash); + const meta = await this.getMeta(hash); if (!meta) return; return meta.tx; @@ -1094,7 +1094,7 @@ ChainDB.prototype.hasTX = function hasTX(hash) { */ ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { - let coins = []; + const coins = []; if (!this.options.indexAddress) return coins; @@ -1102,17 +1102,17 @@ ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { if (!Array.isArray(addrs)) addrs = [addrs]; - for (let addr of addrs) { - let hash = Address.getHash(addr); + for (const addr of addrs) { + const hash = Address.getHash(addr); - let keys = await this.db.keys({ + const keys = await this.db.keys({ gte: layout.C(hash, encoding.ZERO_HASH, 0), lte: layout.C(hash, encoding.MAX_HASH, 0xffffffff), parse: layout.Cc }); - for (let [hash, index] of keys) { - let coin = await this.getCoin(hash, index); + for (const [hash, index] of keys) { + const coin = await this.getCoin(hash, index); assert(coin); coins.push(coin); } @@ -1129,19 +1129,19 @@ ChainDB.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { */ ChainDB.prototype.getHashesByAddress = async function getHashesByAddress(addrs) { - let hashes = Object.create(null); + const hashes = Object.create(null); if (!this.options.indexTX || !this.options.indexAddress) return []; - for (let addr of addrs) { - let hash = Address.getHash(addr); + for (const addr of addrs) { + const hash = Address.getHash(addr); await this.db.keys({ gte: layout.T(hash, encoding.ZERO_HASH), lte: layout.T(hash, encoding.MAX_HASH), parse: (key) => { - let hash = layout.Tt(key); + const hash = layout.Tt(key); hashes[hash] = true; } }); @@ -1158,10 +1158,10 @@ ChainDB.prototype.getHashesByAddress = async function getHashesByAddress(addrs) */ ChainDB.prototype.getTXByAddress = async function getTXByAddress(addrs) { - let mtxs = await this.getMetaByAddress(addrs); - let out = []; + const mtxs = await this.getMetaByAddress(addrs); + const out = []; - for (let mtx of mtxs) + for (const mtx of mtxs) out.push(mtx.tx); return out; @@ -1175,7 +1175,7 @@ ChainDB.prototype.getTXByAddress = async function getTXByAddress(addrs) { */ ChainDB.prototype.getMetaByAddress = async function getTXByAddress(addrs) { - let txs = []; + const txs = []; let hashes; if (!this.options.indexTX || !this.options.indexAddress) @@ -1186,8 +1186,8 @@ ChainDB.prototype.getMetaByAddress = async function getTXByAddress(addrs) { hashes = await this.getHashesByAddress(addrs); - for (let hash of hashes) { - let tx = await this.getMeta(hash); + for (const hash of hashes) { + const tx = await this.getMeta(hash); assert(tx); txs.push(tx); } @@ -1225,8 +1225,8 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) { throw new Error('Cannot rescan an alternate chain.'); while (entry) { - let block = await this.getBlock(entry.hash); - let txs = []; + const block = await this.getBlock(entry.hash); + const txs = []; total++; @@ -1243,18 +1243,18 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) { entry.rhash(), entry.height); for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; let found = false; for (let j = 0; j < tx.outputs.length; j++) { - let output = tx.outputs[j]; - let hash = output.getHash(); + const output = tx.outputs[j]; + const hash = output.getHash(); if (!hash) continue; if (filter.test(hash)) { - let prevout = Outpoint.fromTX(tx, j); + const prevout = Outpoint.fromTX(tx, j); filter.add(prevout.toRaw()); found = true; } @@ -1268,7 +1268,7 @@ ChainDB.prototype.scan = async function scan(start, filter, iter) { if (i === 0) continue; - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { if (filter.test(prevout.toRaw())) { txs.push(tx); break; @@ -1318,7 +1318,7 @@ ChainDB.prototype.save = async function save(entry, block, view) { */ ChainDB.prototype._save = async function save(entry, block, view) { - let hash = block.hash(); + const hash = block.hash(); // Hash->height index. this.put(layout.h(hash), U32(entry.height)); @@ -1386,7 +1386,7 @@ ChainDB.prototype.reconnect = async function reconnect(entry, block, view) { */ ChainDB.prototype._reconnect = async function reconnect(entry, block, view) { - let hash = block.hash(); + const hash = block.hash(); assert(!entry.isGenesis()); @@ -1472,15 +1472,15 @@ ChainDB.prototype._disconnect = async function disconnect(entry, block) { */ ChainDB.prototype.saveUpdates = function saveUpdates() { - let updates = this.stateCache.updates; + const updates = this.stateCache.updates; if (updates.length === 0) return; this.logger.info('Saving %d state cache updates.', updates.length); - for (let update of updates) { - let {bit, hash} = update; + for (const update of updates) { + const {bit, hash} = update; this.put(layout.v(bit, hash), update.toRaw()); } }; @@ -1494,7 +1494,7 @@ ChainDB.prototype.saveUpdates = function saveUpdates() { */ ChainDB.prototype.reset = async function reset(block) { - let entry = await this.getEntry(block); + const entry = await this.getEntry(block); let tip; if (!entry) @@ -1571,14 +1571,14 @@ ChainDB.prototype.reset = async function reset(block) { */ ChainDB.prototype.removeChains = async function removeChains() { - let tips = await this.getTips(); + const tips = await this.getTips(); // Note that this has to be // one giant atomic write! this.start(); try { - for (let tip of tips) + for (const tip of tips) await this._removeChain(tip); } catch (e) { this.drop(); @@ -1636,7 +1636,7 @@ ChainDB.prototype._removeChain = async function removeChain(hash) { */ ChainDB.prototype.saveBlock = async function saveBlock(entry, block, view) { - let hash = block.hash(); + const hash = block.hash(); if (this.options.spv) return; @@ -1682,8 +1682,8 @@ ChainDB.prototype.removeBlock = async function removeBlock(entry) { */ ChainDB.prototype.saveView = function saveView(view) { - for (let [hash, coins] of view.map) { - for (let [index, coin] of coins.outputs) { + for (const [hash, coins] of view.map) { + for (const [index, coin] of coins.outputs) { let raw; if (coin.spent) { @@ -1710,7 +1710,7 @@ ChainDB.prototype.saveView = function saveView(view) { */ ChainDB.prototype.connectBlock = async function connectBlock(entry, block, view) { - let hash = block.hash(); + const hash = block.hash(); if (this.options.spv) return; @@ -1723,14 +1723,14 @@ ChainDB.prototype.connectBlock = async function connectBlock(entry, block, view) // Update chain state value. for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; if (i > 0) { - for (let {prevout} of tx.inputs) + for (const {prevout} of tx.inputs) this.pending.spend(view.getOutput(prevout)); } - for (let output of tx.outputs) { + for (const output of tx.outputs) { if (output.script.isUnspendable()) continue; @@ -1761,8 +1761,8 @@ ChainDB.prototype.connectBlock = async function connectBlock(entry, block, view) */ ChainDB.prototype.disconnectBlock = async function disconnectBlock(entry, block) { - let view = new CoinView(); - let hash = block.hash(); + const view = new CoinView(); + const hash = block.hash(); let undo; if (this.options.spv) @@ -1774,11 +1774,11 @@ ChainDB.prototype.disconnectBlock = async function disconnectBlock(entry, block) // Disconnect all transactions. for (let i = block.txs.length - 1; i >= 0; i--) { - let tx = block.txs[i]; + const tx = block.txs[i]; if (i > 0) { for (let j = tx.inputs.length - 1; j >= 0; j--) { - let {prevout} = tx.inputs[j]; + const {prevout} = tx.inputs[j]; undo.apply(view, prevout); this.pending.add(view.getOutput(prevout)); } @@ -1788,7 +1788,7 @@ ChainDB.prototype.disconnectBlock = async function disconnectBlock(entry, block) view.removeTX(tx, entry.height); for (let j = tx.outputs.length - 1; j >= 0; j--) { - let output = tx.outputs[j]; + const output = tx.outputs[j]; if (output.script.isUnspendable()) continue; @@ -1850,7 +1850,7 @@ ChainDB.prototype.pruneBlock = async function pruneBlock(entry) { */ ChainDB.prototype.saveFlags = function saveFlags() { - let flags = ChainFlags.fromOptions(this.options); + const flags = ChainFlags.fromOptions(this.options); return this.db.put(layout.O, flags.toRaw()); }; @@ -1864,16 +1864,16 @@ ChainDB.prototype.saveFlags = function saveFlags() { */ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { - let hash = tx.hash(); + const hash = tx.hash(); if (this.options.indexTX) { - let meta = TXMeta.fromTX(tx, entry, index); + const meta = TXMeta.fromTX(tx, entry, index); this.put(layout.t(hash), meta.toRaw()); if (this.options.indexAddress) { - let hashes = tx.getHashes(view); - for (let addr of hashes) + const hashes = tx.getHashes(view); + for (const addr of hashes) this.put(layout.T(addr, hash), null); } } @@ -1882,8 +1882,8 @@ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { return; if (!tx.isCoinbase()) { - for (let {prevout} of tx.inputs) { - let addr = view.getOutput(prevout).getHash(); + for (const {prevout} of tx.inputs) { + const addr = view.getOutput(prevout).getHash(); if (!addr) continue; @@ -1893,8 +1893,8 @@ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { } for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let addr = output.getHash(); + const output = tx.outputs[i]; + const addr = output.getHash(); if (!addr) continue; @@ -1911,13 +1911,13 @@ ChainDB.prototype.indexTX = function indexTX(tx, view, entry, index) { */ ChainDB.prototype.unindexTX = function unindexTX(tx, view) { - let hash = tx.hash(); + const hash = tx.hash(); if (this.options.indexTX) { this.del(layout.t(hash)); if (this.options.indexAddress) { - let hashes = tx.getHashes(view); - for (let addr of hashes) + const hashes = tx.getHashes(view); + for (const addr of hashes) this.del(layout.T(addr, hash)); } } @@ -1926,8 +1926,8 @@ ChainDB.prototype.unindexTX = function unindexTX(tx, view) { return; if (!tx.isCoinbase()) { - for (let {prevout} of tx.inputs) { - let addr = view.getOutput(prevout).getHash(); + for (const {prevout} of tx.inputs) { + const addr = view.getOutput(prevout).getHash(); if (!addr) continue; @@ -1937,8 +1937,8 @@ ChainDB.prototype.unindexTX = function unindexTX(tx, view) { } for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let addr = output.getHash(); + const output = tx.outputs[i]; + const addr = output.getHash(); if (!addr) continue; @@ -2011,7 +2011,7 @@ ChainFlags.fromOptions = function fromOptions(data) { }; ChainFlags.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(12); + const bw = new StaticWriter(12); let flags = 0; if (this.spv) @@ -2043,7 +2043,7 @@ ChainFlags.prototype.toRaw = function toRaw() { }; ChainFlags.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); let flags; this.network = Network.fromMagic(br.readU32()); @@ -2088,7 +2088,7 @@ ChainState.prototype.rhash = function rhash() { }; ChainState.prototype.clone = function clone() { - let state = new ChainState(); + const state = new ChainState(); state.tip = this.tip; state.tx = this.tx; state.coin = this.coin; @@ -2123,7 +2123,7 @@ ChainState.prototype.commit = function commit(hash) { }; ChainState.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(56); + const bw = new StaticWriter(56); bw.writeHash(this.tip); bw.writeU64(this.tx); bw.writeU64(this.coin); @@ -2132,8 +2132,8 @@ ChainState.prototype.toRaw = function toRaw() { }; ChainState.fromRaw = function fromRaw(data) { - let state = new ChainState(); - let br = new BufferReader(data); + const state = new ChainState(); + const br = new BufferReader(data); state.tip = br.readHash(); state.tx = br.readU53(); state.coin = br.readU53(); @@ -2158,14 +2158,14 @@ StateCache.prototype._init = function _init() { for (let i = 0; i < 32; i++) this.bits.push(null); - for (let {bit} of this.network.deploys) { + for (const {bit} of this.network.deploys) { assert(!this.bits[bit]); this.bits[bit] = new Map(); } }; StateCache.prototype.set = function set(bit, entry, state) { - let cache = this.bits[bit]; + const cache = this.bits[bit]; assert(cache); @@ -2176,7 +2176,7 @@ StateCache.prototype.set = function set(bit, entry, state) { }; StateCache.prototype.get = function get(bit, entry) { - let cache = this.bits[bit]; + const cache = this.bits[bit]; let state; assert(cache); @@ -2194,8 +2194,8 @@ StateCache.prototype.commit = function commit() { }; StateCache.prototype.drop = function drop() { - for (let {bit, hash} of this.updates) { - let cache = this.bits[bit]; + for (const {bit, hash} of this.updates) { + const cache = this.bits[bit]; assert(cache); cache.delete(hash); } @@ -2204,7 +2204,7 @@ StateCache.prototype.drop = function drop() { }; StateCache.prototype.insert = function insert(bit, hash, state) { - let cache = this.bits[bit]; + const cache = this.bits[bit]; assert(cache); cache.set(hash, state); }; diff --git a/lib/blockchain/chainentry.js b/lib/blockchain/chainentry.js index c024c064f..401961b83 100644 --- a/lib/blockchain/chainentry.js +++ b/lib/blockchain/chainentry.js @@ -129,7 +129,7 @@ ChainEntry.fromOptions = function fromOptions(chain, options, prev) { */ ChainEntry.prototype.getProof = function getProof() { - let target = consensus.fromCompact(this.bits); + const target = consensus.fromCompact(this.bits); if (target.isNeg() || target.cmpn(0) === 0) return new BN(0); return ChainEntry.MAX_CHAINWORK.div(target.iaddn(1)); @@ -142,7 +142,7 @@ ChainEntry.prototype.getProof = function getProof() { */ ChainEntry.prototype.getChainwork = function getChainwork(prev) { - let proof = this.getProof(); + const proof = this.getProof(); if (!prev) return proof; @@ -239,7 +239,7 @@ ChainEntry.prototype.getPrevCache = function getPrevCache() { */ ChainEntry.prototype.getNext = async function getNext() { - let hash = await this.chain.db.getNextHash(this.hash); + const hash = await this.chain.db.getNextHash(this.hash); if (!hash) return; return await this.chain.db.getEntry(hash); @@ -252,7 +252,7 @@ ChainEntry.prototype.getNext = async function getNext() { */ ChainEntry.prototype.getNextEntry = async function getNextEntry() { - let entry = await this.chain.db.getEntry(this.height + 1); + const entry = await this.chain.db.getEntry(this.height + 1); if (!entry) return; @@ -274,7 +274,7 @@ ChainEntry.prototype.getNextEntry = async function getNextEntry() { ChainEntry.prototype.getMedianTime = async function getMedianTime(time) { let timespan = ChainEntry.MEDIAN_TIMESPAN; let entry = this; - let median = []; + const median = []; // In case we ever want to check // the MTP of the _current_ block @@ -324,8 +324,8 @@ ChainEntry.prototype.isHistorical = function isHistorical() { */ ChainEntry.prototype.hasUnknown = function hasUnknown() { - let bits = this.version & consensus.VERSION_TOP_MASK; - let topBits = consensus.VERSION_TOP_BITS; + const bits = this.version & consensus.VERSION_TOP_MASK; + const topBits = consensus.VERSION_TOP_BITS; if ((bits >>> 0) !== topBits) return false; @@ -390,7 +390,7 @@ ChainEntry.fromBlock = function fromBlock(chain, block, prev) { */ ChainEntry.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(116); + const bw = new StaticWriter(116); bw.writeU32(this.version); bw.writeHash(this.prevBlock); @@ -411,8 +411,8 @@ ChainEntry.prototype.toRaw = function toRaw() { */ ChainEntry.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let hash = digest.hash256(br.readBytes(80)); + const br = new BufferReader(data, true); + const hash = digest.hash256(br.readBytes(80)); br.seek(-80); @@ -525,7 +525,7 @@ ChainEntry.prototype.toInv = function toInv() { */ ChainEntry.prototype.inspect = function inspect() { - let json = this.toJSON(); + const json = this.toJSON(); json.version = util.hex32(json.version); return json; }; diff --git a/lib/blockchain/layout.js b/lib/blockchain/layout.js index 7ea8c5c86..c36531210 100644 --- a/lib/blockchain/layout.js +++ b/lib/blockchain/layout.js @@ -62,7 +62,7 @@ const layout = { return pair(0x75, hash); }, v: function v(bit, hash) { - let key = Buffer.allocUnsafe(1 + 1 + 32); + const key = Buffer.allocUnsafe(1 + 1 + 32); assert(typeof bit === 'number'); key[0] = 0x76; key[1] = bit; @@ -169,14 +169,14 @@ function write(data, str, off) { } function pair(prefix, hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); key[0] = prefix; write(key, hash, 1); return key; } function ipair(prefix, num) { - let key = Buffer.allocUnsafe(5); + const key = Buffer.allocUnsafe(5); assert(typeof num === 'number'); key[0] = prefix; key.writeUInt32BE(num, 1, true); @@ -184,7 +184,7 @@ function ipair(prefix, num) { } function bpair(prefix, hash, index) { - let key = Buffer.allocUnsafe(37); + const key = Buffer.allocUnsafe(37); assert(typeof index === 'number'); key[0] = prefix; write(key, hash, 1); diff --git a/lib/btc/amount.js b/lib/btc/amount.js index b92669020..e3a5879c7 100644 --- a/lib/btc/amount.js +++ b/lib/btc/amount.js @@ -426,9 +426,9 @@ Amount.value = function _value(value, num) { Amount.parse = function parse(value, exp, num) { let negative = false; - let mult = pow10(exp); - let maxLo = modSafe(mult); - let maxHi = divSafe(mult); + const mult = pow10(exp); + const maxLo = modSafe(mult); + const maxHi = divSafe(mult); let parts, hi, lo, result; if (num && typeof value === 'number') { diff --git a/lib/btc/uri.js b/lib/btc/uri.js index addbdfcd6..9f8c08d38 100644 --- a/lib/btc/uri.js +++ b/lib/btc/uri.js @@ -156,7 +156,7 @@ URI.fromString = function fromString(str, network) { URI.prototype.toString = function toString() { let str = 'bitcoin:'; - let query = []; + const query = []; str += this.address.toString(); @@ -199,12 +199,12 @@ function BitcoinQuery() { } function parsePairs(str) { - let parts = str.split('&'); - let data = new BitcoinQuery(); + const parts = str.split('&'); + const data = new BitcoinQuery(); let size = 0; - for (let pair of parts) { - let index = pair.indexOf('='); + for (const pair of parts) { + const index = pair.indexOf('='); let key, value; if (index === -1) { diff --git a/lib/coins/coinentry.js b/lib/coins/coinentry.js index 1e19bf729..52f31c16b 100644 --- a/lib/coins/coinentry.js +++ b/lib/coins/coinentry.js @@ -55,7 +55,7 @@ CoinEntry.prototype.toOutput = function toOutput() { */ CoinEntry.prototype.toCoin = function toCoin(prevout) { - let coin = new Coin(); + const coin = new Coin(); coin.version = this.version; coin.height = this.height; coin.coinbase = this.coinbase; diff --git a/lib/coins/coins.js b/lib/coins/coins.js index 287ecfe07..97516f68a 100644 --- a/lib/coins/coins.js +++ b/lib/coins/coins.js @@ -79,7 +79,7 @@ Coins.prototype.has = function has(index) { */ Coins.prototype.isUnspent = function isUnspent(index) { - let coin = this.outputs.get(index); + const coin = this.outputs.get(index); if (!coin || coin.spent) return false; @@ -104,7 +104,7 @@ Coins.prototype.get = function get(index) { */ Coins.prototype.getOutput = function getOutput(index) { - let coin = this.outputs.get(index); + const coin = this.outputs.get(index); if (!coin) return null; @@ -119,7 +119,7 @@ Coins.prototype.getOutput = function getOutput(index) { */ Coins.prototype.getCoin = function getCoin(prevout) { - let coin = this.outputs.get(prevout.index); + const coin = this.outputs.get(prevout.index); if (!coin) return null; @@ -134,7 +134,7 @@ Coins.prototype.getCoin = function getCoin(prevout) { */ Coins.prototype.spend = function spend(index) { - let coin = this.get(index); + const coin = this.get(index); if (!coin || coin.spent) return null; @@ -151,7 +151,7 @@ Coins.prototype.spend = function spend(index) { */ Coins.prototype.remove = function remove(index) { - let coin = this.get(index); + const coin = this.get(index); if (!coin) return null; @@ -182,7 +182,7 @@ Coins.prototype.fromTX = function fromTX(tx, height) { assert(typeof height === 'number'); for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; + const output = tx.outputs[i]; if (output.script.isUnspendable()) continue; diff --git a/lib/coins/coinview.js b/lib/coins/coinview.js index 0bce7a62d..3674b8e6c 100644 --- a/lib/coins/coinview.js +++ b/lib/coins/coinview.js @@ -66,7 +66,7 @@ CoinView.prototype.add = function add(hash, coins) { */ CoinView.prototype.remove = function remove(hash) { - let coins = this.map.get(hash); + const coins = this.map.get(hash); if (!coins) return null; @@ -84,8 +84,8 @@ CoinView.prototype.remove = function remove(hash) { */ CoinView.prototype.addTX = function addTX(tx, height) { - let hash = tx.hash('hex'); - let coins = Coins.fromTX(tx, height); + const hash = tx.hash('hex'); + const coins = Coins.fromTX(tx, height); return this.add(hash, coins); }; @@ -97,10 +97,10 @@ CoinView.prototype.addTX = function addTX(tx, height) { */ CoinView.prototype.removeTX = function removeTX(tx, height) { - let hash = tx.hash('hex'); - let coins = Coins.fromTX(tx, height); + const hash = tx.hash('hex'); + const coins = Coins.fromTX(tx, height); - for (let coin of coins.outputs.values()) + for (const coin of coins.outputs.values()) coin.spent = true; return this.add(hash, coins); @@ -114,7 +114,7 @@ CoinView.prototype.removeTX = function removeTX(tx, height) { */ CoinView.prototype.addEntry = function addEntry(prevout, coin) { - let {hash, index} = prevout; + const {hash, index} = prevout; let coins = this.get(hash); if (!coins) { @@ -138,7 +138,7 @@ CoinView.prototype.addEntry = function addEntry(prevout, coin) { */ CoinView.prototype.addCoin = function addCoin(coin) { - let {hash, index} = coin; + const {hash, index} = coin; let coins = this.get(hash); if (!coins) { @@ -163,7 +163,7 @@ CoinView.prototype.addCoin = function addCoin(coin) { */ CoinView.prototype.addOutput = function addOutput(prevout, output) { - let {hash, index} = prevout; + const {hash, index} = prevout; let coins = this.get(hash); if (!coins) { @@ -187,8 +187,8 @@ CoinView.prototype.addOutput = function addOutput(prevout, output) { */ CoinView.prototype.spendEntry = function spendEntry(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); let coin; if (!coins) @@ -211,8 +211,8 @@ CoinView.prototype.spendEntry = function spendEntry(prevout) { */ CoinView.prototype.removeEntry = function removeEntry(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); if (!coins) return null; @@ -227,8 +227,8 @@ CoinView.prototype.removeEntry = function removeEntry(prevout) { */ CoinView.prototype.hasEntry = function hasEntry(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); if (!coins) return false; @@ -243,8 +243,8 @@ CoinView.prototype.hasEntry = function hasEntry(prevout) { */ CoinView.prototype.getEntry = function getEntry(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); if (!coins) return null; @@ -259,8 +259,8 @@ CoinView.prototype.getEntry = function getEntry(prevout) { */ CoinView.prototype.isUnspent = function isUnspent(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); if (!coins) return false; @@ -275,7 +275,7 @@ CoinView.prototype.isUnspent = function isUnspent(prevout) { */ CoinView.prototype.getCoin = function getCoin(prevout) { - let coins = this.get(prevout.hash); + const coins = this.get(prevout.hash); if (!coins) return null; @@ -290,8 +290,8 @@ CoinView.prototype.getCoin = function getCoin(prevout) { */ CoinView.prototype.getOutput = function getOutput(prevout) { - let {hash, index} = prevout; - let coins = this.get(hash); + const {hash, index} = prevout; + const coins = this.get(hash); if (!coins) return null; @@ -306,7 +306,7 @@ CoinView.prototype.getOutput = function getOutput(prevout) { */ CoinView.prototype.getHeight = function getHeight(prevout) { - let coin = this.getEntry(prevout); + const coin = this.getEntry(prevout); if (!coin) return -1; @@ -321,7 +321,7 @@ CoinView.prototype.getHeight = function getHeight(prevout) { */ CoinView.prototype.isCoinbase = function isCoinbase(prevout) { - let coin = this.getEntry(prevout); + const coin = this.getEntry(prevout); if (!coin) return false; @@ -432,7 +432,7 @@ CoinView.prototype.readCoin = async function readCoin(db, prevout) { CoinView.prototype.readInputs = async function readInputs(db, tx) { let found = true; - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { if (!(await this.readCoin(db, prevout))) found = false; } @@ -450,15 +450,15 @@ CoinView.prototype.readInputs = async function readInputs(db, tx) { CoinView.prototype.spendInputs = async function spendInputs(db, tx) { if (tx.inputs.length < 4) { - let jobs = []; + const jobs = []; let coins; - for (let {prevout} of tx.inputs) + for (const {prevout} of tx.inputs) jobs.push(this.readCoin(db, prevout)); coins = await Promise.all(jobs); - for (let coin of coins) { + for (const coin of coins) { if (!coin || coin.spent) return false; @@ -469,8 +469,8 @@ CoinView.prototype.spendInputs = async function spendInputs(db, tx) { return true; } - for (let {prevout} of tx.inputs) { - let coin = await this.readCoin(db, prevout); + for (const {prevout} of tx.inputs) { + const coin = await this.readCoin(db, prevout); if (!coin || coin.spent) return false; @@ -492,8 +492,8 @@ CoinView.prototype.getSize = function getSize(tx) { size += tx.inputs.length; - for (let {prevout} of tx.inputs) { - let coin = this.getEntry(prevout); + for (const {prevout} of tx.inputs) { + const coin = this.getEntry(prevout); if (!coin) continue; @@ -512,8 +512,8 @@ CoinView.prototype.getSize = function getSize(tx) { */ CoinView.prototype.toWriter = function toWriter(bw, tx) { - for (let {prevout} of tx.inputs) { - let coin = this.getEntry(prevout); + for (const {prevout} of tx.inputs) { + const coin = this.getEntry(prevout); if (!coin) { bw.writeU8(0); @@ -536,7 +536,7 @@ CoinView.prototype.toWriter = function toWriter(bw, tx) { */ CoinView.prototype.fromReader = function fromReader(br, tx) { - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { let coin; if (br.readU8() === 0) diff --git a/lib/coins/compress.js b/lib/coins/compress.js index 5a572e8e1..2cc50bffd 100644 --- a/lib/coins/compress.js +++ b/lib/coins/compress.js @@ -39,7 +39,7 @@ function compressScript(script, bw) { // P2PKH -> 0 | key-hash // Saves 5 bytes. if (script.isPubkeyhash(true)) { - let hash = script.code[2].data; + const hash = script.code[2].data; bw.writeU8(0); bw.writeBytes(hash); return bw; @@ -48,7 +48,7 @@ function compressScript(script, bw) { // P2SH -> 1 | script-hash // Saves 3 bytes. if (script.isScripthash()) { - let hash = script.code[1].data; + const hash = script.code[1].data; bw.writeU8(1); bw.writeBytes(hash); return bw; @@ -136,7 +136,7 @@ function sizeScript(script) { return 21; if (script.isPubkey(true)) { - let key = script.code[0].data; + const key = script.code[0].data; if (publicKeyVerify(key)) return 33; } @@ -308,7 +308,7 @@ function compressKey(key) { */ function decompressKey(key) { - let format = key[0]; + const format = key[0]; let out; assert(key.length === 33); diff --git a/lib/coins/undocoins.js b/lib/coins/undocoins.js index 7808bfe9f..1396609bc 100644 --- a/lib/coins/undocoins.js +++ b/lib/coins/undocoins.js @@ -49,7 +49,7 @@ UndoCoins.prototype.getSize = function getSize() { size += 4; - for (let coin of this.items) + for (const coin of this.items) size += coin.getSize(); return size; @@ -61,12 +61,12 @@ UndoCoins.prototype.getSize = function getSize() { */ UndoCoins.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU32(this.items.length); - for (let coin of this.items) + for (const coin of this.items) coin.toWriter(bw); return bw.render(); @@ -80,8 +80,8 @@ UndoCoins.prototype.toRaw = function toRaw() { */ UndoCoins.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let count = br.readU32(); + const br = new BufferReader(data); + const count = br.readU32(); for (let i = 0; i < count; i++) this.items.push(CoinEntry.fromReader(br)); @@ -114,7 +114,7 @@ UndoCoins.prototype.isEmpty = function isEmpty() { */ UndoCoins.prototype.commit = function commit() { - let raw = this.toRaw(); + const raw = this.toRaw(); this.items.length = 0; return raw; }; @@ -126,7 +126,7 @@ UndoCoins.prototype.commit = function commit() { */ UndoCoins.prototype.apply = function apply(view, prevout) { - let undo = this.items.pop(); + const undo = this.items.pop(); assert(undo); diff --git a/lib/crypto/aead.js b/lib/crypto/aead.js index 3ebfef9bb..494bb8bed 100644 --- a/lib/crypto/aead.js +++ b/lib/crypto/aead.js @@ -36,7 +36,7 @@ function AEAD() { */ AEAD.prototype.init = function init(key, iv) { - let polyKey = Buffer.allocUnsafe(32); + const polyKey = Buffer.allocUnsafe(32); polyKey.fill(0); this.chacha20.init(key, iv); @@ -122,7 +122,7 @@ AEAD.prototype.auth = function auth(data) { */ AEAD.prototype.finish = function finish() { - let len = Buffer.allocUnsafe(16); + const len = Buffer.allocUnsafe(16); let lo, hi; // The RFC says these are supposed to be diff --git a/lib/crypto/aes-browser.js b/lib/crypto/aes-browser.js index 376f469dd..1d34ebafb 100644 --- a/lib/crypto/aes-browser.js +++ b/lib/crypto/aes-browser.js @@ -106,7 +106,7 @@ AESKey.prototype.getEncryptKey = function getEncryptKey() { if (this.bits === 128) { for (;;) { - let tmp = key[kp + 3]; + const tmp = key[kp + 3]; key[kp + 4] = key[kp + 0] ^ (TE2[(tmp >>> 16) & 0xff] & 0xff000000) @@ -130,7 +130,7 @@ AESKey.prototype.getEncryptKey = function getEncryptKey() { if (this.bits === 192) { for (;;) { - let tmp = key[kp + 5]; + const tmp = key[kp + 5]; key[kp + 6] = key[kp + 0] ^ (TE2[(tmp >>> 16) & 0xff] & 0xff000000) @@ -496,7 +496,7 @@ function AESCipher(key, iv, bits, mode) { */ AESCipher.prototype.update = function update(data) { - let blocks = []; + const blocks = []; let trailing, len; if (this.waiting) { @@ -535,8 +535,8 @@ AESCipher.prototype.final = function final() { block = Buffer.allocUnsafe(16); block.fill(16); } else { - let left = 16 - this.waiting.length; - let pad = Buffer.allocUnsafe(left); + const left = 16 - this.waiting.length; + const pad = Buffer.allocUnsafe(left); pad.fill(left); block = concat(this.waiting, pad); } @@ -582,7 +582,7 @@ function AESDecipher(key, iv, bits, mode) { */ AESDecipher.prototype.update = function update(data) { - let blocks = []; + const blocks = []; let trailing, len; if (this.waiting) { @@ -595,7 +595,7 @@ AESDecipher.prototype.update = function update(data) { // Decrypt all blocks. for (let i = 0; i < len; i += 16) { - let chunk = this.prev; + const chunk = this.prev; let block; this.prev = data.slice(i, i + 16); @@ -669,7 +669,7 @@ AESDecipher.prototype.final = function final() { */ AES.encrypt = function encrypt(data, key, iv, bits, mode) { - let cipher = new AESCipher(key, iv, bits, mode); + const cipher = new AESCipher(key, iv, bits, mode); return concat(cipher.update(data), cipher.final()); }; @@ -684,7 +684,7 @@ AES.encrypt = function encrypt(data, key, iv, bits, mode) { */ AES.decrypt = function decrypt(data, key, iv, bits, mode) { - let decipher = new AESDecipher(key, iv, bits, mode); + const decipher = new AESDecipher(key, iv, bits, mode); return concat(decipher.update(data), decipher.final()); }; @@ -723,7 +723,7 @@ AES.decipher = function decipher(data, key, iv) { */ function xor(v1, v2) { - let out = Buffer.allocUnsafe(v1.length); + const out = Buffer.allocUnsafe(v1.length); for (let i = 0; i < v1.length; i++) out[i] = v1[i] ^ v2[i]; return out; @@ -744,7 +744,7 @@ function writeU32(data, value, i) { } function concat(a, b) { - let data = Buffer.allocUnsafe(a.length + b.length); + const data = Buffer.allocUnsafe(a.length + b.length); a.copy(data, 0); b.copy(data, a.length); return data; diff --git a/lib/crypto/aes.js b/lib/crypto/aes.js index 1bec17298..ac8748756 100644 --- a/lib/crypto/aes.js +++ b/lib/crypto/aes.js @@ -22,7 +22,7 @@ const native = require('../native').binding; */ exports.encipher = function encipher(data, key, iv) { - let cipher = crypto.createCipheriv('aes-256-cbc', key, iv); + const cipher = crypto.createCipheriv('aes-256-cbc', key, iv); return Buffer.concat([cipher.update(data), cipher.final()]); }; @@ -35,7 +35,7 @@ exports.encipher = function encipher(data, key, iv) { */ exports.decipher = function _decipher(data, key, iv) { - let decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); + const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); try { return Buffer.concat([decipher.update(data), decipher.final()]); } catch (e) { diff --git a/lib/crypto/chacha20.js b/lib/crypto/chacha20.js index c9e30e516..1870af69d 100644 --- a/lib/crypto/chacha20.js +++ b/lib/crypto/chacha20.js @@ -168,8 +168,8 @@ ChaCha20.prototype.setCounter = function setCounter(counter) { */ ChaCha20.prototype.getCounter = function getCounter() { - let lo = this.state[12]; - let hi = this.state[13]; + const lo = this.state[12]; + const hi = this.state[13]; if (this.ivSize === 64) return hi * 0x100000000 + lo; return lo; diff --git a/lib/crypto/digest-browser.js b/lib/crypto/digest-browser.js index 95a94e455..fc6a320a1 100644 --- a/lib/crypto/digest-browser.js +++ b/lib/crypto/digest-browser.js @@ -94,7 +94,7 @@ exports.hash256 = function hash256(data) { */ exports.root256 = function root256(left, right) { - let data = POOL64; + const data = POOL64; assert(left.length === 32); assert(right.length === 32); @@ -114,7 +114,7 @@ exports.root256 = function root256(left, right) { */ exports.hmac = function _hmac(alg, data, key) { - let hash = hashjs[alg]; + const hash = hashjs[alg]; let hmac; assert(hash != null, 'Unknown algorithm.'); diff --git a/lib/crypto/digest.js b/lib/crypto/digest.js index 9a23cb6ff..c184ed88e 100644 --- a/lib/crypto/digest.js +++ b/lib/crypto/digest.js @@ -84,7 +84,7 @@ exports.hash256 = function hash256(data) { */ exports.root256 = function root256(left, right) { - let data = POOL64; + const data = POOL64; assert(left.length === 32); assert(right.length === 32); @@ -104,7 +104,7 @@ exports.root256 = function root256(left, right) { */ exports.hmac = function _hmac(alg, data, key) { - let hmac = crypto.createHmac(alg, key); + const hmac = crypto.createHmac(alg, key); return hmac.update(data).digest(); }; diff --git a/lib/crypto/hkdf.js b/lib/crypto/hkdf.js index 02de4e1a9..567d76fd6 100644 --- a/lib/crypto/hkdf.js +++ b/lib/crypto/hkdf.js @@ -34,8 +34,8 @@ exports.extract = function extract(ikm, key, alg) { */ exports.expand = function expand(prk, info, len, alg) { - let size = digest.hash(alg, Buffer.alloc(0)).length; - let blocks = Math.ceil(len / size); + const size = digest.hash(alg, Buffer.alloc(0)).length; + const blocks = Math.ceil(len / size); let okm, buf, out; if (blocks > 255) diff --git a/lib/crypto/hmac-drbg.js b/lib/crypto/hmac-drbg.js index 068e9679f..ead618c34 100644 --- a/lib/crypto/hmac-drbg.js +++ b/lib/crypto/hmac-drbg.js @@ -47,7 +47,7 @@ HmacDRBG.prototype.init = function init(entropy, nonce, pers) { }; HmacDRBG.prototype.reseed = function reseed(entropy, nonce, pers) { - let seed = POOL112; + const seed = POOL112; assert(Buffer.isBuffer(entropy)); assert(Buffer.isBuffer(nonce)); @@ -66,7 +66,7 @@ HmacDRBG.prototype.reseed = function reseed(entropy, nonce, pers) { }; HmacDRBG.prototype.iterate = function iterate() { - let data = POOL33; + const data = POOL33; this.V.copy(data, 0); data[HASH_SIZE] = 0x00; @@ -76,7 +76,7 @@ HmacDRBG.prototype.iterate = function iterate() { }; HmacDRBG.prototype.update = function update(seed) { - let data = POOL145; + const data = POOL145; assert(Buffer.isBuffer(seed)); assert(seed.length === HASH_SIZE * 2 + 48); @@ -95,7 +95,7 @@ HmacDRBG.prototype.update = function update(seed) { }; HmacDRBG.prototype.generate = function generate(len) { - let data = Buffer.allocUnsafe(len); + const data = Buffer.allocUnsafe(len); let pos = 0; if (this.rounds > RESEED_INTERVAL) diff --git a/lib/crypto/merkle.js b/lib/crypto/merkle.js index 36ef202ea..0da879f92 100644 --- a/lib/crypto/merkle.js +++ b/lib/crypto/merkle.js @@ -21,7 +21,7 @@ const digest = require('./digest'); */ exports.createTree = function createTree(leaves) { - let nodes = leaves; + const nodes = leaves; let size = leaves.length; let malleated = false; let i = 0; @@ -33,9 +33,9 @@ exports.createTree = function createTree(leaves) { while (size > 1) { for (let j = 0; j < size; j += 2) { - let k = Math.min(j + 1, size - 1); - let left = nodes[i + j]; - let right = nodes[i + k]; + const k = Math.min(j + 1, size - 1); + const left = nodes[i + j]; + const right = nodes[i + k]; let hash; if (k === j + 1 && k + 1 === size @@ -62,8 +62,8 @@ exports.createTree = function createTree(leaves) { */ exports.createRoot = function createRoot(leaves) { - let [nodes, malleated] = exports.createTree(leaves); - let root = nodes[nodes.length - 1]; + const [nodes, malleated] = exports.createTree(leaves); + const root = nodes[nodes.length - 1]; return [root, malleated]; }; @@ -76,12 +76,12 @@ exports.createRoot = function createRoot(leaves) { exports.createBranch = function createBranch(index, leaves) { let size = leaves.length; - let [nodes] = exports.createTree(leaves); - let branch = []; + const [nodes] = exports.createTree(leaves); + const branch = []; let i = 0; while (size > 1) { - let j = Math.min(index ^ 1, size - 1); + const j = Math.min(index ^ 1, size - 1); branch.push(nodes[i + j]); index >>>= 1; i += size; @@ -103,7 +103,7 @@ exports.createBranch = function createBranch(index, leaves) { exports.deriveRoot = function deriveRoot(hash, branch, index) { let root = hash; - for (let hash of branch) { + for (const hash of branch) { if (index & 1) root = digest.root256(hash, root); else diff --git a/lib/crypto/pbkdf2-browser.js b/lib/crypto/pbkdf2-browser.js index a2407f482..82e4fc4d1 100644 --- a/lib/crypto/pbkdf2-browser.js +++ b/lib/crypto/pbkdf2-browser.js @@ -26,11 +26,11 @@ const subtle = crypto.subtle || {}; */ exports.derive = function derive(key, salt, iter, len, alg) { - let size = digest.hash(alg, Buffer.alloc(0)).length; - let blocks = Math.ceil(len / size); - let out = Buffer.allocUnsafe(len); - let buf = Buffer.allocUnsafe(salt.length + 4); - let block = Buffer.allocUnsafe(size); + const size = digest.hash(alg, Buffer.alloc(0)).length; + const blocks = Math.ceil(len / size); + const out = Buffer.allocUnsafe(len); + const buf = Buffer.allocUnsafe(salt.length + 4); + const block = Buffer.allocUnsafe(size); let pos = 0; salt.copy(buf, 0); @@ -63,8 +63,8 @@ exports.derive = function derive(key, salt, iter, len, alg) { */ exports.deriveAsync = async function deriveAsync(key, salt, iter, len, alg) { - let algo = { name: 'PBKDF2' }; - let use = ['deriveBits']; + const algo = { name: 'PBKDF2' }; + const use = ['deriveBits']; let options, imported, data; if (!subtle.importKey || !subtle.deriveBits) diff --git a/lib/crypto/poly1305.js b/lib/crypto/poly1305.js index d6a3d6329..7f371e030 100644 --- a/lib/crypto/poly1305.js +++ b/lib/crypto/poly1305.js @@ -35,14 +35,14 @@ function Poly1305() { Poly1305.prototype.init = function init(key) { // r &= 0xffffffc0ffffffc0ffffffc0fffffff - let t0 = key.readUInt16LE(0, true); - let t1 = key.readUInt16LE(2, true); - let t2 = key.readUInt16LE(4, true); - let t3 = key.readUInt16LE(6, true); - let t4 = key.readUInt16LE(8, true); - let t5 = key.readUInt16LE(10, true); - let t6 = key.readUInt16LE(12, true); - let t7 = key.readUInt16LE(14, true); + const t0 = key.readUInt16LE(0, true); + const t1 = key.readUInt16LE(2, true); + const t2 = key.readUInt16LE(4, true); + const t3 = key.readUInt16LE(6, true); + const t4 = key.readUInt16LE(8, true); + const t5 = key.readUInt16LE(10, true); + const t6 = key.readUInt16LE(12, true); + const t7 = key.readUInt16LE(14, true); this.r[0] = t0 & 0x1fff; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; @@ -75,19 +75,19 @@ Poly1305.prototype.init = function init(key) { */ Poly1305.prototype.blocks = function blocks(data, bytes, m) { - let hibit = this.fin ? 0 : (1 << 11); // 1 << 128 - let d = new Uint32Array(10); + const hibit = this.fin ? 0 : (1 << 11); // 1 << 128 + const d = new Uint32Array(10); while (bytes >= 16) { // h += m[i] - let t0 = data.readUInt16LE(m + 0, true); - let t1 = data.readUInt16LE(m + 2, true); - let t2 = data.readUInt16LE(m + 4, true); - let t3 = data.readUInt16LE(m + 6, true); - let t4 = data.readUInt16LE(m + 8, true); - let t5 = data.readUInt16LE(m + 10, true); - let t6 = data.readUInt16LE(m + 12, true); - let t7 = data.readUInt16LE(m + 14, true); + const t0 = data.readUInt16LE(m + 0, true); + const t1 = data.readUInt16LE(m + 2, true); + const t2 = data.readUInt16LE(m + 4, true); + const t3 = data.readUInt16LE(m + 6, true); + const t4 = data.readUInt16LE(m + 8, true); + const t5 = data.readUInt16LE(m + 10, true); + const t6 = data.readUInt16LE(m + 12, true); + const t7 = data.readUInt16LE(m + 14, true); let c = 0; this.h[0] += t0 & 0x1fff; @@ -172,7 +172,7 @@ Poly1305.prototype.update = function update(data) { // process full blocks if (bytes >= 16) { - let want = bytes & ~(16 - 1); + const want = bytes & ~(16 - 1); this.blocks(data, want, m); m += want; bytes -= want; @@ -192,8 +192,8 @@ Poly1305.prototype.update = function update(data) { */ Poly1305.prototype.finish = function finish() { - let mac = Buffer.allocUnsafe(16); - let g = new Uint16Array(10); + const mac = Buffer.allocUnsafe(16); + const g = new Uint16Array(10); let c, mask, f; // process the remaining block @@ -283,7 +283,7 @@ Poly1305.prototype.finish = function finish() { */ Poly1305.auth = function auth(msg, key) { - let poly = new Poly1305(); + const poly = new Poly1305(); poly.init(key); poly.update(msg); return poly.finish(); diff --git a/lib/crypto/random-browser.js b/lib/crypto/random-browser.js index fbaf0092f..0f102b055 100644 --- a/lib/crypto/random-browser.js +++ b/lib/crypto/random-browser.js @@ -20,7 +20,7 @@ const crypto = global.crypto || global.msCrypto || {}; */ exports.randomBytes = function randomBytes(size) { - let data = new Uint8Array(size); + const data = new Uint8Array(size); crypto.getRandomValues(data); return Buffer.from(data.buffer); }; @@ -28,7 +28,7 @@ exports.randomBytes = function randomBytes(size) { if (!crypto.getRandomValues) { // Out of luck here. Use bad randomness for now. exports.randomBytes = function randomBytes(size) { - let data = Buffer.allocUnsafe(size); + const data = Buffer.allocUnsafe(size); for (let i = 0; i < data.length; i++) data[i] = Math.floor(Math.random() * 256); @@ -58,6 +58,6 @@ exports.randomInt = function randomInt() { */ exports.randomRange = function randomRange(min, max) { - let num = exports.randomInt(); + const num = exports.randomInt(); return Math.floor((num / 0x100000000) * (max - min) + min); }; diff --git a/lib/crypto/random.js b/lib/crypto/random.js index f2280a9ff..e98c29198 100644 --- a/lib/crypto/random.js +++ b/lib/crypto/random.js @@ -42,6 +42,6 @@ exports.randomInt = function randomInt() { */ exports.randomRange = function randomRange(min, max) { - let num = exports.randomInt(); + const num = exports.randomInt(); return Math.floor((num / 0x100000000) * (max - min) + min); }; diff --git a/lib/crypto/rsa-browser.js b/lib/crypto/rsa-browser.js index 897ec9b5e..11fa41233 100644 --- a/lib/crypto/rsa-browser.js +++ b/lib/crypto/rsa-browser.js @@ -44,7 +44,7 @@ rsa.prefixes = { */ rsa.verify = function verify(alg, msg, sig, key) { - let prefix = rsa.prefixes[alg]; + const prefix = rsa.prefixes[alg]; let hash, len, pub; let N, e, k, m, em, ok; @@ -91,7 +91,7 @@ rsa.verify = function verify(alg, msg, sig, key) { */ rsa.sign = function sign(alg, msg, key) { - let prefix = rsa.prefixes[alg]; + const prefix = rsa.prefixes[alg]; let hash, len, priv; let N, D, k, em; @@ -135,7 +135,7 @@ rsa.sign = function sign(alg, msg, key) { */ rsa.decrypt = function decrypt(N, D, m) { - let c = new BN(m); + const c = new BN(m); if (c.cmp(N) > 0) throw new Error('Cannot decrypt.'); diff --git a/lib/crypto/schnorr.js b/lib/crypto/schnorr.js index 74878277a..915e58739 100644 --- a/lib/crypto/schnorr.js +++ b/lib/crypto/schnorr.js @@ -29,8 +29,8 @@ const schnorr = exports; */ schnorr.hash = function _hash(msg, r) { - let R = r.toBuffer('be', 32); - let B = POOL64; + const R = r.toBuffer('be', 32); + const B = POOL64; R.copy(B, 0); msg.copy(B, 32); @@ -100,9 +100,9 @@ schnorr.trySign = function trySign(msg, prv, k, pn) { */ schnorr.sign = function sign(msg, key, pubNonce) { - let prv = new BN(key); - let drbg = schnorr.drbg(msg, key, pubNonce); - let len = curve.n.byteLength(); + const prv = new BN(key); + const drbg = schnorr.drbg(msg, key, pubNonce); + const len = curve.n.byteLength(); let k, pn, sig; if (pubNonce) @@ -125,8 +125,8 @@ schnorr.sign = function sign(msg, key, pubNonce) { */ schnorr.verify = function verify(msg, signature, key) { - let sig = new Signature(signature); - let h = schnorr.hash(msg, sig.r); + const sig = new Signature(signature); + const h = schnorr.hash(msg, sig.r); let k, l, r, rl; if (h.cmp(curve.n) >= 0) @@ -160,8 +160,8 @@ schnorr.verify = function verify(msg, signature, key) { */ schnorr.recover = function recover(signature, msg) { - let sig = new Signature(signature); - let h = schnorr.hash(msg, sig.r); + const sig = new Signature(signature); + const h = schnorr.hash(msg, sig.r); let hinv, s, R, l, r, k, rl; if (h.cmp(curve.n) >= 0) @@ -215,7 +215,7 @@ schnorr.combineSigs = function combineSigs(sigs) { let r, last; for (let i = 0; i < sigs.length; i++) { - let sig = new Signature(sigs[i]); + const sig = new Signature(sigs[i]); if (sig.s.cmpn(0) === 0) throw new Error('Bad S value.'); @@ -276,10 +276,10 @@ schnorr.combineKeys = function combineKeys(keys) { */ schnorr.partialSign = function partialSign(msg, priv, privNonce, pubNonce) { - let prv = new BN(priv); - let k = new BN(privNonce); - let pn = curve.decodePoint(pubNonce); - let sig = schnorr.trySign(msg, prv, k, pn); + const prv = new BN(priv); + const k = new BN(privNonce); + const pn = curve.decodePoint(pubNonce); + const sig = schnorr.trySign(msg, prv, k, pn); if (!sig) throw new Error('Bad K value.'); @@ -303,7 +303,7 @@ schnorr.alg = Buffer.from('Schnorr+SHA256 ', 'ascii'); */ schnorr.drbg = function drbg(msg, priv, data) { - let pers = Buffer.allocUnsafe(48); + const pers = Buffer.allocUnsafe(48); pers.fill(0); @@ -326,8 +326,8 @@ schnorr.drbg = function drbg(msg, priv, data) { */ schnorr.generateNoncePair = function generateNoncePair(msg, priv, data) { - let drbg = schnorr.drbg(msg, priv, data); - let len = curve.n.byteLength(); + const drbg = schnorr.drbg(msg, priv, data); + const len = curve.n.byteLength(); let k; for (;;) { diff --git a/lib/crypto/scrypt.js b/lib/crypto/scrypt.js index 2c3170675..9f1d5e588 100644 --- a/lib/crypto/scrypt.js +++ b/lib/crypto/scrypt.js @@ -125,8 +125,8 @@ if (native) */ function salsa20_8(B) { - let B32 = new Uint32Array(16); - let x = new Uint32Array(16); + const B32 = new Uint32Array(16); + const x = new Uint32Array(16); for (let i = 0; i < 16; i++) B32[i] = B.readUInt32LE(i * 4, true); @@ -188,7 +188,7 @@ function R(a, b) { } function blockmix_salsa8(B, Y, Yo, r) { - let X = Buffer.allocUnsafe(64); + const X = Buffer.allocUnsafe(64); blkcpy(X, B, 0, (2 * r - 1) * 64, 64); @@ -210,8 +210,8 @@ function integerify(B, r) { } function smix(B, Bo, r, N, V, XY) { - let X = XY; - let Y = XY; + const X = XY; + const Y = XY; blkcpy(X, B, 0, Bo, 128 * r); @@ -221,7 +221,7 @@ function smix(B, Bo, r, N, V, XY) { } for (let i = 0; i < N; i++) { - let j = integerify(X, r) & (N - 1); + const j = integerify(X, r) & (N - 1); blkxor(X, V, 0, j * (128 * r), 128 * r); blockmix_salsa8(X, Y, 128 * r, r); } @@ -230,8 +230,8 @@ function smix(B, Bo, r, N, V, XY) { } async function smixAsync(B, Bo, r, N, V, XY) { - let X = XY; - let Y = XY; + const X = XY; + const Y = XY; blkcpy(X, B, 0, Bo, 128 * r); @@ -242,7 +242,7 @@ async function smixAsync(B, Bo, r, N, V, XY) { } for (let i = 0; i < N; i++) { - let j = integerify(X, r) & (N - 1); + const j = integerify(X, r) & (N - 1); blkxor(X, V, 0, j * (128 * r), 128 * r); blockmix_salsa8(X, Y, 128 * r, r); await co.wait(); diff --git a/lib/crypto/secp256k1-browser.js b/lib/crypto/secp256k1-browser.js index 37936502f..c576ebbf1 100644 --- a/lib/crypto/secp256k1-browser.js +++ b/lib/crypto/secp256k1-browser.js @@ -34,7 +34,7 @@ ec.binding = false; */ ec.generatePrivateKey = function generatePrivateKey() { - let key = secp256k1.genKeyPair(); + const key = secp256k1.genKeyPair(); return key.getPrivate().toBuffer('be', 32); }; @@ -65,7 +65,7 @@ ec.publicKeyCreate = function publicKeyCreate(priv, compress) { */ ec.publicKeyConvert = function publicKeyConvert(key, compress) { - let point = curve.decodePoint(key); + const point = curve.decodePoint(key); if (compress == null) compress = true; @@ -81,7 +81,7 @@ ec.publicKeyConvert = function publicKeyConvert(key, compress) { */ ec.privateKeyTweakAdd = function privateKeyTweakAdd(privateKey, tweak) { - let key = new BN(tweak) + const key = new BN(tweak) .add(new BN(privateKey)) .mod(curve.n) .toBuffer('be', 32); @@ -101,8 +101,8 @@ ec.privateKeyTweakAdd = function privateKeyTweakAdd(privateKey, tweak) { */ ec.publicKeyTweakAdd = function publicKeyTweakAdd(publicKey, tweak, compress) { - let key = curve.decodePoint(publicKey); - let point = curve.g.mul(new BN(tweak)).add(key); + const key = curve.decodePoint(publicKey); + const point = curve.g.mul(new BN(tweak)).add(key); let pub; if (compress == null) @@ -305,7 +305,7 @@ ec.isLowS = function isLowS(sig) { function normalizeLength(sig) { let data = sig; - let p = { place: 0 }; + const p = { place: 0 }; let len, rlen, slen; if (data[p.place++] !== 0x30) @@ -333,8 +333,8 @@ function normalizeLength(sig) { } function getLength(buf, p) { - let initial = buf[p.place++]; - let len = initial & 0xf; + const initial = buf[p.place++]; + const len = initial & 0xf; let off = p.place; let val = 0; diff --git a/lib/crypto/secp256k1-native.js b/lib/crypto/secp256k1-native.js index 10738a93e..b83401559 100644 --- a/lib/crypto/secp256k1-native.js +++ b/lib/crypto/secp256k1-native.js @@ -105,7 +105,7 @@ ec.publicKeyTweakAdd = function publicKeyTweakAdd(publicKey, tweak, compress) { */ ec.ecdh = function ecdh(pub, priv) { - let point = secp256k1.ecdhUnsafe(pub, priv, true); + const point = secp256k1.ecdhUnsafe(pub, priv, true); return point.slice(1, 33); }; diff --git a/lib/crypto/sha256.js b/lib/crypto/sha256.js index ae292dbd5..0dc4c2026 100644 --- a/lib/crypto/sha256.js +++ b/lib/crypto/sha256.js @@ -175,7 +175,7 @@ SHA256.prototype.transform = function transform(chunk, pos) { let f = this.s[5]; let g = this.s[6]; let h = this.s[7]; - let w = this.w; + const w = this.w; let i = 0; for (; i < 16; i++) @@ -248,7 +248,7 @@ function SHA256Hmac() { */ SHA256Hmac.prototype.init = function init(data) { - let key = BUFFER64; + const key = BUFFER64; if (data.length > 64) { this.inner.init(); @@ -363,7 +363,7 @@ function sha256(data) { */ function hash256(data) { - let out = Buffer.allocUnsafe(32); + const out = Buffer.allocUnsafe(32); ctx.init(); ctx.update(data); ctx._finish(out); diff --git a/lib/crypto/siphash.js b/lib/crypto/siphash.js index fb28b7803..0dd921446 100644 --- a/lib/crypto/siphash.js +++ b/lib/crypto/siphash.js @@ -24,15 +24,15 @@ const native = require('../native').binding; */ function siphash24(data, key, shift) { - let blocks = Math.floor(data.length / 8); - let c0 = U64(0x736f6d65, 0x70736575); - let c1 = U64(0x646f7261, 0x6e646f6d); - let c2 = U64(0x6c796765, 0x6e657261); - let c3 = U64(0x74656462, 0x79746573); - let f0 = U64(blocks << (shift - 32), 0); - let f1 = U64(0, 0xff); - let k0 = U64.fromRaw(key, 0); - let k1 = U64.fromRaw(key, 8); + const blocks = Math.floor(data.length / 8); + const c0 = U64(0x736f6d65, 0x70736575); + const c1 = U64(0x646f7261, 0x6e646f6d); + const c2 = U64(0x6c796765, 0x6e657261); + const c3 = U64(0x74656462, 0x79746573); + const f0 = U64(blocks << (shift - 32), 0); + const f1 = U64(0, 0xff); + const k0 = U64.fromRaw(key, 0); + const k1 = U64.fromRaw(key, 8); let p = 0; let v0, v1, v2, v3; @@ -44,7 +44,7 @@ function siphash24(data, key, shift) { // Blocks for (let i = 0; i < blocks; i++) { - let d = U64.fromRaw(data, p); + const d = U64.fromRaw(data, p); p += 8; v3.ixor(d); sipround(v0, v1, v2, v3); @@ -152,7 +152,7 @@ function U64(hi, lo) { } U64.prototype.iadd = function iadd(b) { - let a = this; + const a = this; let hi, lo, as, bs, s, c; // Credit to @indutny for this method. @@ -214,8 +214,8 @@ U64.prototype.irotl = function irotl(bits) { }; U64.fromRaw = function fromRaw(data, off) { - let lo = data.readUInt32LE(off, true); - let hi = data.readUInt32LE(off + 4, true); + const lo = data.readUInt32LE(off, true); + const hi = data.readUInt32LE(off + 4, true); return new U64(hi, lo); }; diff --git a/lib/db/ldb.js b/lib/db/ldb.js index 8f9f42277..fc0294e6a 100644 --- a/lib/db/ldb.js +++ b/lib/db/ldb.js @@ -19,9 +19,9 @@ const backends = require('./backends'); */ function LDB(options) { - let result = LDB.getBackend(options); - let backend = result.backend; - let location = result.location; + const result = LDB.getBackend(options); + const backend = result.backend; + const location = result.location; return new LowlevelUp(backend, location, options); } @@ -78,8 +78,8 @@ LDB.getName = function getName(db) { */ LDB.getBackend = function getBackend(options) { - let [name, ext] = LDB.getName(options.db); - let backend = backends.get(name); + const [name, ext] = LDB.getName(options.db); + const backend = backends.get(name); let location = options.location; if (typeof location !== 'string') { diff --git a/lib/db/level.js b/lib/db/level.js index 9e82b10bd..de003600c 100644 --- a/lib/db/level.js +++ b/lib/db/level.js @@ -39,7 +39,7 @@ DB.prototype.batch = function batch(ops, options, callback) { return new Batch(this); if (this.bufferKeys) { - for (let op of ops) { + for (const op of ops) { if (Buffer.isBuffer(op.key)) op.key = op.key.toString('hex'); } diff --git a/lib/db/lowlevelup.js b/lib/db/lowlevelup.js index ce6d84ca5..8f1aca906 100644 --- a/lib/db/lowlevelup.js +++ b/lib/db/lowlevelup.js @@ -58,7 +58,7 @@ function LowlevelUp(backend, location, options) { */ LowlevelUp.prototype.init = function init() { - let backend = this.backend; + const backend = this.backend; let db = new backend(this.location); let binding = db; @@ -93,7 +93,7 @@ LowlevelUp.prototype.init = function init() { */ LowlevelUp.prototype.open = async function open() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._open(); } finally { @@ -135,7 +135,7 @@ LowlevelUp.prototype._open = async function open() { */ LowlevelUp.prototype.close = async function close() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._close(); } finally { @@ -429,7 +429,7 @@ LowlevelUp.prototype.compactRange = function compactRange(start, end) { */ LowlevelUp.prototype.has = async function has(key) { - let value = await this.get(key); + const value = await this.get(key); return value != null; }; @@ -441,10 +441,10 @@ LowlevelUp.prototype.has = async function has(key) { */ LowlevelUp.prototype.range = async function range(options) { - let items = []; - let parse = options.parse; + const items = []; + const parse = options.parse; - let iter = this.iterator({ + const iter = this.iterator({ gte: options.gte, lte: options.lte, keys: true, @@ -481,10 +481,10 @@ LowlevelUp.prototype.range = async function range(options) { */ LowlevelUp.prototype.keys = async function _keys(options) { - let keys = []; - let parse = options.parse; + const keys = []; + const parse = options.parse; - let iter = this.iterator({ + const iter = this.iterator({ gte: options.gte, lte: options.lte, keys: true, @@ -492,7 +492,7 @@ LowlevelUp.prototype.keys = async function _keys(options) { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); let key; if (!item) @@ -524,10 +524,10 @@ LowlevelUp.prototype.keys = async function _keys(options) { */ LowlevelUp.prototype.values = async function _values(options) { - let values = []; - let parse = options.parse; + const values = []; + const parse = options.parse; - let iter = this.iterator({ + const iter = this.iterator({ gte: options.gte, lte: options.lte, keys: false, @@ -535,7 +535,7 @@ LowlevelUp.prototype.values = async function _values(options) { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); let value; if (!item) @@ -566,16 +566,16 @@ LowlevelUp.prototype.values = async function _values(options) { */ LowlevelUp.prototype.dump = async function dump() { - let records = Object.create(null); + const records = Object.create(null); - let items = await this.range({ + const items = await this.range({ gte: LOW, lte: HIGH }); - for (let item of items) { - let key = item.key.toString('hex'); - let value = item.value.toString('hex'); + for (const item of items) { + const key = item.key.toString('hex'); + const value = item.value.toString('hex'); records[key] = value; } @@ -613,8 +613,8 @@ LowlevelUp.prototype.checkVersion = async function checkVersion(key, version) { */ LowlevelUp.prototype.clone = async function clone(path) { - let options = new LLUOptions(this.options); - let hwm = 256 << 20; + const options = new LLUOptions(this.options); + const hwm = 256 << 20; let total = 0; let tmp, batch, iter; @@ -636,7 +636,7 @@ LowlevelUp.prototype.clone = async function clone(path) { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; diff --git a/lib/db/memdb.js b/lib/db/memdb.js index 73750a16e..ad94aa0b0 100644 --- a/lib/db/memdb.js +++ b/lib/db/memdb.js @@ -162,7 +162,7 @@ MemDB.prototype.get = function get(key, options, callback) { value = this.search(key); if (!value) { - let err = new Error('MEMDB_NOTFOUND: Key not found.'); + const err = new Error('MEMDB_NOTFOUND: Key not found.'); err.notFound = true; err.type = 'NotFoundError'; setImmediate(() => callback(err)); @@ -267,10 +267,10 @@ MemDB.prototype.getProperty = function getProperty(name) { */ MemDB.prototype.approximateSize = function approximateSize(start, end, callback) { - let items = this.range(start, end); + const items = this.range(start, end); let size = 0; - for (let item of items) { + for (const item of items) { size += item.key.length; size += item.value.length; } @@ -348,7 +348,7 @@ Batch.prototype.write = function write(callback) { return; } - for (let op of this.ops) { + for (const op of this.ops) { switch (op.type) { case 'put': this.db.insert(op.key, op.value); @@ -419,8 +419,8 @@ function Iterator(db, options) { */ Iterator.prototype.init = function init() { - let snapshot = this.db.tree.snapshot(); - let iter = this.db.tree.iterator(snapshot); + const snapshot = this.db.tree.snapshot(); + const iter = this.db.tree.iterator(snapshot); if (this.options.reverse) { if (this.options.end) { @@ -453,8 +453,8 @@ Iterator.prototype.init = function init() { */ Iterator.prototype.next = function next(callback) { - let options = this.options; - let iter = this.iter; + const options = this.options; + const iter = this.iter; let key, value, result; if (!this.iter) { diff --git a/lib/hd/common.js b/lib/hd/common.js index a8c9f180c..97f98e5ff 100644 --- a/lib/hd/common.js +++ b/lib/hd/common.js @@ -65,9 +65,9 @@ common.cache = new LRU(500); */ common.parsePath = function parsePath(path, max) { - let parts = path.split('/'); - let root = parts.shift(); - let result = []; + const parts = path.split('/'); + const root = parts.shift(); + const result = []; if (max == null) max = common.MAX_INDEX; @@ -80,7 +80,7 @@ common.parsePath = function parsePath(path, max) { } for (let index of parts) { - let hardened = index[index.length - 1] === '\''; + const hardened = index[index.length - 1] === '\''; if (hardened) index = index.slice(0, -1); diff --git a/lib/hd/mnemonic.js b/lib/hd/mnemonic.js index 5edd05380..c1c04b799 100644 --- a/lib/hd/mnemonic.js +++ b/lib/hd/mnemonic.js @@ -203,9 +203,9 @@ Mnemonic.prototype.getPhrase = function getPhrase() { for (let i = 0; i < bits / 11; i++) { let index = 0; for (let j = 0; j < 11; j++) { - let pos = i * 11 + j; - let bit = pos % 8; - let oct = (pos - bit) / 8; + const pos = i * 11 + j; + const bit = pos % 8; + const oct = (pos - bit) / 8; index <<= 1; index |= (entropy[oct] >>> (7 - bit)) & 1; } @@ -230,12 +230,12 @@ Mnemonic.prototype.getPhrase = function getPhrase() { */ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) { - let words = phrase.split(/[ \u3000]+/); + const words = phrase.split(/[ \u3000]+/); let bits = words.length * 11; - let cbits = bits % 32; - let cbytes = Math.ceil(cbits / 8); - let lang = Mnemonic.getLanguage(words[0]); - let wordlist = Mnemonic.getWordlist(lang); + const cbits = bits % 32; + const cbytes = Math.ceil(cbits / 8); + const lang = Mnemonic.getLanguage(words[0]); + const wordlist = Mnemonic.getWordlist(lang); let ent, entropy, chk; bits -= cbits; @@ -250,17 +250,17 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) { // Rebuild entropy bytes. for (let i = 0; i < words.length; i++) { - let word = words[i]; - let index = util.binarySearch(wordlist, word, util.strcmp); + const word = words[i]; + const index = util.binarySearch(wordlist, word, util.strcmp); if (index === -1) throw new Error('Could not find word.'); for (let j = 0; j < 11; j++) { - let pos = i * 11 + j; - let bit = pos % 8; - let oct = (pos - bit) / 8; - let val = (index >>> (10 - j)) & 1; + const pos = i * 11 + j; + const bit = pos % 8; + const oct = (pos - bit) / 8; + const val = (index >>> (10 - j)) & 1; ent[oct] |= val << (7 - bit); } } @@ -271,10 +271,10 @@ Mnemonic.prototype.fromPhrase = function fromPhrase(phrase) { // Verify checksum. for (let i = 0; i < cbits; i++) { - let bit = i % 8; - let oct = (i - bit) / 8; - let a = (ent[oct] >>> (7 - bit)) & 1; - let b = (chk[oct] >>> (7 - bit)) & 1; + const bit = i % 8; + const oct = (i - bit) / 8; + const a = (ent[oct] >>> (7 - bit)) & 1; + const b = (chk[oct] >>> (7 - bit)) & 1; if (a !== b) throw new Error('Invalid checksum.'); } @@ -434,7 +434,7 @@ Mnemonic.prototype.getSize = function getSize() { */ Mnemonic.prototype.toWriter = function toWriter(bw) { - let lang = Mnemonic.languages.indexOf(this.language); + const lang = Mnemonic.languages.indexOf(this.language); assert(lang !== -1); @@ -453,7 +453,7 @@ Mnemonic.prototype.toWriter = function toWriter(bw) { */ Mnemonic.prototype.toRaw = function toRaw(writer) { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; diff --git a/lib/hd/private.js b/lib/hd/private.js index ccddb8848..248e60e26 100644 --- a/lib/hd/private.js +++ b/lib/hd/private.js @@ -384,10 +384,10 @@ HDPrivateKey.isValidPath = function isValidPath(path) { */ HDPrivateKey.prototype.derivePath = function derivePath(path) { - let indexes = common.parsePath(path, common.MAX_INDEX); + const indexes = common.parsePath(path, common.MAX_INDEX); let key = this; - for (let index of indexes) + for (const index of indexes) key = key.derive(index); return key; @@ -528,7 +528,7 @@ HDPrivateKey.fromMnemonic = function fromMnemonic(mnemonic, network) { */ HDPrivateKey.prototype.fromPhrase = function fromPhrase(phrase, network) { - let mnemonic = Mnemonic.fromPhrase(phrase); + const mnemonic = Mnemonic.fromPhrase(phrase); this.fromMnemonic(mnemonic, network); return this; }; @@ -584,8 +584,8 @@ HDPrivateKey.fromKey = function fromKey(key, entropy, network) { */ HDPrivateKey.generate = function generate(network) { - let key = secp256k1.generatePrivateKey(); - let entropy = random.randomBytes(32); + const key = secp256k1.generatePrivateKey(); + const entropy = random.randomBytes(32); return HDPrivateKey.fromKey(key, entropy, network); }; @@ -610,7 +610,7 @@ HDPrivateKey.prototype.fromBase58 = function fromBase58(xkey, network) { */ HDPrivateKey.prototype.fromReader = function fromReader(br, network) { - let version = br.readU32BE(); + const version = br.readU32BE(); this.network = Network.fromPrivate(version, network); this.depth = br.readU8(); diff --git a/lib/hd/public.js b/lib/hd/public.js index c9ea64909..f07d1ff58 100644 --- a/lib/hd/public.js +++ b/lib/hd/public.js @@ -300,10 +300,10 @@ HDPublicKey.isValidPath = function isValidPath(path) { */ HDPublicKey.prototype.derivePath = function derivePath(path) { - let indexes = common.parsePath(path, common.HARDENED); + const indexes = common.parsePath(path, common.HARDENED); let key = this; - for (let index of indexes) + for (const index of indexes) key = key.derive(index); return key; @@ -474,7 +474,7 @@ HDPublicKey.prototype.fromBase58 = function fromBase58(xkey, network) { */ HDPublicKey.prototype.fromReader = function fromReader(br, network) { - let version = br.readU32BE(); + const version = br.readU32BE(); this.network = Network.fromPublic(version, network); this.depth = br.readU8(); diff --git a/lib/http/base.js b/lib/http/base.js index e89df8048..8dad9019f 100644 --- a/lib/http/base.js +++ b/lib/http/base.js @@ -58,8 +58,8 @@ util.inherits(HTTPBase, AsyncObject); */ HTTPBase.prototype._init = function _init() { - let backend = this.config.getBackend(); - let options = this.config.toHTTP(); + const backend = this.config.getBackend(); + const options = this.config.toHTTP(); this.server = backend.createServer(options); @@ -97,8 +97,8 @@ HTTPBase.prototype._init = function _init() { HTTPBase.prototype._initRouter = function _initRouter() { this.server.on('request', async (hreq, hres) => { - let req = new Request(hreq, hres, hreq.url); - let res = new Response(hreq, hres); + const req = new Request(hreq, hres, hreq.url); + const res = new Response(hreq, hres); req.on('error', () => {}); @@ -136,8 +136,8 @@ HTTPBase.prototype.handleRequest = async function handleRequest(req, res) { if (!routes) throw new Error(`No routes found for method: ${req.method}.`); - for (let route of routes) { - let params = route.match(req.pathname); + for (const route of routes) { + const params = route.match(req.pathname); if (!params) continue; @@ -257,7 +257,7 @@ HTTPBase.prototype.basicAuth = function basicAuth(options) { */ HTTPBase.prototype.bodyParser = function bodyParser(options) { - let opt = new BodyParserOptions(options); + const opt = new BodyParserOptions(options); return async (req, res) => { if (req.hasBody) @@ -337,7 +337,7 @@ HTTPBase.prototype.readBody = function readBody(req, enc, options) { */ HTTPBase.prototype._readBody = function _readBody(req, enc, options, resolve, reject) { - let decode = new StringDecoder(enc); + const decode = new StringDecoder(enc); let hasData = false; let total = 0; let body = ''; @@ -433,8 +433,8 @@ HTTPBase.prototype.jsonRPC = function jsonRPC(rpc) { HTTPBase.prototype.handleMounts = async function handleMounts(req, res) { let url = req.url; - for (let route of this.mounts) { - let server = route.handler; + for (const route of this.mounts) { + const server = route.handler; if (!route.hasPrefix(req.pathname)) continue; @@ -461,7 +461,7 @@ HTTPBase.prototype.handleMounts = async function handleMounts(req, res) { */ HTTPBase.prototype.handleStack = async function handleStack(req, res) { - for (let route of this.stack) { + for (const route of this.stack) { if (!route.hasPrefix(req.pathname)) continue; @@ -481,7 +481,7 @@ HTTPBase.prototype.handleStack = async function handleStack(req, res) { */ HTTPBase.prototype.handleHooks = async function handleHooks(req, res) { - for (let route of this.hooks) { + for (const route of this.hooks) { if (!route.hasPrefix(req.pathname)) continue; @@ -532,7 +532,7 @@ HTTPBase.prototype._initSockets = function _initSockets() { */ HTTPBase.prototype.to = function to(name, ...args) { - let list = this.channels.get(name); + const list = this.channels.get(name); if (!list) return; @@ -540,7 +540,7 @@ HTTPBase.prototype.to = function to(name, ...args) { assert(list.size > 0); for (let item = list.head; item; item = item.next) { - let socket = item.value; + const socket = item.value; socket.emit(...args); } }; @@ -553,7 +553,7 @@ HTTPBase.prototype.to = function to(name, ...args) { */ HTTPBase.prototype.all = function all() { - let list = this.sockets; + const list = this.sockets; for (let socket = list.head; socket; socket = socket.next) socket.emit.apply(socket, arguments); @@ -566,7 +566,7 @@ HTTPBase.prototype.all = function all() { */ HTTPBase.prototype.addSocket = function addSocket(ws) { - let socket = new WebSocket(ws, this); + const socket = new WebSocket(ws, this); socket.on('error', (err) => { this.emit('error', err); @@ -586,7 +586,7 @@ HTTPBase.prototype.addSocket = function addSocket(ws) { this.sockets.push(socket); - for (let route of this.mounts) + for (const route of this.mounts) route.handler.addSocket(ws); this.emit('socket', socket); @@ -599,7 +599,7 @@ HTTPBase.prototype.addSocket = function addSocket(ws) { */ HTTPBase.prototype.removeSocket = function removeSocket(socket) { - for (let key of socket.channels.keys()) + for (const key of socket.channels.keys()) this.leaveChannel(socket, key); assert(this.sockets.remove(socket)); @@ -638,8 +638,8 @@ HTTPBase.prototype.joinChannel = function joinChannel(socket, name) { */ HTTPBase.prototype.leaveChannel = function leaveChannel(socket, name) { - let list = this.channels.get(name); - let item = socket.channels.get(name); + const list = this.channels.get(name); + const item = socket.channels.get(name); if (!item) return; @@ -660,7 +660,7 @@ HTTPBase.prototype.leaveChannel = function leaveChannel(socket, name) { */ HTTPBase.prototype.channel = function channel(name) { - let list = this.channels.get(name); + const list = this.channels.get(name); if (!list) return; @@ -813,7 +813,7 @@ HTTPBase.prototype.listen = function listen(port, host) { return new Promise((resolve, reject) => { this.server.once('error', reject); this.server.listen(port, host, () => { - let addr = this.address(); + const addr = this.address(); this.emit('listening', addr); @@ -1062,7 +1062,7 @@ function Route(ctx, path, handler) { Route.prototype.compile = function compile() { let path = this.path; - let map = this.map; + const map = this.map; if (this.compiled) return; @@ -1100,8 +1100,8 @@ Route.prototype.match = function _match(pathname) { params = Object.create(null); for (let i = 1; i < match.length; i++) { - let item = match[i]; - let key = this.map[i - 1]; + const item = match[i]; + const key = this.map[i - 1]; if (key) params[key] = item; @@ -1229,7 +1229,7 @@ Request.prototype.init = function init(req, res, url) { }; Request.prototype.parse = function parse(url) { - let uri = URL.parse(url); + const uri = URL.parse(url); let pathname = uri.pathname; let query = Object.create(null); let trailing = false; @@ -1295,7 +1295,7 @@ Request.prototype.parse = function parse(url) { }; Request.prototype.rewrite = function rewrite(url) { - let req = new Request(); + const req = new Request(); req.init(this.req, this.res, url); req.body = this.body; req.hasBody = this.hasBody; @@ -1468,7 +1468,7 @@ Response.prototype.send = function send(code, msg, type) { this.setType(type); if (typeof msg === 'string') { - let len = Buffer.byteLength(msg, 'utf8'); + const len = Buffer.byteLength(msg, 'utf8'); this.setHeader('Content-Length', len + ''); try { this.write(msg, 'utf8'); @@ -1522,11 +1522,11 @@ function WebSocket(socket, ctx) { util.inherits(WebSocket, EventEmitter); WebSocket.prototype.init = function init() { - let socket = this.socket; - let onevent = socket.onevent.bind(socket); + const socket = this.socket; + const onevent = socket.onevent.bind(socket); socket.onevent = (packet) => { - let result = onevent(packet); + const result = onevent(packet); this.onevent(packet); return result; }; @@ -1541,8 +1541,8 @@ WebSocket.prototype.init = function init() { }; WebSocket.prototype.onevent = async function onevent(packet) { - let args = (packet.data || []).slice(); - let type = args.shift() || ''; + const args = (packet.data || []).slice(); + const type = args.shift() || ''; let ack, result; if (typeof args[args.length - 1] === 'function') @@ -1573,7 +1573,7 @@ WebSocket.prototype.hook = function hook(type, handler) { }; WebSocket.prototype.fire = async function fire(type, args) { - let handler = this.hooks[type]; + const handler = this.hooks[type]; if (!handler) return; @@ -1590,7 +1590,7 @@ WebSocket.prototype.leave = function leave(name) { }; WebSocket.prototype.dispatch = function dispatch() { - let emit = EventEmitter.prototype.emit; + const emit = EventEmitter.prototype.emit; return emit.apply(this, arguments); }; @@ -1599,7 +1599,7 @@ WebSocket.prototype.emit = function emit() { }; WebSocket.prototype.call = function call(...args) { - let socket = this.socket; + const socket = this.socket; return new Promise((resolve, reject) => { args.push(co.wrap(resolve, reject)); socket.emit(...args); @@ -1615,16 +1615,16 @@ WebSocket.prototype.destroy = function destroy() { */ function parsePairs(str, limit) { - let parts = str.split('&'); - let data = Object.create(null); + const parts = str.split('&'); + const data = Object.create(null); if (parts.length > limit) return data; assert(!limit || parts.length <= limit, 'Too many keys in querystring.'); - for (let pair of parts) { - let index = pair.indexOf('='); + for (const pair of parts) { + const index = pair.indexOf('='); let key, value; if (index === -1) { diff --git a/lib/http/client.js b/lib/http/client.js index 98921be55..5cb028c86 100644 --- a/lib/http/client.js +++ b/lib/http/client.js @@ -565,7 +565,7 @@ HTTPClient.prototype.getLast = function getLast(id, account, limit) { */ HTTPClient.prototype.getRange = function getRange(id, account, options) { - let body = { + const body = { account: account, start: options.start, end: options.end , @@ -632,7 +632,7 @@ HTTPClient.prototype.getWalletCoin = function getWalletCoin(id, account, hash, i */ HTTPClient.prototype.send = function send(id, options) { - let body = Object.assign({}, options); + const body = Object.assign({}, options); if (!body.outputs) body.outputs = []; @@ -655,7 +655,7 @@ HTTPClient.prototype.send = function send(id, options) { */ HTTPClient.prototype.retoken = async function retoken(id, passphrase) { - let body = await this._post(`/wallet/${id}/retoken`, { passphrase }); + const body = await this._post(`/wallet/${id}/retoken`, { passphrase }); return body.token; }; @@ -667,7 +667,7 @@ HTTPClient.prototype.retoken = async function retoken(id, passphrase) { */ HTTPClient.prototype.setPassphrase = function setPassphrase(id, old, new_) { - let body = { old: old, passphrase: new_ }; + const body = { old: old, passphrase: new_ }; return this._post(`/wallet/${id}/passphrase`, body); }; @@ -679,7 +679,7 @@ HTTPClient.prototype.setPassphrase = function setPassphrase(id, old, new_) { */ HTTPClient.prototype.createTX = function createTX(id, options) { - let body = Object.assign({}, options); + const body = Object.assign({}, options); if (!body.outputs) body.outputs = []; @@ -704,7 +704,7 @@ HTTPClient.prototype.createTX = function createTX(id, options) { */ HTTPClient.prototype.sign = function sign(id, tx, options) { - let body = Object.assign({}, options); + const body = Object.assign({}, options); body.tx = toHex(tx); return this._post(`/wallet/${id}/sign`, body); }; @@ -753,7 +753,7 @@ HTTPClient.prototype.getWIF = function getWIF(id, address, passphrase) { */ HTTPClient.prototype.addSharedKey = function addSharedKey(id, account, key) { - let body = { account: account, accountKey: key }; + const body = { account: account, accountKey: key }; return this._put(`/wallet/${id}/shared-key`, body); }; @@ -767,7 +767,7 @@ HTTPClient.prototype.addSharedKey = function addSharedKey(id, account, key) { */ HTTPClient.prototype.removeSharedKey = function removeSharedKey(id, account, key) { - let body = { account: account, accountKey: key }; + const body = { account: account, accountKey: key }; return this._del(`/wallet/${id}/shared-key`, body); }; @@ -780,7 +780,7 @@ HTTPClient.prototype.removeSharedKey = function removeSharedKey(id, account, key */ HTTPClient.prototype.importPrivate = function importPrivate(id, account, key) { - let body = { account: account, privateKey: key }; + const body = { account: account, privateKey: key }; return this._post(`/wallet/${id}/import`, body); }; @@ -793,7 +793,7 @@ HTTPClient.prototype.importPrivate = function importPrivate(id, account, key) { */ HTTPClient.prototype.importPublic = function importPublic(id, account, key) { - let body = { account: account, publicKey: key }; + const body = { account: account, publicKey: key }; return this._post(`/wallet/${id}/import`, body); }; diff --git a/lib/http/request.js b/lib/http/request.js index 4a8775221..022120bcb 100644 --- a/lib/http/request.js +++ b/lib/http/request.js @@ -77,7 +77,7 @@ RequestOptions.prototype.setURI = function setURI(uri) { this.port = uri.port || (this.ssl ? 443 : 80); if (uri.auth) { - let parts = uri.auth.split(':'); + const parts = uri.auth.split(':'); this.auth = { username: parts[0] || '', password: parts[1] || '' @@ -239,8 +239,8 @@ RequestOptions.prototype.getHeaders = function getHeaders() { headers['Content-Length'] = this.body.length + ''; if (this.auth) { - let auth = `${this.auth.username}:${this.auth.password}`; - let data = Buffer.from(auth, 'utf8'); + const auth = `${this.auth.username}:${this.auth.password}`; + const data = Buffer.from(auth, 'utf8'); headers['Authorization'] = `Basic ${data.toString('base64')}`; } @@ -360,8 +360,8 @@ Request.prototype.destroy = function destroy() { }; Request.prototype.start = function start() { - let backend = this.options.getBackend(); - let options = this.options.toHTTP(); + const backend = this.options.getBackend(); + const options = this.options.toHTTP(); this.startTimeout(); @@ -427,8 +427,8 @@ Request.prototype.finish = function finish(err) { Request.prototype._onResponse = function _onResponse(response) { let type = response.headers['content-type']; - let length = response.headers['content-length']; - let location = response.headers['location']; + const length = response.headers['content-length']; + const location = response.headers['location']; if (location) { if (++this.redirects > this.options.maxRedirects) { @@ -531,7 +531,7 @@ function request(options) { options.buffer = true; return new Promise((resolve, reject) => { - let stream = new Request(options); + const stream = new Request(options); stream.on('error', err => reject(err)); stream.on('end', () => resolve(stream)); @@ -542,7 +542,7 @@ function request(options) { } request.stream = function _stream(options) { - let stream = new Request(options); + const stream = new Request(options); stream.start(); return stream; }; diff --git a/lib/http/rpc.js b/lib/http/rpc.js index 1edbf4443..58a8ae731 100644 --- a/lib/http/rpc.js +++ b/lib/http/rpc.js @@ -216,13 +216,13 @@ RPC.prototype.stop = async function stop(args, help) { */ RPC.prototype.getNetworkInfo = async function getNetworkInfo(args, help) { - let hosts = this.pool.hosts; - let locals = []; + const hosts = this.pool.hosts; + const locals = []; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'getnetworkinfo'); - for (let local of hosts.local.values()) { + for (const local of hosts.local.values()) { locals.push({ address: local.addr.host, port: local.addr.port, @@ -248,9 +248,9 @@ RPC.prototype.getNetworkInfo = async function getNetworkInfo(args, help) { }; RPC.prototype.addNode = async function addNode(args, help) { - let valid = new Validator([args]); - let node = valid.str(0, ''); - let cmd = valid.str(1, ''); + const valid = new Validator([args]); + const node = valid.str(0, ''); + const cmd = valid.str(1, ''); if (help || args.length !== 2) throw new RPCError(errs.MISC_ERROR, 'addnode "node" "add|remove|onetry"'); @@ -261,10 +261,10 @@ RPC.prototype.addNode = async function addNode(args, help) { ; // fall through } case 'onetry': { - let addr = parseNetAddress(node, this.network); + const addr = parseNetAddress(node, this.network); if (!this.pool.peers.get(addr.hostname)) { - let peer = this.pool.createOutbound(addr); + const peer = this.pool.createOutbound(addr); this.pool.peers.add(peer); } @@ -280,7 +280,7 @@ RPC.prototype.addNode = async function addNode(args, help) { }; RPC.prototype.disconnectNode = async function disconnectNode(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let addr = valid.str(0, ''); let peer; @@ -297,10 +297,10 @@ RPC.prototype.disconnectNode = async function disconnectNode(args, help) { }; RPC.prototype.getAddedNodeInfo = async function getAddedNodeInfo(args, help) { - let hosts = this.pool.hosts; - let valid = new Validator([args]); - let addr = valid.str(0, ''); - let result = []; + const hosts = this.pool.hosts; + const valid = new Validator([args]); + const addr = valid.str(0, ''); + const result = []; let target; if (help || args.length > 1) @@ -309,7 +309,7 @@ RPC.prototype.getAddedNodeInfo = async function getAddedNodeInfo(args, help) { if (args.length === 1) target = parseIP(addr, this.network); - for (let node of hosts.nodes) { + for (const node of hosts.nodes) { let peer; if (target) { @@ -380,14 +380,14 @@ RPC.prototype.getNetTotals = async function getNetTotals(args, help) { }; RPC.prototype.getPeerInfo = async function getPeerInfo(args, help) { - let peers = []; + const peers = []; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'getpeerinfo'); for (let peer = this.pool.peers.head(); peer; peer = peer.next) { let offset = this.network.time.known.get(peer.hostname()); - let hashes = []; + const hashes = []; if (offset == null) offset = 0; @@ -441,9 +441,9 @@ RPC.prototype.ping = async function ping(args, help) { }; RPC.prototype.setBan = async function setBan(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let addr = valid.str(0, ''); - let action = valid.str(1, ''); + const action = valid.str(1, ''); if (help || args.length < 2 @@ -467,12 +467,12 @@ RPC.prototype.setBan = async function setBan(args, help) { }; RPC.prototype.listBanned = async function listBanned(args, help) { - let banned = []; + const banned = []; if (help || args.length !== 0) throw new RPCError(errs.MISC_ERROR, 'listbanned'); - for (let [host, time] of this.pool.hosts.banned) { + for (const [host, time] of this.pool.hosts.banned) { banned.push({ address: host, banned_until: time + this.pool.options.banTime, @@ -533,10 +533,10 @@ RPC.prototype.getBlockCount = async function getBlockCount(args, help) { }; RPC.prototype.getBlock = async function getBlock(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let verbose = valid.bool(1, true); - let details = valid.bool(2, false); + const valid = new Validator([args]); + const hash = valid.hash(0); + const verbose = valid.bool(1, true); + const details = valid.bool(2, false); let entry, block; if (help || args.length < 1 || args.length > 3) @@ -569,10 +569,10 @@ RPC.prototype.getBlock = async function getBlock(args, help) { }; RPC.prototype.getBlockByHeight = async function getBlockByHeight(args, help) { - let valid = new Validator([args]); - let height = valid.u32(0, -1); - let verbose = valid.bool(1, true); - let details = valid.bool(2, false); + const valid = new Validator([args]); + const height = valid.u32(0, -1); + const verbose = valid.bool(1, true); + const details = valid.bool(2, false); let entry, block; if (help || args.length < 1 || args.length > 3) { @@ -607,8 +607,8 @@ RPC.prototype.getBlockByHeight = async function getBlockByHeight(args, help) { }; RPC.prototype.getBlockHash = async function getBlockHash(args, help) { - let valid = new Validator([args]); - let height = valid.u32(0); + const valid = new Validator([args]); + const height = valid.u32(0); let hash; if (help || args.length !== 1) @@ -626,9 +626,9 @@ RPC.prototype.getBlockHash = async function getBlockHash(args, help) { }; RPC.prototype.getBlockHeader = async function getBlockHeader(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let verbose = valid.bool(1, true); + const valid = new Validator([args]); + const hash = valid.hash(0); + const verbose = valid.bool(1, true); let entry; if (help || args.length < 1 || args.length > 2) @@ -657,8 +657,8 @@ RPC.prototype.getChainTips = async function getChainTips(args, help) { tips = await this.chain.db.getTips(); result = []; - for (let hash of tips) { - let entry = await this.chain.db.getEntry(hash); + for (const hash of tips) { + const entry = await this.chain.db.getEntry(hash); let fork, main; assert(entry); @@ -701,10 +701,10 @@ RPC.prototype.getMempoolInfo = async function getMempoolInfo(args, help) { }; RPC.prototype.getMempoolAncestors = async function getMempoolAncestors(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let verbose = valid.bool(1, false); - let out = []; + const valid = new Validator([args]); + const hash = valid.hash(0); + const verbose = valid.bool(1, false); + const out = []; let entries, entry; if (help || args.length < 1 || args.length > 2) @@ -724,10 +724,10 @@ RPC.prototype.getMempoolAncestors = async function getMempoolAncestors(args, hel entries = this.mempool.getAncestors(entry); if (verbose) { - for (let entry of entries) + for (const entry of entries) out.push(this.entryToJSON(entry)); } else { - for (let entry of entries) + for (const entry of entries) out.push(entry.txid()); } @@ -735,10 +735,10 @@ RPC.prototype.getMempoolAncestors = async function getMempoolAncestors(args, hel }; RPC.prototype.getMempoolDescendants = async function getMempoolDescendants(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let verbose = valid.bool(1, false); - let out = []; + const valid = new Validator([args]); + const hash = valid.hash(0); + const verbose = valid.bool(1, false); + const out = []; let entries, entry; if (help || args.length < 1 || args.length > 2) @@ -758,10 +758,10 @@ RPC.prototype.getMempoolDescendants = async function getMempoolDescendants(args, entries = this.mempool.getDescendants(entry); if (verbose) { - for (let entry of entries) + for (const entry of entries) out.push(this.entryToJSON(entry)); } else { - for (let entry of entries) + for (const entry of entries) out.push(entry.txid()); } @@ -769,8 +769,8 @@ RPC.prototype.getMempoolDescendants = async function getMempoolDescendants(args, }; RPC.prototype.getMempoolEntry = async function getMempoolEntry(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); + const valid = new Validator([args]); + const hash = valid.hash(0); let entry; if (help || args.length !== 1) @@ -791,9 +791,9 @@ RPC.prototype.getMempoolEntry = async function getMempoolEntry(args, help) { }; RPC.prototype.getRawMempool = async function getRawMempool(args, help) { - let valid = new Validator([args]); - let verbose = valid.bool(0, false); - let out = {}; + const valid = new Validator([args]); + const verbose = valid.bool(0, false); + const out = {}; let hashes; if (help || args.length > 1) @@ -803,7 +803,7 @@ RPC.prototype.getRawMempool = async function getRawMempool(args, help) { throw new RPCError(errs.MISC_ERROR, 'No mempool available.'); if (verbose) { - for (let entry of this.mempool.map.values()) + for (const entry of this.mempool.map.values()) out[entry.txid()] = this.entryToJSON(entry); return out; @@ -815,10 +815,10 @@ RPC.prototype.getRawMempool = async function getRawMempool(args, help) { }; RPC.prototype.getTXOut = async function getTXOut(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let index = valid.u32(1); - let mempool = valid.bool(2, true); + const valid = new Validator([args]); + const hash = valid.hash(0); + const index = valid.u32(1); + const mempool = valid.bool(2, true); let coin; if (help || args.length < 2 || args.length > 3) @@ -857,9 +857,9 @@ RPC.prototype.getTXOut = async function getTXOut(args, help) { RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { let valid = new Validator([args]); - let txids = valid.array(0); - let hash = valid.hash(1); - let uniq = new Set(); + const txids = valid.array(0); + const hash = valid.hash(1); + const uniq = new Set(); let block, last; if (help || (args.length !== 1 && args.length !== 2)) { @@ -879,7 +879,7 @@ RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { valid = new Validator([txids]); for (let i = 0; i < txids.length; i++) { - let txid = valid.hash(i); + const txid = valid.hash(i); if (!txid) throw new RPCError(errs.TYPE_ERROR, 'Invalid TXID.'); @@ -895,12 +895,12 @@ RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { if (hash) { block = await this.chain.db.getBlock(hash); } else if (this.chain.options.indexTX) { - let tx = await this.chain.db.getMeta(last); + const tx = await this.chain.db.getMeta(last); if (!tx) return; block = await this.chain.db.getBlock(tx.block); } else { - let coins = await this.chain.db.getCoins(last); + const coins = await this.chain.db.getCoins(last); if (!coins) return; block = await this.chain.db.getBlock(coins.height); @@ -909,7 +909,7 @@ RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { if (!block) throw new RPCError(errs.MISC_ERROR, 'Block not found.'); - for (let txid of txids) { + for (const txid of txids) { if (!block.hasTX(txid)) { throw new RPCError(errs.VERIFY_ERROR, 'Block does not contain all txids.'); @@ -922,9 +922,9 @@ RPC.prototype.getTXOutProof = async function getTXOutProof(args, help) { }; RPC.prototype.verifyTXOutProof = async function verifyTXOutProof(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); - let out = []; + const valid = new Validator([args]); + const data = valid.buf(0); + const out = []; let block, entry, tree; if (help || args.length !== 1) @@ -945,7 +945,7 @@ RPC.prototype.verifyTXOutProof = async function verifyTXOutProof(args, help) { tree = block.getTree(); - for (let hash of tree.matches) + for (const hash of tree.matches) out.push(util.revHex(hash)); return out; @@ -990,9 +990,9 @@ RPC.prototype.pruneBlockchain = async function pruneBlockchain(args, help) { }; RPC.prototype.verifyChain = async function verifyChain(args, help) { - let valid = new Validator([args]); - let level = valid.u32(0); - let blocks = valid.u32(1); + const valid = new Validator([args]); + const level = valid.u32(0); + const blocks = valid.u32(1); if (help || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'verifychain ( checklevel numblocks )'); @@ -1014,7 +1014,7 @@ RPC.prototype.verifyChain = async function verifyChain(args, help) { */ RPC.prototype.submitWork = async function submitWork(data) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._submitWork(data); } finally { @@ -1023,7 +1023,7 @@ RPC.prototype.submitWork = async function submitWork(data) { }; RPC.prototype._submitWork = async function _submitWork(data) { - let attempt = this.attempt; + const attempt = this.attempt; let header, nonce, time, nonces; let n1, n2, proof, block, entry; @@ -1083,7 +1083,7 @@ RPC.prototype._submitWork = async function _submitWork(data) { }; RPC.prototype.createWork = async function createWork(data) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._createWork(data); } finally { @@ -1092,10 +1092,10 @@ RPC.prototype.createWork = async function createWork(data) { }; RPC.prototype._createWork = async function _createWork() { - let attempt = await this.updateWork(); - let n1 = this.nonce1; - let n2 = this.nonce2; - let time = attempt.time; + const attempt = await this.updateWork(); + const n1 = this.nonce1; + const n2 = this.nonce2; + const time = attempt.time; let data, root, head; data = Buffer.allocUnsafe(128); @@ -1124,8 +1124,8 @@ RPC.prototype.getWorkLongpoll = async function getWorkLongpoll(args, help) { }; RPC.prototype.getWork = async function getWork(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); if (args.length > 1) throw new RPCError(errs.MISC_ERROR, 'getwork ( "data" )'); @@ -1141,8 +1141,8 @@ RPC.prototype.getWork = async function getWork(args, help) { }; RPC.prototype.submitBlock = async function submitBlock(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let block; if (help || args.length < 1 || args.length > 2) { @@ -1156,14 +1156,14 @@ RPC.prototype.submitBlock = async function submitBlock(args, help) { }; RPC.prototype.getBlockTemplate = async function getBlockTemplate(args, help) { - let validator = new Validator([args]); - let options = validator.obj(0, {}); - let valid = new Validator([options]); - let mode = valid.str('mode', 'template'); - let lpid = valid.str('longpollid'); - let data = valid.buf('data'); + const validator = new Validator([args]); + const options = validator.obj(0, {}); + const valid = new Validator([options]); + const mode = valid.str('mode', 'template'); + const lpid = valid.str('longpollid'); + const data = valid.buf('data'); let rules = valid.array('rules'); - let capabilities = valid.array('capabilities'); + const capabilities = valid.array('capabilities'); let maxVersion = valid.u32('maxversion', -1); let coinbase = false; let txnCap = false; @@ -1203,7 +1203,7 @@ RPC.prototype.getBlockTemplate = async function getBlockTemplate(args, help) { maxVersion = -1; if (capabilities) { - for (let capability of capabilities) { + for (const capability of capabilities) { if (typeof capability !== 'string') throw new RPCError(errs.TYPE_ERROR, 'Invalid capability.'); @@ -1259,7 +1259,7 @@ RPC.prototype.getBlockTemplate = async function getBlockTemplate(args, help) { }; RPC.prototype.createTemplate = async function createTemplate(maxVersion, coinbase, rules) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._createTemplate(maxVersion, coinbase, rules); } finally { @@ -1268,14 +1268,14 @@ RPC.prototype.createTemplate = async function createTemplate(maxVersion, coinbas }; RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinbase, rules) { - let attempt = await this.getTemplate(); + const attempt = await this.getTemplate(); let version = attempt.version; - let scale = attempt.witness ? 1 : consensus.WITNESS_SCALE_FACTOR; - let mutable = ['time', 'transactions', 'prevblock']; - let txs = []; - let index = new Map(); - let vbavailable = {}; - let vbrules = []; + const scale = attempt.witness ? 1 : consensus.WITNESS_SCALE_FACTOR; + const mutable = ['time', 'transactions', 'prevblock']; + const txs = []; + const index = new Map(); + const vbavailable = {}; + const vbrules = []; let json; // The miner doesn't support @@ -1296,19 +1296,19 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb // Build an index of every transaction. for (let i = 0; i < attempt.items.length; i++) { - let entry = attempt.items[i]; + const entry = attempt.items[i]; index.set(entry.hash, i + 1); } // Calculate dependencies for each transaction. for (let i = 0; i < attempt.items.length; i++) { - let entry = attempt.items[i]; - let tx = entry.tx; - let deps = []; + const entry = attempt.items[i]; + const tx = entry.tx; + const deps = []; for (let j = 0; j < tx.inputs.length; j++) { - let input = tx.inputs[j]; - let dep = index.get(input.prevout.hash); + const input = tx.inputs[j]; + const dep = index.get(input.prevout.hash); if (dep == null) continue; @@ -1339,8 +1339,8 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb rules.push('segwit'); // Calculate version based on given rules. - for (let deploy of this.network.deploys) { - let state = await this.chain.getState(this.chain.tip, deploy); + for (const deploy of this.network.deploys) { + const state = await this.chain.getState(this.chain.tip, deploy); let name = deploy.name; switch (state) { @@ -1416,7 +1416,7 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb // The client wants a coinbasetxn // instead of a coinbasevalue. if (coinbase) { - let tx = attempt.toCoinbase(); + const tx = attempt.toCoinbase(); // Pop off the nonces. tx.inputs[0].script.code.pop(); @@ -1425,7 +1425,7 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb if (attempt.witness) { // We don't include the commitment // output (see bip145). - let output = tx.outputs.pop(); + const output = tx.outputs.pop(); assert(output.script.isCommitment()); // Also not including the witness nonce. @@ -1455,7 +1455,7 @@ RPC.prototype._createTemplate = async function _createTemplate(maxVersion, coinb }; RPC.prototype.getMiningInfo = async function getMiningInfo(args, help) { - let attempt = this.attempt; + const attempt = this.attempt; let size = 0; let weight = 0; let txs = 0; @@ -1469,7 +1469,7 @@ RPC.prototype.getMiningInfo = async function getMiningInfo(args, help) { txs = attempt.items.length + 1; diff = attempt.getDifficulty(); size = 1000; - for (let item of attempt.items) + for (const item of attempt.items) size += item.tx.getBaseSize(); } @@ -1492,9 +1492,9 @@ RPC.prototype.getMiningInfo = async function getMiningInfo(args, help) { }; RPC.prototype.getNetworkHashPS = async function getNetworkHashPS(args, help) { - let valid = new Validator([args]); - let lookup = valid.u32(0, 120); - let height = valid.u32(1); + const valid = new Validator([args]); + const lookup = valid.u32(0, 120); + const height = valid.u32(1); if (help || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'getnetworkhashps ( blocks height )'); @@ -1503,10 +1503,10 @@ RPC.prototype.getNetworkHashPS = async function getNetworkHashPS(args, help) { }; RPC.prototype.prioritiseTransaction = async function prioritiseTransaction(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let pri = valid.num(1); - let fee = valid.i64(2); + const valid = new Validator([args]); + const hash = valid.hash(0); + const pri = valid.num(1); + const fee = valid.i64(2); let entry; if (help || args.length !== 3) { @@ -1534,8 +1534,8 @@ RPC.prototype.prioritiseTransaction = async function prioritiseTransaction(args, }; RPC.prototype.verifyBlock = async function verifyBlock(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let block; if (help || args.length !== 1) @@ -1571,9 +1571,9 @@ RPC.prototype.getGenerate = async function getGenerate(args, help) { }; RPC.prototype.setGenerate = async function setGenerate(args, help) { - let valid = new Validator([args]); - let mine = valid.bool(0, false); - let limit = valid.u32(1, 0); + const valid = new Validator([args]); + const mine = valid.bool(0, false); + const limit = valid.u32(1, 0); if (help || args.length < 1 || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'setgenerate mine ( proclimit )'); @@ -1597,9 +1597,9 @@ RPC.prototype.setGenerate = async function setGenerate(args, help) { }; RPC.prototype.generate = async function generate(args, help) { - let valid = new Validator([args]); - let blocks = valid.u32(0, 1); - let tries = valid.u32(1); + const valid = new Validator([args]); + const blocks = valid.u32(0, 1); + const tries = valid.u32(1); if (help || args.length < 1 || args.length > 2) throw new RPCError(errs.MISC_ERROR, 'generate numblocks ( maxtries )'); @@ -1613,10 +1613,10 @@ RPC.prototype.generate = async function generate(args, help) { }; RPC.prototype.generateToAddress = async function _generateToAddress(args, help) { - let valid = new Validator([args]); - let blocks = valid.u32(0, 1); + const valid = new Validator([args]); + const blocks = valid.u32(0, 1); let addr = valid.str(1, ''); - let tries = valid.u32(2); + const tries = valid.u32(2); if (help || args.length < 2 || args.length > 3) { throw new RPCError(errs.MISC_ERROR, @@ -1634,10 +1634,10 @@ RPC.prototype.generateToAddress = async function _generateToAddress(args, help) RPC.prototype.createRawTransaction = async function createRawTransaction(args, help) { let valid = new Validator([args]); - let inputs = valid.array(0); - let sendTo = valid.obj(1); - let locktime = valid.u32(2); - let uniq = new Set(); + const inputs = valid.array(0); + const sendTo = valid.obj(1); + const locktime = valid.u32(2); + const uniq = new Set(); let tx; if (help || args.length < 2 || args.length > 3) { @@ -1659,9 +1659,9 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h tx.locktime = locktime; for (let input of tx.inputs) { - let valid = new Validator([input]); - let hash = valid.hash('txid'); - let index = valid.u32('vout'); + const valid = new Validator([input]); + const hash = valid.hash('txid'); + const index = valid.u32('vout'); let sequence = valid.u32('sequence', 0xffffffff); if (tx.locktime) @@ -1680,11 +1680,11 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h valid = new Validator([sendTo]); - for (let key of Object.keys(sendTo)) { + for (const key of Object.keys(sendTo)) { let addr, b58, value, output; if (key === 'data') { - let value = valid.buf(key); + const value = valid.buf(key); let output; if (!value) @@ -1722,8 +1722,8 @@ RPC.prototype.createRawTransaction = async function createRawTransaction(args, h }; RPC.prototype.decodeRawTransaction = async function decodeRawTransaction(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let tx; if (help || args.length !== 1) @@ -1738,8 +1738,8 @@ RPC.prototype.decodeRawTransaction = async function decodeRawTransaction(args, h }; RPC.prototype.decodeScript = async function decodeScript(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let script, addr; if (help || args.length !== 1) @@ -1759,9 +1759,9 @@ RPC.prototype.decodeScript = async function decodeScript(args, help) { }; RPC.prototype.getRawTransaction = async function getRawTransaction(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); - let verbose = valid.bool(1, false); + const valid = new Validator([args]); + const hash = valid.hash(0); + const verbose = valid.bool(1, false); let json, meta, tx, entry; if (help || args.length < 1 || args.length > 2) @@ -1791,8 +1791,8 @@ RPC.prototype.getRawTransaction = async function getRawTransaction(args, help) { }; RPC.prototype.sendRawTransaction = async function sendRawTransaction(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let tx; if (help || args.length < 1 || args.length > 2) { @@ -1811,14 +1811,14 @@ RPC.prototype.sendRawTransaction = async function sendRawTransaction(args, help) }; RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) { - let valid = new Validator([args]); - let data = valid.buf(0); - let prevout = valid.array(1); - let secrets = valid.array(2); - let sighash = valid.str(3); - let type = Script.hashType.ALL; - let map = new Map(); - let keys = []; + const valid = new Validator([args]); + const data = valid.buf(0); + const prevout = valid.array(1); + const secrets = valid.array(2); + const sighash = valid.str(3); + const type = Script.hashType.ALL; + const map = new Map(); + const keys = []; let tx; if (help || args.length < 1 || args.length > 4) { @@ -1840,22 +1840,22 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) tx.view = await this.mempool.getSpentView(tx); if (secrets) { - let valid = new Validator([secrets]); + const valid = new Validator([secrets]); for (let i = 0; i < secrets.length; i++) { - let secret = valid.str(i, ''); - let key = parseSecret(secret, this.network); + const secret = valid.str(i, ''); + const key = parseSecret(secret, this.network); map.set(key.getPublicKey('hex'), key); keys.push(key); } } if (prevout) { - for (let prev of prevout) { - let valid = new Validator([prev]); - let hash = valid.hash('txid'); - let index = valid.u32('index'); + for (const prev of prevout) { + const valid = new Validator([prev]); + const hash = valid.hash('txid'); + const index = valid.u32('index'); let script = valid.buf('scriptPubKey'); - let value = valid.btc('amount'); + const value = valid.btc('amount'); let redeem = valid.buf('redeemScript'); let coin; @@ -1883,7 +1883,7 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) redeem = Script.fromRaw(redeem); - for (let op of redeem.code) { + for (const op of redeem.code) { let key; if (!op.data) @@ -1902,7 +1902,7 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) } if (sighash) { - let parts = sighash.split('|'); + const parts = sighash.split('|'); let type = Script.hashType[parts[0]]; if (type == null) @@ -1932,9 +1932,9 @@ RPC.prototype.signRawTransaction = async function signRawTransaction(args, help) RPC.prototype.createMultisig = async function createMultisig(args, help) { let valid = new Validator([args]); - let keys = valid.array(1, []); - let m = valid.u32(0, 0); - let n = keys.length; + const keys = valid.array(1, []); + const m = valid.u32(0, 0); + const n = keys.length; let script, addr; if (help || args.length < 2 || args.length > 2) @@ -1946,7 +1946,7 @@ RPC.prototype.createMultisig = async function createMultisig(args, help) { valid = new Validator([keys]); for (let i = 0; i < keys.length; i++) { - let key = valid.buf(i); + const key = valid.buf(i); if (!key) throw new RPCError(errs.TYPE_ERROR, 'Invalid key.'); @@ -1971,8 +1971,8 @@ RPC.prototype.createMultisig = async function createMultisig(args, help) { }; RPC.prototype.createWitnessAddress = async function createWitnessAddress(args, help) { - let valid = new Validator([args]); - let raw = valid.buf(0); + const valid = new Validator([args]); + const raw = valid.buf(0); let script, program, addr; if (help || args.length !== 1) @@ -1992,8 +1992,8 @@ RPC.prototype.createWitnessAddress = async function createWitnessAddress(args, h }; RPC.prototype.validateAddress = async function validateAddress(args, help) { - let valid = new Validator([args]); - let b58 = valid.str(0, ''); + const valid = new Validator([args]); + const b58 = valid.str(0, ''); let addr, script; if (help || args.length !== 1) @@ -2019,9 +2019,9 @@ RPC.prototype.validateAddress = async function validateAddress(args, help) { }; RPC.prototype.verifyMessage = async function verifyMessage(args, help) { - let valid = new Validator([args]); - let b58 = valid.str(0, ''); - let sig = valid.buf(1, null, 'base64'); + const valid = new Validator([args]); + const b58 = valid.str(0, ''); + const sig = valid.buf(1, null, 'base64'); let msg = valid.str(2); let addr, key; @@ -2049,7 +2049,7 @@ RPC.prototype.verifyMessage = async function verifyMessage(args, help) { }; RPC.prototype.signMessageWithPrivkey = async function signMessageWithPrivkey(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let key = valid.str(0, ''); let msg = valid.str(1, ''); let sig; @@ -2069,7 +2069,7 @@ RPC.prototype.signMessageWithPrivkey = async function signMessageWithPrivkey(arg }; RPC.prototype.estimateFee = async function estimateFee(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let blocks = valid.u32(0, 1); let fee; @@ -2091,7 +2091,7 @@ RPC.prototype.estimateFee = async function estimateFee(args, help) { }; RPC.prototype.estimatePriority = async function estimatePriority(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let blocks = valid.u32(0, 1); if (help || args.length !== 1) @@ -2107,7 +2107,7 @@ RPC.prototype.estimatePriority = async function estimatePriority(args, help) { }; RPC.prototype.estimateSmartFee = async function estimateSmartFee(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let blocks = valid.u32(0, 1); let fee; @@ -2134,7 +2134,7 @@ RPC.prototype.estimateSmartFee = async function estimateSmartFee(args, help) { }; RPC.prototype.estimateSmartPriority = async function estimateSmartPriority(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let blocks = valid.u32(0, 1); let pri; @@ -2156,8 +2156,8 @@ RPC.prototype.estimateSmartPriority = async function estimateSmartPriority(args, }; RPC.prototype.invalidateBlock = async function invalidateBlock(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); + const valid = new Validator([args]); + const hash = valid.hash(0); if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'invalidateblock "hash"'); @@ -2171,8 +2171,8 @@ RPC.prototype.invalidateBlock = async function invalidateBlock(args, help) { }; RPC.prototype.reconsiderBlock = async function reconsiderBlock(args, help) { - let valid = new Validator([args]); - let hash = valid.hash(0); + const valid = new Validator([args]); + const hash = valid.hash(0); if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'reconsiderblock "hash"'); @@ -2186,8 +2186,8 @@ RPC.prototype.reconsiderBlock = async function reconsiderBlock(args, help) { }; RPC.prototype.setMockTime = async function setMockTime(args, help) { - let valid = new Validator([args]); - let time = valid.u32(0); + const valid = new Validator([args]); + const time = valid.u32(0); let delta; if (help || args.length !== 1) @@ -2213,8 +2213,8 @@ RPC.prototype.getMemoryInfo = async function getMemoryInfo(args, help) { }; RPC.prototype.setLogLevel = async function setLogLevel(args, help) { - let valid = new Validator([args]); - let level = valid.str(0, ''); + const valid = new Validator([args]); + const level = valid.str(0, ''); if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'setloglevel "level"'); @@ -2255,7 +2255,7 @@ RPC.prototype.longpoll = function longpoll() { }; RPC.prototype.refreshBlock = function refreshBlock() { - let pollers = this.pollers; + const pollers = this.pollers; this.attempt = null; this.lastActivity = 0; @@ -2264,7 +2264,7 @@ RPC.prototype.refreshBlock = function refreshBlock() { this.nonce2 = 0; this.pollers = []; - for (let job of pollers) + for (const job of pollers) job.resolve(); }; @@ -2360,8 +2360,8 @@ RPC.prototype.updateWork = async function updateWork() { }; RPC.prototype.addBlock = async function addBlock(block) { - let unlock1 = await this.locker.lock(); - let unlock2 = await this.chain.locker.lock(); + const unlock1 = await this.locker.lock(); + const unlock2 = await this.chain.locker.lock(); try { return await this._addBlock(block); } finally { @@ -2378,11 +2378,11 @@ RPC.prototype._addBlock = async function _addBlock(block) { prev = await this.chain.db.getEntry(block.prevBlock); if (prev) { - let state = await this.chain.getDeployments(block.time, prev); + const state = await this.chain.getDeployments(block.time, prev); // Fix eloipool bug (witness nonce is not present). if (state.hasWitness() && block.getCommitmentHash()) { - let tx = block.txs[0]; + const tx = block.txs[0]; if (!tx.hasWitness()) { this.logger.warning('Submitted block had no witness nonce.'); this.logger.debug(tx); @@ -2430,11 +2430,11 @@ RPC.prototype.getSoftforks = function getSoftforks() { }; RPC.prototype.getBIP9Softforks = async function getBIP9Softforks() { - let tip = this.chain.tip; - let forks = {}; + const tip = this.chain.tip; + const forks = {}; - for (let deployment of this.network.deploys) { - let state = await this.chain.getState(tip, deployment); + for (const deployment of this.network.deploys) { + const state = await this.chain.getState(tip, deployment); let status; switch (state) { @@ -2490,7 +2490,7 @@ RPC.prototype.getHashRate = async function getHashRate(lookup, height) { entry = tip; for (let i = 0; i < lookup; i++) { - let entry = await entry.getPrevious(); + const entry = await entry.getPrevious(); if (!entry) throw new RPCError(errs.DATABASE_ERROR, 'Not found.'); @@ -2510,7 +2510,7 @@ RPC.prototype.getHashRate = async function getHashRate(lookup, height) { }; RPC.prototype.mineBlocks = async function mineBlocks(blocks, addr, tries) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._mineBlocks(blocks, addr, tries); } finally { @@ -2519,10 +2519,10 @@ RPC.prototype.mineBlocks = async function mineBlocks(blocks, addr, tries) { }; RPC.prototype._mineBlocks = async function _mineBlocks(blocks, addr, tries) { - let hashes = []; + const hashes = []; for (let i = 0; i < blocks; i++) { - let block = await this.miner.mineBlock(null, addr); + const block = await this.miner.mineBlock(null, addr); hashes.push(block.rhash()); assert(await this.chain.add(block)); } @@ -2544,8 +2544,8 @@ RPC.prototype.txToJSON = function txToJSON(tx, entry) { let conf = 0; let time = 0; let hash = null; - let vin = []; - let vout = []; + const vin = []; + const vout = []; if (entry) { height = entry.height; @@ -2554,8 +2554,8 @@ RPC.prototype.txToJSON = function txToJSON(tx, entry) { conf = this.chain.height - height + 1; } - for (let input of tx.inputs) { - let json = { + for (const input of tx.inputs) { + const json = { coinbase: undefined, txid: undefined, scriptSig: undefined, @@ -2584,7 +2584,7 @@ RPC.prototype.txToJSON = function txToJSON(tx, entry) { } for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; + const output = tx.outputs[i]; vout.push({ value: Amount.btc(output.value, true), n: i, @@ -2610,7 +2610,7 @@ RPC.prototype.txToJSON = function txToJSON(tx, entry) { }; RPC.prototype.scriptToJSON = function scriptToJSON(script, hex) { - let type = script.getType(); + const type = script.getType(); let addr = script.getAddress(); let out; @@ -2638,8 +2638,8 @@ RPC.prototype.scriptToJSON = function scriptToJSON(script, hex) { }; RPC.prototype.headerToJSON = async function headerToJSON(entry) { - let mtp = await entry.getMedianTime(); - let next = await this.chain.db.getNextHash(entry.hash); + const mtp = await entry.getMedianTime(); + const next = await this.chain.db.getNextHash(entry.hash); return { hash: entry.rhash(), @@ -2661,13 +2661,13 @@ RPC.prototype.headerToJSON = async function headerToJSON(entry) { }; RPC.prototype.blockToJSON = async function blockToJSON(entry, block, details) { - let mtp = await entry.getMedianTime(); - let next = await this.chain.db.getNextHash(entry.hash); - let txs = []; + const mtp = await entry.getMedianTime(); + const next = await this.chain.db.getNextHash(entry.hash); + const txs = []; - for (let tx of block.txs) { + for (const tx of block.txs) { if (details) { - let json = this.txToJSON(tx, entry); + const json = this.txToJSON(tx, entry); txs.push(json); continue; } @@ -2723,7 +2723,7 @@ RPC.prototype.entryToJSON = function entryToJSON(entry) { function swap32(data) { for (let i = 0; i < data.length; i += 4) { - let field = data.readUInt32LE(i, true); + const field = data.readUInt32LE(i, true); data.writeUInt32BE(field, i, true); } return data; diff --git a/lib/http/rpcbase.js b/lib/http/rpcbase.js index 23213a8a7..f618fa121 100644 --- a/lib/http/rpcbase.js +++ b/lib/http/rpcbase.js @@ -111,7 +111,7 @@ RPCBase.prototype.call = async function call(body, query) { array = false; } - for (let cmd of cmds) { + for (const cmd of cmds) { let result; if (!cmd || typeof cmd !== 'object') { @@ -245,10 +245,10 @@ RPCBase.prototype.call = async function call(body, query) { */ RPCBase.prototype.execute = async function execute(json, help) { - let func = this.calls[json.method]; + const func = this.calls[json.method]; if (!func) { - for (let mount of this.mounts) { + for (const mount of this.mounts) { if (mount.calls[json.method]) return await mount.execute(json, help); } diff --git a/lib/http/rpcclient.js b/lib/http/rpcclient.js index 9abc8f742..c7fd5302e 100644 --- a/lib/http/rpcclient.js +++ b/lib/http/rpcclient.js @@ -45,7 +45,7 @@ function RPCClient(options) { */ RPCClient.prototype.execute = async function execute(method, params) { - let res = await request({ + const res = await request({ method: 'POST', uri: this.uri, pool: true, diff --git a/lib/http/server.js b/lib/http/server.js index a5c7d0975..ba48e2e8c 100644 --- a/lib/http/server.js +++ b/lib/http/server.js @@ -102,8 +102,8 @@ HTTPServer.prototype.initRouter = function initRouter() { this.use(this.jsonRPC(this.rpc)); this.get('/', async (req, res) => { - let totalTX = this.mempool ? this.mempool.map.size : 0; - let size = this.mempool ? this.mempool.getSize() : 0; + const totalTX = this.mempool ? this.mempool.map.size : 0; + const size = this.mempool ? this.mempool.getSize() : 0; let addr = this.pool.hosts.getLocal(); if (!addr) @@ -141,9 +141,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // UTXO by address this.get('/coin/address/:address', async (req, res) => { - let valid = req.valid(); - let address = valid.str('address'); - let result = []; + const valid = req.valid(); + const address = valid.str('address'); + const result = []; let coins; enforce(address, 'Address is required.'); @@ -151,7 +151,7 @@ HTTPServer.prototype.initRouter = function initRouter() { coins = await this.node.getCoinsByAddress(address); - for (let coin of coins) + for (const coin of coins) result.push(coin.getJSON(this.network)); res.send(200, result); @@ -159,9 +159,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // UTXO by id this.get('/coin/:hash/:index', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); - let index = valid.u32('index'); + const valid = req.valid(); + const hash = valid.hash('hash'); + const index = valid.u32('index'); let coin; enforce(hash, 'Hash is required.'); @@ -180,9 +180,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Bulk read UTXOs this.post('/coin/address', async (req, res) => { - let valid = req.valid(); - let address = valid.array('addresses'); - let result = []; + const valid = req.valid(); + const address = valid.array('addresses'); + const result = []; let coins; enforce(address, 'Address is required.'); @@ -190,7 +190,7 @@ HTTPServer.prototype.initRouter = function initRouter() { coins = await this.node.getCoinsByAddress(address); - for (let coin of coins) + for (const coin of coins) result.push(coin.getJSON(this.network)); res.send(200, result); @@ -198,8 +198,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // TX by hash this.get('/tx/:hash', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); + const valid = req.valid(); + const hash = valid.hash('hash'); let meta, view; enforce(hash, 'Hash is required.'); @@ -219,9 +219,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // TX by address this.get('/tx/address/:address', async (req, res) => { - let valid = req.valid(); - let address = valid.str('address'); - let result = []; + const valid = req.valid(); + const address = valid.str('address'); + const result = []; let metas; enforce(address, 'Address is required.'); @@ -229,8 +229,8 @@ HTTPServer.prototype.initRouter = function initRouter() { metas = await this.node.getMetaByAddress(address); - for (let meta of metas) { - let view = await this.node.getMetaView(meta); + for (const meta of metas) { + const view = await this.node.getMetaView(meta); result.push(meta.getJSON(this.network, view)); } @@ -239,9 +239,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Bulk read TXs this.post('/tx/address', async (req, res) => { - let valid = req.valid(); - let address = valid.array('address'); - let result = []; + const valid = req.valid(); + const address = valid.array('address'); + const result = []; let metas; enforce(address, 'Address is required.'); @@ -249,8 +249,8 @@ HTTPServer.prototype.initRouter = function initRouter() { metas = await this.node.getMetaByAddress(address); - for (let meta of metas) { - let view = await this.node.getMetaView(meta); + for (const meta of metas) { + const view = await this.node.getMetaView(meta); result.push(meta.getJSON(this.network, view)); } @@ -259,7 +259,7 @@ HTTPServer.prototype.initRouter = function initRouter() { // Block by hash/height this.get('/block/:block', async (req, res) => { - let valid = req.valid(); + const valid = req.valid(); let hash = valid.get('block'); let block, view, height; @@ -292,14 +292,14 @@ HTTPServer.prototype.initRouter = function initRouter() { // Mempool snapshot this.get('/mempool', async (req, res) => { - let result = []; + const result = []; let hashes; enforce(this.mempool, 'No mempool available.'); hashes = this.mempool.getSnapshot(); - for (let hash of hashes) + for (const hash of hashes) result.push(util.revHex(hash)); res.send(200, result); @@ -307,8 +307,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Broadcast TX this.post('/broadcast', async (req, res) => { - let valid = req.valid(); - let raw = valid.buf('tx'); + const valid = req.valid(); + const raw = valid.buf('tx'); let tx; enforce(raw, 'TX is required.'); @@ -322,8 +322,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Estimate fee this.get('/fee', async (req, res) => { - let valid = req.valid(); - let blocks = valid.u32('blocks'); + const valid = req.valid(); + const blocks = valid.u32('blocks'); let fee; if (!this.fees) { @@ -338,8 +338,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Reset chain this.post('/reset', async (req, res) => { - let valid = req.valid(); - let height = valid.u32('height'); + const valid = req.valid(); + const height = valid.u32('height'); enforce(height != null, 'Height is required.'); @@ -371,9 +371,9 @@ HTTPServer.prototype.initSockets = function initSockets() { HTTPServer.prototype.handleSocket = function handleSocket(socket) { socket.hook('auth', (args) => { - let valid = new Validator([args]); - let hash = this.options.apiHash; - let key = valid.str(0); + const valid = new Validator([args]); + const hash = this.options.apiHash; + const key = valid.str(0); if (socket.auth) throw new Error('Already authed.'); @@ -425,8 +425,8 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('set filter', (args) => { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); if (!data) throw new Error('Invalid parameter.'); @@ -441,8 +441,8 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('get entry', async (args) => { - let valid = new Validator([args]); - let block = valid.numhash(0); + const valid = new Validator([args]); + const block = valid.numhash(0); let entry; if (block == null) @@ -461,7 +461,7 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { socket.hook('add filter', (args) => { let valid = new Validator([args]); - let chunks = valid.array(0); + const chunks = valid.array(0); if (!chunks) throw new Error('Invalid parameter.'); @@ -472,7 +472,7 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { valid = new Validator([chunks]); for (let i = 0; i < chunks.length; i++) { - let data = valid.buf(i); + const data = valid.buf(i); if (!data) throw new Error('Bad data chunk.'); @@ -492,8 +492,8 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('estimate fee', (args) => { - let valid = new Validator([args]); - let blocks = valid.u32(0); + const valid = new Validator([args]); + const blocks = valid.u32(0); if (!this.fees) return this.network.feeRate; @@ -502,8 +502,8 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('send', (args) => { - let valid = new Validator([args]); - let data = valid.buf(0); + const valid = new Validator([args]); + const data = valid.buf(0); let tx; if (!data) @@ -517,8 +517,8 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('rescan', (args) => { - let valid = new Validator([args]); - let start = valid.numhash(0); + const valid = new Validator([args]); + const start = valid.numhash(0); if (start == null) throw new Error('Invalid parameter.'); @@ -535,10 +535,10 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { */ HTTPServer.prototype.bindChain = function bindChain() { - let pool = this.mempool || this.pool; + const pool = this.mempool || this.pool; this.chain.on('connect', (entry, block, view) => { - let list = this.channel('chain'); + const list = this.channel('chain'); let raw; if (!list) @@ -549,14 +549,14 @@ HTTPServer.prototype.bindChain = function bindChain() { this.to('chain', 'chain connect', raw); for (let item = list.head; item; item = item.next) { - let socket = item.value; - let txs = this.filterBlock(socket, block); + const socket = item.value; + const txs = this.filterBlock(socket, block); socket.emit('block connect', raw, txs); } }); this.chain.on('disconnect', (entry, block, view) => { - let list = this.channel('chain'); + const list = this.channel('chain'); let raw; if (!list) @@ -569,7 +569,7 @@ HTTPServer.prototype.bindChain = function bindChain() { }); this.chain.on('reset', (tip) => { - let list = this.channel('chain'); + const list = this.channel('chain'); let raw; if (!list) @@ -581,7 +581,7 @@ HTTPServer.prototype.bindChain = function bindChain() { }); pool.on('tx', (tx) => { - let list = this.channel('mempool'); + const list = this.channel('mempool'); let raw; if (!list) @@ -590,7 +590,7 @@ HTTPServer.prototype.bindChain = function bindChain() { raw = tx.toRaw(); for (let item = list.head; item; item = item.next) { - let socket = item.value; + const socket = item.value; if (!this.filterTX(socket, tx)) continue; @@ -609,12 +609,12 @@ HTTPServer.prototype.bindChain = function bindChain() { */ HTTPServer.prototype.filterBlock = function filterBlock(socket, block) { - let txs = []; + const txs = []; if (!socket.filter) return txs; - for (let tx of block.txs) { + for (const tx of block.txs) { if (this.filterTX(socket, tx)) txs.push(tx.toRaw()); } @@ -637,14 +637,14 @@ HTTPServer.prototype.filterTX = function filterTX(socket, tx) { return false; for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let hash = output.getHash(); + const output = tx.outputs[i]; + const hash = output.getHash(); if (!hash) continue; if (socket.filter.test(hash)) { - let prevout = Outpoint.fromTX(tx, i); + const prevout = Outpoint.fromTX(tx, i); socket.filter.add(prevout.toRaw()); found = true; } @@ -654,7 +654,7 @@ HTTPServer.prototype.filterTX = function filterTX(socket, tx) { return true; if (!tx.isCoinbase()) { - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { if (socket.filter.test(prevout.toRaw())) return true; } @@ -672,7 +672,7 @@ HTTPServer.prototype.filterTX = function filterTX(socket, tx) { */ HTTPServer.prototype.scan = async function scan(socket, start) { - let scanner = this.scanner.bind(this, socket); + const scanner = this.scanner.bind(this, socket); await this.node.scan(start, socket.filter, scanner); return null; }; @@ -687,10 +687,10 @@ HTTPServer.prototype.scan = async function scan(socket, start) { */ HTTPServer.prototype.scanner = function scanner(socket, entry, txs) { - let block = entry.toRaw(); - let raw = []; + const block = entry.toRaw(); + const raw = []; - for (let tx of txs) + for (const tx of txs) raw.push(tx.toRaw()); socket.emit('block rescan', block, raw); @@ -832,7 +832,7 @@ function hash256(data) { function enforce(value, msg) { if (!value) { - let err = new Error(msg); + const err = new Error(msg); err.statusCode = 400; throw err; } diff --git a/lib/http/wallet.js b/lib/http/wallet.js index fd0d910ad..6c7035d4a 100644 --- a/lib/http/wallet.js +++ b/lib/http/wallet.js @@ -348,7 +348,7 @@ HTTPWallet.prototype.setPassphrase = function setPassphrase(old, new_) { */ HTTPWallet.prototype.retoken = async function retoken(passphrase) { - let token = await this.client.retoken(this.id, passphrase); + const token = await this.client.retoken(this.id, passphrase); this.token = token; this.client.token = token; diff --git a/lib/mempool/fees.js b/lib/mempool/fees.js index 379e979d8..345d0f118 100644 --- a/lib/mempool/fees.js +++ b/lib/mempool/fees.js @@ -176,15 +176,15 @@ ConfirmStats.prototype.estimateMedian = function estimateMedian(target, needed, let conf = 0; let total = 0; let extra = 0; - let max = this.buckets.length - 1; - let start = greater ? max : 0; - let step = greater ? -1 : 1; + const max = this.buckets.length - 1; + const start = greater ? max : 0; + const step = greater ? -1 : 1; let near = start; let far = start; let bestNear = start; let bestFar = start; let found = false; - let bins = this.unconfTX.length; + const bins = this.unconfTX.length; let median = -1; let sum = 0; let minBucket, maxBucket; @@ -200,7 +200,7 @@ ConfirmStats.prototype.estimateMedian = function estimateMedian(target, needed, extra += this.oldUnconfTX[i]; if (total >= needed / (1 - this.decay)) { - let perc = conf / (total + extra); + const perc = conf / (total + extra); if (greater && perc < breakpoint) break; @@ -247,8 +247,8 @@ ConfirmStats.prototype.estimateMedian = function estimateMedian(target, needed, */ ConfirmStats.prototype.addTX = function addTX(height, val) { - let bucketIndex = this.bucketMap.search(val); - let blockIndex = height % this.unconfTX.length; + const bucketIndex = this.bucketMap.search(val); + const blockIndex = height % this.unconfTX.length; this.unconfTX[blockIndex][bucketIndex]++; this.logger.spam('Adding tx to %s.', this.type); return bucketIndex; @@ -280,7 +280,7 @@ ConfirmStats.prototype.removeTX = function removeTX(entryHeight, bestHeight, buc bucketIndex); } } else { - let blockIndex = entryHeight % this.unconfTX.length; + const blockIndex = entryHeight % this.unconfTX.length; if (this.unconfTX[blockIndex][bucketIndex] > 0) { this.unconfTX[blockIndex][bucketIndex]--; } else { @@ -318,8 +318,8 @@ ConfirmStats.prototype.getSize = function getSize() { */ ConfirmStats.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeDouble(this.decay); writeArray(bw, this.buckets); @@ -341,13 +341,13 @@ ConfirmStats.prototype.toRaw = function toRaw() { */ ConfirmStats.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let decay = br.readDouble(); - let buckets = readArray(br); - let avg = readArray(br); - let txAvg = readArray(br); - let maxConfirms = br.readVarint(); - let confAvg = new Array(maxConfirms); + const br = new BufferReader(data); + const decay = br.readDouble(); + const buckets = readArray(br); + const avg = readArray(br); + const txAvg = readArray(br); + const maxConfirms = br.readVarint(); + const confAvg = new Array(maxConfirms); for (let i = 0; i < maxConfirms; i++) confAvg[i] = readArray(br); @@ -448,10 +448,10 @@ PolicyEstimator.VERSION = 0; */ PolicyEstimator.prototype.init = function init() { - let minFee = this.minTrackedFee; - let minPri = this.minTrackedPri; - let fee = []; - let priority = []; + const minFee = this.minTrackedFee; + const minPri = this.minTrackedPri; + const fee = []; + const priority = []; for (let b = minFee; b <= MAX_FEERATE; b *= FEE_SPACING) fee.push(b); @@ -489,7 +489,7 @@ PolicyEstimator.prototype.reset = function reset() { */ PolicyEstimator.prototype.removeTX = function removeTX(hash) { - let item = this.map.get(hash); + const item = this.map.get(hash); if (!item) { this.logger.spam('Mempool tx %s not found.', util.revHex(hash)); @@ -538,8 +538,8 @@ PolicyEstimator.prototype.isPriPoint = function isPriPoint(fee, priority) { */ PolicyEstimator.prototype.processTX = function processTX(entry, current) { - let height = entry.height; - let hash = entry.hash('hex'); + const height = entry.height; + const hash = entry.hash('hex'); let fee, rate, priority, item; if (this.map.has(hash)) { @@ -671,7 +671,7 @@ PolicyEstimator.prototype.processBlock = function processBlock(height, entries, this.feeStats.clearCurrent(height); this.priStats.clearCurrent(height); - for (let entry of entries) + for (const entry of entries) this.processBlockTX(height, entry); this.feeStats.updateAverages(); @@ -790,8 +790,8 @@ PolicyEstimator.prototype.getSize = function getSize() { */ PolicyEstimator.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU8(PolicyEstimator.VERSION); bw.writeU32(this.bestHeight); @@ -808,7 +808,7 @@ PolicyEstimator.prototype.toRaw = function toRaw() { */ PolicyEstimator.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); if (br.readU8() !== PolicyEstimator.VERSION) throw new Error('Bad serialization version for estimator.'); @@ -867,12 +867,12 @@ function DoubleMap() { } DoubleMap.prototype.insert = function insert(key, value) { - let i = util.binarySearch(this.buckets, key, compare, true); + const i = util.binarySearch(this.buckets, key, compare, true); this.buckets.splice(i, 0, [key, value]); }; DoubleMap.prototype.search = function search(key) { - let i = util.binarySearch(this.buckets, key, compare, true); + const i = util.binarySearch(this.buckets, key, compare, true); assert(this.buckets.length !== 0, 'Cannot search.'); return this.buckets[i][1]; }; @@ -886,7 +886,7 @@ function compare(a, b) { } function sizeArray(buckets) { - let size = encoding.sizeVarint(buckets.length); + const size = encoding.sizeVarint(buckets.length); return size + buckets.length * 8; } @@ -898,7 +898,7 @@ function writeArray(bw, buckets) { } function readArray(br) { - let buckets = new Float64Array(br.readVarint()); + const buckets = new Float64Array(br.readVarint()); for (let i = 0; i < buckets.length; i++) buckets[i] = br.readDouble(); diff --git a/lib/mempool/layout.js b/lib/mempool/layout.js index 3fac1d642..916dae742 100644 --- a/lib/mempool/layout.js +++ b/lib/mempool/layout.js @@ -21,7 +21,7 @@ const layout = { V: Buffer.from([0x76]), F: Buffer.from([0x46]), e: function e(hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); key[0] = 0x65; write(key, hash, 1); return key; diff --git a/lib/mempool/mempool.js b/lib/mempool/mempool.js index 653afafb6..414004ce4 100644 --- a/lib/mempool/mempool.js +++ b/lib/mempool/mempool.js @@ -105,22 +105,22 @@ util.inherits(Mempool, AsyncObject); */ Mempool.prototype._open = async function open() { - let size = (this.options.maxSize / 1024).toFixed(2); + const size = (this.options.maxSize / 1024).toFixed(2); await this.chain.open(); await this.cache.open(); if (this.options.persistent) { - let entries = await this.cache.getEntries(); + const entries = await this.cache.getEntries(); - for (let entry of entries) + for (const entry of entries) this.trackEntry(entry); - for (let entry of entries) { + for (const entry of entries) { this.updateAncestors(entry, addFee); if (this.options.indexAddress) { - let view = await this.getCoinView(entry.tx); + const view = await this.getCoinView(entry.tx); this.indexEntry(entry, view); } } @@ -130,7 +130,7 @@ Mempool.prototype._open = async function open() { entries.length); if (this.fees) { - let fees = await this.cache.getFees(); + const fees = await this.cache.getFees(); if (fees) { this.fees.inject(fees); @@ -167,7 +167,7 @@ Mempool.prototype._close = async function close() { */ Mempool.prototype.addBlock = async function addBlock(block, txs) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._addBlock(block, txs); } finally { @@ -195,9 +195,9 @@ Mempool.prototype._addBlock = async function addBlock(block, txs) { entries = []; for (let i = txs.length - 1; i >= 1; i--) { - let tx = txs[i]; - let hash = tx.hash('hex'); - let entry = this.getEntry(hash); + const tx = txs[i]; + const hash = tx.hash('hex'); + const entry = this.getEntry(hash); if (!entry) { this.removeOrphan(hash); @@ -246,7 +246,7 @@ Mempool.prototype._addBlock = async function addBlock(block, txs) { */ Mempool.prototype.removeBlock = async function removeBlock(block, txs) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._removeBlock(block, txs); } finally { @@ -273,8 +273,8 @@ Mempool.prototype._removeBlock = async function removeBlock(block, txs) { } for (let i = 1; i < txs.length; i++) { - let tx = txs[i]; - let hash = tx.hash('hex'); + const tx = txs[i]; + const hash = tx.hash('hex'); if (this.hasEntry(hash)) continue; @@ -313,7 +313,7 @@ Mempool.prototype._removeBlock = async function removeBlock(block, txs) { */ Mempool.prototype.reset = async function reset() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._reset(); } finally { @@ -362,10 +362,10 @@ Mempool.prototype._reset = async function reset() { */ Mempool.prototype.limitSize = function limitSize(added) { - let maxSize = this.options.maxSize; - let threshold = maxSize - (maxSize / 10); - let expiryTime = this.options.expiryTime; - let now = util.now(); + const maxSize = this.options.maxSize; + const threshold = maxSize - (maxSize / 10); + const expiryTime = this.options.expiryTime; + const now = util.now(); let queue, start; if (this.size <= maxSize) @@ -374,7 +374,7 @@ Mempool.prototype.limitSize = function limitSize(added) { start = util.hrtime(); queue = new Heap(cmpRate); - for (let entry of this.map.values()) { + for (const entry of this.map.values()) { if (this.hasDepends(entry.tx)) continue; @@ -404,8 +404,8 @@ Mempool.prototype.limitSize = function limitSize(added) { queue.size()); while (queue.size() > 0) { - let entry = queue.shift(); - let hash = entry.hash('hex'); + const entry = queue.shift(); + const hash = entry.hash('hex'); assert(this.hasEntry(hash)); @@ -433,7 +433,7 @@ Mempool.prototype.limitSize = function limitSize(added) { */ Mempool.prototype.getTX = function getTX(hash) { - let entry = this.map.get(hash); + const entry = this.map.get(hash); if (!entry) return; return entry.tx; @@ -457,7 +457,7 @@ Mempool.prototype.getEntry = function getEntry(hash) { */ Mempool.prototype.getCoin = function getCoin(hash, index) { - let entry = this.map.get(hash); + const entry = this.map.get(hash); if (!entry) return; @@ -482,7 +482,7 @@ Mempool.prototype.getCoin = function getCoin(hash, index) { */ Mempool.prototype.isSpent = function isSpent(hash, index) { - let key = Outpoint.toKey(hash, index); + const key = Outpoint.toKey(hash, index); return this.spents.has(key); }; @@ -494,7 +494,7 @@ Mempool.prototype.isSpent = function isSpent(hash, index) { */ Mempool.prototype.getSpent = function getSpent(hash, index) { - let key = Outpoint.toKey(hash, index); + const key = Outpoint.toKey(hash, index); return this.spents.get(key); }; @@ -506,8 +506,8 @@ Mempool.prototype.getSpent = function getSpent(hash, index) { */ Mempool.prototype.getSpentTX = function getSpentTX(hash, index) { - let key = Outpoint.toKey(hash, index); - let entry = this.spents.get(key); + const key = Outpoint.toKey(hash, index); + const entry = this.spents.get(key); if (!entry) return; @@ -522,16 +522,16 @@ Mempool.prototype.getSpentTX = function getSpentTX(hash, index) { */ Mempool.prototype.getCoinsByAddress = function getCoinsByAddress(addrs) { - let out = []; + const out = []; if (!Array.isArray(addrs)) addrs = [addrs]; - for (let addr of addrs) { - let hash = Address.getHash(addr, 'hex'); - let coins = this.coinIndex.get(hash); + for (const addr of addrs) { + const hash = Address.getHash(addr, 'hex'); + const coins = this.coinIndex.get(hash); - for (let coin of coins) + for (const coin of coins) out.push(coin); } @@ -545,16 +545,16 @@ Mempool.prototype.getCoinsByAddress = function getCoinsByAddress(addrs) { */ Mempool.prototype.getTXByAddress = function getTXByAddress(addrs) { - let out = []; + const out = []; if (!Array.isArray(addrs)) addrs = [addrs]; - for (let addr of addrs) { - let hash = Address.getHash(addr, 'hex'); - let txs = this.txIndex.get(hash); + for (const addr of addrs) { + const hash = Address.getHash(addr, 'hex'); + const txs = this.txIndex.get(hash); - for (let tx of txs) + for (const tx of txs) out.push(tx); } @@ -568,16 +568,16 @@ Mempool.prototype.getTXByAddress = function getTXByAddress(addrs) { */ Mempool.prototype.getMetaByAddress = function getMetaByAddress(addrs) { - let out = []; + const out = []; if (!Array.isArray(addrs)) addrs = [addrs]; - for (let addr of addrs) { - let hash = Address.getHash(addr, 'hex'); - let txs = this.txIndex.getMeta(hash); + for (const addr of addrs) { + const hash = Address.getHash(addr, 'hex'); + const txs = this.txIndex.getMeta(hash); - for (let tx of txs) + for (const tx of txs) out.push(tx); } @@ -591,7 +591,7 @@ Mempool.prototype.getMetaByAddress = function getMetaByAddress(addrs) { */ Mempool.prototype.getMeta = function getMeta(hash) { - let entry = this.getEntry(hash); + const entry = this.getEntry(hash); let meta; if (!entry) @@ -670,8 +670,8 @@ Mempool.prototype.hasReject = function hasReject(hash) { */ Mempool.prototype.addTX = async function addTX(tx, id) { - let hash = tx.hash('hex'); - let unlock = await this.locker.lock(hash); + const hash = tx.hash('hex'); + const unlock = await this.locker.lock(hash); try { return await this._addTX(tx, id); } finally { @@ -722,9 +722,9 @@ Mempool.prototype._addTX = async function _addTX(tx, id) { */ Mempool.prototype.insertTX = async function insertTX(tx, id) { - let lockFlags = common.lockFlags.STANDARD_LOCKTIME_FLAGS; - let height = this.chain.height; - let hash = tx.hash('hex'); + const lockFlags = common.lockFlags.STANDARD_LOCKTIME_FLAGS; + const height = this.chain.height; + const hash = tx.hash('hex'); let valid, reason, score, entry, view, missing; assert(!tx.mutable, 'Cannot add mutable TX to mempool.'); @@ -769,7 +769,7 @@ Mempool.prototype.insertTX = async function insertTX(tx, id) { // Non-contextual standardness checks. if (this.options.requireStandard) { - let [valid, reason, score] = tx.checkStandard(); + const [valid, reason, score] = tx.checkStandard(); if (!valid) throw new VerifyError(tx, 'nonstandard', reason, score); @@ -862,10 +862,10 @@ Mempool.prototype.insertTX = async function insertTX(tx, id) { */ Mempool.prototype.verify = async function verify(entry, view) { - let height = this.chain.height + 1; - let lockFlags = common.lockFlags.STANDARD_LOCKTIME_FLAGS; + const height = this.chain.height + 1; + const lockFlags = common.lockFlags.STANDARD_LOCKTIME_FLAGS; let flags = Script.flags.STANDARD_VERIFY_FLAGS; - let tx = entry.tx; + const tx = entry.tx; let fee, reason, score, minFee; // Verify sequence locks. @@ -918,7 +918,7 @@ Mempool.prototype.verify = async function verify(entry, view) { // Continuously rate-limit free (really, very-low-fee) // transactions. This mitigates 'penny-flooding'. if (this.options.limitFree && entry.fee < minFee) { - let now = util.now(); + const now = util.now(); // Use an exponentially decaying ~10-minute window. this.freeCount *= Math.pow(1 - 1 / 600, now - this.lastTime); @@ -1061,7 +1061,7 @@ Mempool.prototype.verifyInputs = async function verifyInputs(tx, view, flags) { */ Mempool.prototype.addEntry = async function addEntry(entry, view) { - let tx = entry.tx; + const tx = entry.tx; this.trackEntry(entry, view); @@ -1090,8 +1090,8 @@ Mempool.prototype.addEntry = async function addEntry(entry, view) { */ Mempool.prototype.removeEntry = function removeEntry(entry) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); this.untrackEntry(entry); @@ -1122,11 +1122,11 @@ Mempool.prototype.evictEntry = function evictEntry(entry) { */ Mempool.prototype.removeSpenders = function removeSpenders(entry) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); for (let i = 0; i < tx.outputs.length; i++) { - let spender = this.getSpent(hash, i); + const spender = this.getSpent(hash, i); if (!spender) continue; @@ -1171,11 +1171,11 @@ Mempool.prototype.updateAncestors = function updateAncestors(entry, map) { */ Mempool.prototype._countAncestors = function countAncestors(entry, set, child, map) { - let tx = entry.tx; + const tx = entry.tx; - for (let input of tx.inputs) { - let hash = input.prevout.hash; - let parent = this.getEntry(hash); + for (const input of tx.inputs) { + const hash = input.prevout.hash; + const parent = this.getEntry(hash); if (!parent) continue; @@ -1220,11 +1220,11 @@ Mempool.prototype.countDescendants = function countDescendants(entry) { */ Mempool.prototype._countDescendants = function countDescendants(entry, set) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); for (let i = 0; i < tx.outputs.length; i++) { - let child = this.getSpent(hash, i); + const child = this.getSpent(hash, i); let next; if (!child) @@ -1263,11 +1263,11 @@ Mempool.prototype.getAncestors = function getAncestors(entry) { */ Mempool.prototype._getAncestors = function getAncestors(entry, entries, set) { - let tx = entry.tx; + const tx = entry.tx; - for (let input of tx.inputs) { - let hash = input.prevout.hash; - let parent = this.getEntry(hash); + for (const input of tx.inputs) { + const hash = input.prevout.hash; + const parent = this.getEntry(hash); if (!parent) continue; @@ -1303,11 +1303,11 @@ Mempool.prototype.getDescendants = function getDescendants(entry) { */ Mempool.prototype._getDescendants = function getDescendants(entry, entries, set) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); for (let i = 0; i < tx.outputs.length; i++) { - let child = this.getSpent(hash, i); + const child = this.getSpent(hash, i); let next; if (!child) @@ -1335,10 +1335,10 @@ Mempool.prototype._getDescendants = function getDescendants(entry, entries, set) */ Mempool.prototype.getDepends = function getDepends(tx) { - let prevout = tx.getPrevout(); - let depends = []; + const prevout = tx.getPrevout(); + const depends = []; - for (let hash of prevout) { + for (const hash of prevout) { if (this.hasEntry(hash)) depends.push(hash); } @@ -1353,8 +1353,8 @@ Mempool.prototype.getDepends = function getDepends(tx) { */ Mempool.prototype.hasDepends = function hasDepends(tx) { - for (let input of tx.inputs) { - let hash = input.prevout.hash; + for (const input of tx.inputs) { + const hash = input.prevout.hash; if (this.hasEntry(hash)) return true; } @@ -1370,10 +1370,10 @@ Mempool.prototype.hasDepends = function hasDepends(tx) { Mempool.prototype.getBalance = function getBalance() { let total = 0; - for (let [hash, entry] of this.map) { - let tx = entry.tx; + for (const [hash, entry] of this.map) { + const tx = entry.tx; for (let i = 0; i < tx.outputs.length; i++) { - let coin = this.getCoin(hash, i); + const coin = this.getCoin(hash, i); if (coin) total += coin.value; } @@ -1388,9 +1388,9 @@ Mempool.prototype.getBalance = function getBalance() { */ Mempool.prototype.getHistory = function getHistory() { - let txs = []; + const txs = []; - for (let entry of this.map.values()) + for (const entry of this.map.values()) txs.push(entry.tx); return txs; @@ -1423,7 +1423,7 @@ Mempool.prototype.hasOrphan = function hasOrphan(hash) { */ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { - let hash = tx.hash('hex'); + const hash = tx.hash('hex'); if (tx.getWeight() > policy.MAX_TX_WEIGHT) { this.logger.debug('Ignoring large orphan: %s', tx.txid()); @@ -1432,7 +1432,7 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { return []; } - for (let prev of missing) { + for (const prev of missing) { if (this.hasReject(prev)) { this.logger.debug('Not storing orphan %s (rejected parents).', tx.txid()); this.rejects.add(tx.hash()); @@ -1445,7 +1445,7 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { this.limitOrphans(); - for (let prev of missing) { + for (const prev of missing) { if (!this.waiting.has(prev)) this.waiting.set(prev, new Set()); @@ -1469,9 +1469,9 @@ Mempool.prototype.storeOrphan = function storeOrphan(tx, missing, id) { */ Mempool.prototype.handleOrphans = async function handleOrphans(parent) { - let resolved = this.resolveOrphans(parent); + const resolved = this.resolveOrphans(parent); - for (let orphan of resolved) { + for (const orphan of resolved) { let tx, missing; try { @@ -1517,17 +1517,17 @@ Mempool.prototype.handleOrphans = async function handleOrphans(parent) { */ Mempool.prototype.resolveOrphans = function resolveOrphans(parent) { - let hash = parent.hash('hex'); - let set = this.waiting.get(hash); - let resolved = []; + const hash = parent.hash('hex'); + const set = this.waiting.get(hash); + const resolved = []; if (!set) return resolved; assert(set.size > 0); - for (let orphanHash of set.keys()) { - let orphan = this.getOrphan(orphanHash); + for (const orphanHash of set.keys()) { + const orphan = this.getOrphan(orphanHash); assert(orphan); @@ -1549,7 +1549,7 @@ Mempool.prototype.resolveOrphans = function resolveOrphans(parent) { */ Mempool.prototype.removeOrphan = function removeOrphan(hash) { - let orphan = this.getOrphan(hash); + const orphan = this.getOrphan(hash); let tx; if (!orphan) @@ -1565,8 +1565,8 @@ Mempool.prototype.removeOrphan = function removeOrphan(hash) { return; } - for (let prev of tx.getPrevout()) { - let set = this.waiting.get(prev); + for (const prev of tx.getPrevout()) { + const set = this.waiting.get(prev); if (!set) continue; @@ -1623,8 +1623,8 @@ Mempool.prototype.limitOrphans = function limitOrphans() { */ Mempool.prototype.isDoubleSpend = function isDoubleSpend(tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; + for (const input of tx.inputs) { + const prevout = input.prevout; if (this.isSpent(prevout.hash, prevout.index)) return true; } @@ -1640,7 +1640,7 @@ Mempool.prototype.isDoubleSpend = function isDoubleSpend(tx) { */ Mempool.prototype.getSpentView = async function getSpentView(tx) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this.getCoinView(tx); } finally { @@ -1656,10 +1656,10 @@ Mempool.prototype.getSpentView = async function getSpentView(tx) { */ Mempool.prototype.getCoinView = async function getCoinView(tx) { - let view = new CoinView(); + const view = new CoinView(); - for (let {prevout} of tx.inputs) { - let entry = this.getEntry(prevout.hash); + for (const {prevout} of tx.inputs) { + const entry = this.getEntry(prevout.hash); let coin; if (entry) { @@ -1670,7 +1670,7 @@ Mempool.prototype.getCoinView = async function getCoinView(tx) { coin = await this.chain.db.readCoin(prevout); if (!coin) { - let coins = new Coins(); + const coins = new Coins(); view.add(prevout.hash, coins); continue; } @@ -1689,9 +1689,9 @@ Mempool.prototype.getCoinView = async function getCoinView(tx) { */ Mempool.prototype.findMissing = function findMissing(tx, view) { - let missing = []; + const missing = []; - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { if (view.hasEntry(prevout)) continue; @@ -1711,9 +1711,9 @@ Mempool.prototype.findMissing = function findMissing(tx, view) { */ Mempool.prototype.getSnapshot = function getSnapshot() { - let keys = []; + const keys = []; - for (let hash of this.map.keys()) + for (const hash of this.map.keys()) keys.push(hash); return keys; @@ -1750,16 +1750,16 @@ Mempool.prototype.verifyFinal = function verifyFinal(tx, flags) { */ Mempool.prototype.trackEntry = function trackEntry(entry, view) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); assert(!this.map.has(hash)); this.map.set(hash, entry); assert(!tx.isCoinbase()); - for (let input of tx.inputs) { - let key = input.prevout.toKey(); + for (const input of tx.inputs) { + const key = input.prevout.toKey(); this.spents.set(key, entry); } @@ -1776,16 +1776,16 @@ Mempool.prototype.trackEntry = function trackEntry(entry, view) { */ Mempool.prototype.untrackEntry = function untrackEntry(entry) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); assert(this.map.has(hash)); this.map.delete(hash); assert(!tx.isCoinbase()); - for (let input of tx.inputs) { - let key = input.prevout.toKey(); + for (const input of tx.inputs) { + const key = input.prevout.toKey(); this.spents.delete(key); } @@ -1803,12 +1803,12 @@ Mempool.prototype.untrackEntry = function untrackEntry(entry) { */ Mempool.prototype.indexEntry = function indexEntry(entry, view) { - let tx = entry.tx; + const tx = entry.tx; this.txIndex.insert(entry, view); - for (let input of tx.inputs) { - let prev = input.prevout; + for (const input of tx.inputs) { + const prev = input.prevout; this.coinIndex.remove(prev.hash, prev.index); } @@ -1823,14 +1823,14 @@ Mempool.prototype.indexEntry = function indexEntry(entry, view) { */ Mempool.prototype.unindexEntry = function unindexEntry(entry) { - let tx = entry.tx; - let hash = tx.hash('hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); this.txIndex.remove(hash); - for (let input of tx.inputs) { - let prevout = input.prevout.hash; - let prev = this.getTX(prevout.hash); + for (const input of tx.inputs) { + const prevout = input.prevout.hash; + const prev = this.getTX(prevout.hash); if (!prev) continue; @@ -1850,9 +1850,9 @@ Mempool.prototype.unindexEntry = function unindexEntry(entry) { */ Mempool.prototype.removeDoubleSpends = function removeDoubleSpends(tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; - let spent = this.getSpent(prevout.hash, prevout.index); + for (const input of tx.inputs) { + const prevout = input.prevout; + const spent = this.getSpent(prevout.hash, prevout.index); if (!spent) continue; @@ -2123,27 +2123,27 @@ TXIndex.prototype.reset = function reset() { }; TXIndex.prototype.get = function get(addr) { - let items = this.index.get(addr); - let out = []; + const items = this.index.get(addr); + const out = []; if (!items) return out; - for (let entry of items.values()) + for (const entry of items.values()) out.push(entry.tx); return out; }; TXIndex.prototype.getMeta = function getMeta(addr) { - let items = this.index.get(addr); - let out = []; + const items = this.index.get(addr); + const out = []; if (!items) return out; - for (let entry of items.values()) { - let meta = TXMeta.fromTX(entry.tx); + for (const entry of items.values()) { + const meta = TXMeta.fromTX(entry.tx); meta.mtime = entry.time; out.push(meta); } @@ -2152,14 +2152,14 @@ TXIndex.prototype.getMeta = function getMeta(addr) { }; TXIndex.prototype.insert = function insert(entry, view) { - let tx = entry.tx; - let hash = tx.hash('hex'); - let addrs = tx.getHashes(view, 'hex'); + const tx = entry.tx; + const hash = tx.hash('hex'); + const addrs = tx.getHashes(view, 'hex'); if (addrs.length === 0) return; - for (let addr of addrs) { + for (const addr of addrs) { let items = this.index.get(addr); if (!items) { @@ -2175,13 +2175,13 @@ TXIndex.prototype.insert = function insert(entry, view) { }; TXIndex.prototype.remove = function remove(hash) { - let addrs = this.map.get(hash); + const addrs = this.map.get(hash); if (!addrs) return; - for (let addr of addrs) { - let items = this.index.get(addr); + for (const addr of addrs) { + const items = this.index.get(addr); assert(items); assert(items.has(hash)); @@ -2215,22 +2215,22 @@ CoinIndex.prototype.reset = function reset() { }; CoinIndex.prototype.get = function get(addr) { - let items = this.index.get(addr); - let out = []; + const items = this.index.get(addr); + const out = []; if (!items) return out; - for (let coin of items.values()) + for (const coin of items.values()) out.push(coin.toCoin()); return out; }; CoinIndex.prototype.insert = function insert(tx, index) { - let output = tx.outputs[index]; - let hash = tx.hash('hex'); - let addr = output.getHash('hex'); + const output = tx.outputs[index]; + const hash = tx.hash('hex'); + const addr = output.getHash('hex'); let items, key; if (!addr) @@ -2252,8 +2252,8 @@ CoinIndex.prototype.insert = function insert(tx, index) { }; CoinIndex.prototype.remove = function remove(hash, index) { - let key = Outpoint.toKey(hash, index); - let addr = this.map.get(key); + const key = Outpoint.toKey(hash, index); + const addr = this.map.get(key); let items; if (!addr) @@ -2331,7 +2331,7 @@ function MempoolCache(options) { MempoolCache.VERSION = 2; MempoolCache.prototype.getVersion = async function getVersion() { - let data = await this.db.get(layout.V); + const data = await this.db.get(layout.V); if (!data) return -1; @@ -2340,7 +2340,7 @@ MempoolCache.prototype.getVersion = async function getVersion() { }; MempoolCache.prototype.getTip = async function getTip() { - let hash = await this.db.get(layout.R); + const hash = await this.db.get(layout.R); if (!hash) return; @@ -2349,7 +2349,7 @@ MempoolCache.prototype.getTip = async function getTip() { }; MempoolCache.prototype.getFees = async function getFees() { - let data = await this.db.get(layout.F); + const data = await this.db.get(layout.F); let fees; if (!data) @@ -2443,7 +2443,7 @@ MempoolCache.prototype.flush = async function flush() { }; MempoolCache.prototype.init = async function init(hash) { - let batch = this.db.batch(); + const batch = this.db.batch(); batch.put(layout.V, encoding.U32(MempoolCache.VERSION)); batch.put(layout.R, Buffer.from(hash, 'hex')); await batch.write(); @@ -2490,10 +2490,10 @@ MempoolCache.prototype.verify = async function verify() { }; MempoolCache.prototype.wipe = async function wipe() { - let batch = this.db.batch(); - let keys = await this.getKeys(); + const batch = this.db.batch(); + const keys = await this.getKeys(); - for (let key of keys) + for (const key of keys) batch.del(key); batch.put(layout.V, encoding.U32(MempoolCache.VERSION)); @@ -2560,8 +2560,8 @@ function cmpRate(a, b) { } function useDesc(a) { - let x = a.deltaFee * a.descSize; - let y = a.descFee * a.size; + const x = a.deltaFee * a.descSize; + const y = a.descFee * a.size; return y > x; } diff --git a/lib/mempool/mempoolentry.js b/lib/mempool/mempoolentry.js index b1a866b07..1416c009f 100644 --- a/lib/mempool/mempoolentry.js +++ b/lib/mempool/mempoolentry.js @@ -91,15 +91,15 @@ MempoolEntry.fromOptions = function fromOptions(options) { */ MempoolEntry.prototype.fromTX = function fromTX(tx, view, height) { - let flags = Script.flags.STANDARD_VERIFY_FLAGS; - let value = tx.getChainValue(view); - let sigops = tx.getSigopsCost(view, flags); - let size = tx.getSigopsSize(sigops); - let priority = tx.getPriority(view, height, size); - let fee = tx.getFee(view); + const flags = Script.flags.STANDARD_VERIFY_FLAGS; + const value = tx.getChainValue(view); + const sigops = tx.getSigopsCost(view, flags); + const size = tx.getSigopsSize(sigops); + const priority = tx.getPriority(view, height, size); + const fee = tx.getFee(view); let dependencies = false; - for (let {prevout} of tx.inputs) { + for (const {prevout} of tx.inputs) { if (view.getHeight(prevout) === -1) { dependencies = true; break; @@ -161,8 +161,8 @@ MempoolEntry.prototype.txid = function txid() { */ MempoolEntry.prototype.getPriority = function getPriority(height) { - let delta = height - this.height; - let priority = (delta * this.value) / this.size; + const delta = height - this.height; + const priority = (delta * this.value) / this.size; let result = this.priority + Math.floor(priority); if (result < 0) result = 0; @@ -225,7 +225,7 @@ MempoolEntry.prototype.getDescRate = function getDescRate() { */ MempoolEntry.prototype.memUsage = function memUsage() { - let tx = this.tx; + const tx = this.tx; let total = 0; total += 176; // mempool entry @@ -240,7 +240,7 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // input array - for (let input of tx.inputs) { + for (const input of tx.inputs) { total += 120; // input total += 104; // prevout total += 88; // prevout hash @@ -250,7 +250,7 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // script code array total += input.script.code.length * 40; // opcodes - for (let op of input.script.code) { + for (const op of input.script.code) { if (op.data) total += 80; // op buffers } @@ -262,14 +262,14 @@ MempoolEntry.prototype.memUsage = function memUsage() { total += 32; // output array - for (let output of tx.outputs) { + for (const 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 (let op of output.script.code) { + for (const op of output.script.code) { if (op.data) total += 80; // op buffers } @@ -287,7 +287,7 @@ MempoolEntry.prototype.memUsage = function memUsage() { */ MempoolEntry.prototype.isFree = function isFree(height) { - let priority = this.getPriority(height); + const priority = this.getPriority(height); return priority > policy.FREE_THRESHOLD; }; @@ -306,7 +306,7 @@ MempoolEntry.prototype.getSize = function getSize() { */ MempoolEntry.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(this.getSize()); + const bw = new StaticWriter(this.getSize()); bw.writeBytes(this.tx.toRaw()); bw.writeU32(this.height); bw.writeU32(this.size); @@ -327,7 +327,7 @@ MempoolEntry.prototype.toRaw = function toRaw() { */ MempoolEntry.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.tx = TX.fromReader(br); this.height = br.readU32(); this.size = br.readU32(); diff --git a/lib/mining/common.js b/lib/mining/common.js index 90a82d03b..75105f919 100644 --- a/lib/mining/common.js +++ b/lib/mining/common.js @@ -34,7 +34,7 @@ const B0 = 0x1; common.swap32 = function swap32(data) { for (let i = 0; i < data.length; i += 4) { - let field = data.readUInt32LE(i, true); + const field = data.readUInt32LE(i, true); data.writeUInt32BE(field, i, true); } @@ -48,7 +48,7 @@ common.swap32 = function swap32(data) { */ common.swap32hex = function swap32hex(str) { - let data = Buffer.from(str, 'hex'); + const data = Buffer.from(str, 'hex'); return common.swap32(data).toString('hex'); }; @@ -111,8 +111,8 @@ common.double256 = function double256(target) { */ common.getDifficulty = function getDifficulty(target) { - let d = DIFF; - let n = common.double256(target); + const d = DIFF; + const n = common.double256(target); if (n === 0) return d; @@ -127,7 +127,7 @@ common.getDifficulty = function getDifficulty(target) { */ common.getTarget = function getTarget(bits) { - let target = consensus.fromCompact(bits); + const target = consensus.fromCompact(bits); if (target.isNeg()) throw new Error('Target is negative.'); @@ -145,7 +145,7 @@ common.getTarget = function getTarget(bits) { */ common.getBits = function getBits(data) { - let target = new BN(data, 'le'); + const target = new BN(data, 'le'); if (target.cmpn(0) === 0) throw new Error('Target is zero.'); diff --git a/lib/mining/cpuminer.js b/lib/mining/cpuminer.js index f953f0917..9fe6f1edb 100644 --- a/lib/mining/cpuminer.js +++ b/lib/mining/cpuminer.js @@ -193,7 +193,7 @@ CPUMiner.prototype._start = async function start() { */ CPUMiner.prototype.stop = async function stop() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._stop(); } finally { @@ -250,7 +250,7 @@ CPUMiner.prototype.wait = function wait() { */ CPUMiner.prototype.createJob = async function createJob(tip, address) { - let attempt = await this.miner.createBlock(tip, address); + const attempt = await this.miner.createBlock(tip, address); return new CPUJob(this, attempt); }; @@ -263,7 +263,7 @@ CPUMiner.prototype.createJob = async function createJob(tip, address) { */ CPUMiner.prototype.mineBlock = async function mineBlock(tip, address) { - let job = await this.createJob(tip, address); + const job = await this.createJob(tip, address); return await this.mineAsync(job); }; @@ -292,9 +292,9 @@ CPUMiner.prototype.notifyEntry = function notifyEntry() { */ CPUMiner.prototype.findNonce = function findNonce(job) { - let data = job.getHeader(); - let target = job.attempt.target; - let interval = CPUMiner.INTERVAL; + const data = job.getHeader(); + const target = job.attempt.target; + const interval = CPUMiner.INTERVAL; let min = 0; let max = interval; let nonce; @@ -322,9 +322,9 @@ CPUMiner.prototype.findNonce = function findNonce(job) { */ CPUMiner.prototype.findNonceAsync = async function findNonceAsync(job) { - let data = job.getHeader(); - let target = job.attempt.target; - let interval = CPUMiner.INTERVAL; + const data = job.getHeader(); + const target = job.attempt.target; + const interval = CPUMiner.INTERVAL; let min = 0; let max = interval; let nonce; @@ -411,10 +411,10 @@ CPUMiner.prototype.mineAsync = async function mineAsync(job) { */ CPUMiner.prototype.sendStatus = function sendStatus(job, nonce) { - let attempt = job.attempt; - let tip = util.revHex(attempt.prevBlock); - let hashes = job.getHashes(nonce); - let hashrate = job.getRate(nonce); + const attempt = job.attempt; + const tip = util.revHex(attempt.prevBlock); + const hashes = job.getHashes(nonce); + const hashrate = job.getRate(nonce); this.logger.info( 'Status: hashrate=%dkhs hashes=%d target=%d height=%d tip=%s', @@ -453,12 +453,12 @@ function CPUJob(miner, attempt) { */ CPUJob.prototype.getHeader = function getHeader() { - let attempt = this.attempt; - let n1 = this.nonce1; - let n2 = this.nonce2; - let time = attempt.time; - let root = attempt.getRoot(n1, n2); - let data = attempt.getHeader(root, time, 0); + const attempt = this.attempt; + const n1 = this.nonce1; + const n2 = this.nonce2; + const time = attempt.time; + const root = attempt.getRoot(n1, n2); + const data = attempt.getHeader(root, time, 0); return data; }; @@ -469,10 +469,10 @@ CPUJob.prototype.getHeader = function getHeader() { */ CPUJob.prototype.commit = function commit(nonce) { - let attempt = this.attempt; - let n1 = this.nonce1; - let n2 = this.nonce2; - let time = attempt.time; + const attempt = this.attempt; + const n1 = this.nonce1; + const n2 = this.nonce2; + const time = attempt.time; let proof; assert(!this.committed, 'Job already committed.'); @@ -536,7 +536,7 @@ CPUJob.prototype.destroy = function destroy() { */ CPUJob.prototype.getHashes = function getHashes(nonce) { - let extra = this.nonce1 * 0x100000000 + this.nonce2; + const extra = this.nonce1 * 0x100000000 + this.nonce2; return extra * 0xffffffff + nonce; }; @@ -547,8 +547,8 @@ CPUJob.prototype.getHashes = function getHashes(nonce) { */ CPUJob.prototype.getRate = function getRate(nonce) { - let hashes = this.getHashes(nonce); - let seconds = util.now() - this.start; + const hashes = this.getHashes(nonce); + const seconds = util.now() - this.start; return Math.floor(hashes / seconds); }; diff --git a/lib/mining/miner.js b/lib/mining/miner.js index 5d60cd343..6875838a9 100644 --- a/lib/mining/miner.js +++ b/lib/mining/miner.js @@ -103,7 +103,7 @@ Miner.prototype._close = async function close() { */ Miner.prototype.createBlock = async function createBlock(tip, address) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._createBlock(tip, address); } finally { @@ -172,7 +172,7 @@ Miner.prototype._createBlock = async function createBlock(tip, address) { attempt.getDifficulty()); if (this.options.preverify) { - let block = attempt.toBlock(); + const block = attempt.toBlock(); try { await this.chain._verifyBlock(block); @@ -255,8 +255,8 @@ Miner.prototype.getAddress = function getAddress() { Miner.prototype.assemble = function assemble(attempt) { let priority = this.options.priorityWeight > 0; - let queue = new Heap(cmpRate); - let depMap = new Map(); + const queue = new Heap(cmpRate); + const depMap = new Map(); if (priority) queue.set(cmpPriority); @@ -269,15 +269,15 @@ Miner.prototype.assemble = function assemble(attempt) { assert(this.mempool.tip === this.chain.tip.hash, 'Mempool/chain tip mismatch! Unsafe to create block.'); - for (let entry of this.mempool.map.values()) { - let item = BlockEntry.fromEntry(entry, attempt); - let tx = item.tx; + for (const entry of this.mempool.map.values()) { + const item = BlockEntry.fromEntry(entry, attempt); + const tx = item.tx; if (tx.isCoinbase()) throw new Error('Cannot add coinbase to block.'); - for (let {prevout} of tx.inputs) { - let hash = prevout.hash; + for (const {prevout} of tx.inputs) { + const hash = prevout.hash; if (!this.mempool.hasEntry(hash)) continue; @@ -297,9 +297,9 @@ Miner.prototype.assemble = function assemble(attempt) { } while (queue.size() > 0) { - let item = queue.shift(); - let tx = item.tx; - let hash = item.hash; + const item = queue.shift(); + const tx = item.tx; + const hash = item.hash; let weight = attempt.weight; let sigops = attempt.sigops; let deps; @@ -344,7 +344,7 @@ Miner.prototype.assemble = function assemble(attempt) { if (!deps) continue; - for (let item of deps) { + for (const item of deps) { if (--item.depCount === 0) queue.insert(item); } @@ -356,7 +356,7 @@ Miner.prototype.assemble = function assemble(attempt) { 'Block exceeds reserved weight!'); if (this.options.preverify) { - let block = attempt.toBlock(); + const block = attempt.toBlock(); assert(block.getWeight() <= attempt.weight, 'Block exceeds reserved weight!'); @@ -438,7 +438,7 @@ MinerOptions.prototype.fromOptions = function fromOptions(options) { if (options.address) { if (Array.isArray(options.address)) { - for (let item of options.address) + for (const item of options.address) this.addresses.push(new Address(item)); } else { this.addresses.push(new Address(options.address)); @@ -447,7 +447,7 @@ MinerOptions.prototype.fromOptions = function fromOptions(options) { if (options.addresses) { assert(Array.isArray(options.addresses)); - for (let item of options.addresses) + for (const item of options.addresses) this.addresses.push(new Address(item)); } diff --git a/lib/mining/template.js b/lib/mining/template.js index 395354779..433b998d4 100644 --- a/lib/mining/template.js +++ b/lib/mining/template.js @@ -171,13 +171,13 @@ BlockTemplate.fromOptions = function fromOptions(options) { */ BlockTemplate.prototype.getWitnessHash = function getWitnessHash() { - let nonce = encoding.ZERO_HASH; - let leaves = []; + const nonce = encoding.ZERO_HASH; + const leaves = []; let root, malleated; leaves.push(encoding.ZERO_HASH); - for (let item of this.items) + for (const item of this.items) leaves.push(item.tx.witnessHash()); [root, malleated] = merkle.createRoot(leaves); @@ -224,7 +224,7 @@ BlockTemplate.prototype.setTarget = function setTarget(target) { */ BlockTemplate.prototype.getReward = function getReward() { - let reward = consensus.getReward(this.height, this.interval); + const reward = consensus.getReward(this.height, this.interval); return reward + this.fees; }; @@ -235,8 +235,8 @@ BlockTemplate.prototype.getReward = function getReward() { */ BlockTemplate.prototype.createCoinbase = function createCoinbase(hash) { - let scale = consensus.WITNESS_SCALE_FACTOR; - let cb = new TX(); + const scale = consensus.WITNESS_SCALE_FACTOR; + const cb = new TX(); let padding = 0; let input, output, commit; @@ -328,9 +328,9 @@ BlockTemplate.prototype.createCoinbase = function createCoinbase(hash) { */ BlockTemplate.prototype.refresh = function refresh() { - let hash = this.getWitnessHash(); - let cb = this.createCoinbase(hash); - let raw = cb.toNormal(); + const hash = this.getWitnessHash(); + const cb = this.createCoinbase(hash); + const raw = cb.toNormal(); let size = 0; let left, right; @@ -385,8 +385,8 @@ BlockTemplate.prototype.getRawCoinbase = function getRawCoinbase(nonce1, nonce2) */ BlockTemplate.prototype.getRoot = function getRoot(nonce1, nonce2) { - let raw = this.getRawCoinbase(nonce1, nonce2); - let hash = digest.hash256(raw); + const raw = this.getRawCoinbase(nonce1, nonce2); + const hash = digest.hash256(raw); return this.tree.withFirst(hash); }; @@ -399,7 +399,7 @@ BlockTemplate.prototype.getRoot = function getRoot(nonce1, nonce2) { */ BlockTemplate.prototype.getHeader = function getHeader(root, time, nonce) { - let bw = new StaticWriter(80); + const bw = new StaticWriter(80); bw.writeU32(this.version); bw.writeHash(this.prevBlock); @@ -421,9 +421,9 @@ BlockTemplate.prototype.getHeader = function getHeader(root, time, nonce) { */ BlockTemplate.prototype.getProof = function getProof(nonce1, nonce2, time, nonce) { - let root = this.getRoot(nonce1, nonce2); - let data = this.getHeader(root, time, nonce); - let hash = digest.hash256(data); + const root = this.getRoot(nonce1, nonce2); + const data = this.getHeader(root, time, nonce); + const hash = digest.hash256(data); return new BlockProof(hash, root, nonce1, nonce2, time, nonce); }; @@ -435,8 +435,8 @@ BlockTemplate.prototype.getProof = function getProof(nonce1, nonce2, time, nonce */ BlockTemplate.prototype.getCoinbase = function getCoinbase(nonce1, nonce2) { - let raw = this.getRawCoinbase(nonce1, nonce2); - let tx = TX.fromRaw(raw); + const raw = this.getRawCoinbase(nonce1, nonce2); + const tx = TX.fromRaw(raw); let input; if (this.witness) { @@ -456,12 +456,12 @@ BlockTemplate.prototype.getCoinbase = function getCoinbase(nonce1, nonce2) { */ BlockTemplate.prototype.commit = function commit(proof) { - let root = proof.root; - let n1 = proof.nonce1; - let n2 = proof.nonce2; - let time = proof.time; - let nonce = proof.nonce; - let block = new Block(); + const root = proof.root; + const n1 = proof.nonce1; + const n2 = proof.nonce2; + const time = proof.time; + const nonce = proof.nonce; + const block = new Block(); let tx; block.version = this.version; @@ -475,7 +475,7 @@ BlockTemplate.prototype.commit = function commit(proof) { block.txs.push(tx); - for (let item of this.items) + for (const item of this.items) block.txs.push(item.tx); return block; @@ -498,7 +498,7 @@ BlockTemplate.prototype.toCoinbase = function toCoinbase() { */ BlockTemplate.prototype.toBlock = function toBlock() { - let proof = this.getProof(0, 0, this.time, 0); + const proof = this.getProof(0, 0, this.time, 0); return this.commit(proof); }; @@ -624,7 +624,7 @@ function BlockEntry(tx) { */ BlockEntry.fromTX = function fromTX(tx, view, attempt) { - let item = new BlockEntry(tx); + const item = new BlockEntry(tx); item.fee = tx.getFee(view); item.rate = tx.getRate(view); item.priority = tx.getPriority(view, attempt.height); @@ -642,7 +642,7 @@ BlockEntry.fromTX = function fromTX(tx, view, attempt) { */ BlockEntry.fromEntry = function fromEntry(entry, attempt) { - let item = new BlockEntry(entry.tx); + const item = new BlockEntry(entry.tx); item.fee = entry.getFee(); item.rate = entry.getDeltaRate(); item.priority = entry.getPriority(attempt.height); @@ -695,26 +695,26 @@ function MerkleTree() { } MerkleTree.prototype.withFirst = function withFirst(hash) { - for (let step of this.steps) + for (const step of this.steps) hash = digest.root256(hash, step); return hash; }; MerkleTree.prototype.toJSON = function toJSON() { - let steps = []; + const steps = []; - for (let step of this.steps) + for (const step of this.steps) steps.push(step.toString('hex')); return steps; }; MerkleTree.prototype.fromItems = function fromItems(items) { - let leaves = []; + const leaves = []; leaves.push(encoding.ZERO_HASH); - for (let item of items) + for (const item of items) leaves.push(item.tx.hash()); return this.fromLeaves(leaves); @@ -725,12 +725,12 @@ MerkleTree.fromItems = function fromItems(items) { }; MerkleTree.prototype.fromBlock = function fromBlock(txs) { - let leaves = []; + const leaves = []; leaves.push(encoding.ZERO_HASH); for (let i = 1; i < txs.length; i++) { - let tx = txs[i]; + const tx = txs[i]; leaves.push(tx.hash()); } @@ -745,7 +745,7 @@ MerkleTree.prototype.fromLeaves = function fromLeaves(leaves) { let len = leaves.length; while (len > 1) { - let hashes = [encoding.ZERO_HASH]; + const hashes = [encoding.ZERO_HASH]; this.steps.push(leaves[1]); @@ -753,7 +753,7 @@ MerkleTree.prototype.fromLeaves = function fromLeaves(leaves) { leaves.push(leaves[len - 1]); for (let i = 2; i < len; i += 2) { - let hash = digest.root256(leaves[i], leaves[i + 1]); + const hash = digest.root256(leaves[i], leaves[i + 1]); hashes.push(hash); } diff --git a/lib/net/bip150.js b/lib/net/bip150.js index 7dac23821..e762eb76a 100644 --- a/lib/net/bip150.js +++ b/lib/net/bip150.js @@ -121,7 +121,7 @@ BIP150.prototype.isAuthed = function isAuthed() { */ BIP150.prototype.challenge = function challenge(hash) { - let type = this.outbound ? 'r' : 'i'; + const type = this.outbound ? 'r' : 'i'; let msg, sig; assert(this.bip151.handshake, 'No BIP151 handshake before challenge.'); @@ -156,7 +156,7 @@ BIP150.prototype.challenge = function challenge(hash) { */ BIP150.prototype.reply = function reply(data) { - let type = this.outbound ? 'i' : 'r'; + const type = this.outbound ? 'i' : 'r'; let sig, msg, result; assert(this.challengeSent, 'Unsolicited reply.'); @@ -254,7 +254,7 @@ BIP150.prototype.toChallenge = function toChallenge() { */ BIP150.prototype.rekey = function rekey(sid, key, req, res) { - let seed = Buffer.allocUnsafe(130); + const seed = Buffer.allocUnsafe(130); sid.copy(seed, 0); key.copy(seed, 32); req.copy(seed, 64); @@ -268,11 +268,11 @@ BIP150.prototype.rekey = function rekey(sid, key, req, res) { */ BIP150.prototype.rekeyInput = function rekeyInput() { - let stream = this.input; - let req = this.peerIdentity; - let res = this.publicKey; - let k1 = this.rekey(stream.sid, stream.k1, req, res); - let k2 = this.rekey(stream.sid, stream.k2, req, res); + const stream = this.input; + const req = this.peerIdentity; + const res = this.publicKey; + const k1 = this.rekey(stream.sid, stream.k1, req, res); + const k2 = this.rekey(stream.sid, stream.k2, req, res); stream.rekey(k1, k2); }; @@ -282,11 +282,11 @@ BIP150.prototype.rekeyInput = function rekeyInput() { */ BIP150.prototype.rekeyOutput = function rekeyOutput() { - let stream = this.output; - let req = this.publicKey; - let res = this.peerIdentity; - let k1 = this.rekey(stream.sid, stream.k1, req, res); - let k2 = this.rekey(stream.sid, stream.k2, req, res); + const stream = this.output; + const req = this.publicKey; + const res = this.peerIdentity; + const k1 = this.rekey(stream.sid, stream.k1, req, res); + const k2 = this.rekey(stream.sid, stream.k2, req, res); stream.rekey(k1, k2); }; @@ -299,7 +299,7 @@ BIP150.prototype.rekeyOutput = function rekeyOutput() { */ BIP150.prototype.hash = function hash(sid, ch, key) { - let data = Buffer.allocUnsafe(66); + const data = Buffer.allocUnsafe(66); sid.copy(data, 0); data[32] = ch.charCodeAt(0); key.copy(data, 33); @@ -318,8 +318,8 @@ BIP150.prototype.hash = function hash(sid, ch, key) { BIP150.prototype.findAuthorized = function findAuthorized(hash) { // Scary O(n) stuff. - for (let key of this.db.authorized) { - let msg = this.hash(this.output.sid, 'p', key); + for (const key of this.db.authorized) { + const msg = this.hash(this.output.sid, 'p', key); // XXX Do we really need a constant // time compare here? Do it just to @@ -348,7 +348,7 @@ BIP150.prototype.destroy = function destroy() { */ BIP150.prototype.cleanup = function cleanup(err) { - let job = this.job; + const job = this.job; assert(!this.completed, 'Already completed.'); assert(job, 'No completion job.'); @@ -376,7 +376,7 @@ BIP150.prototype.cleanup = function cleanup(err) { */ BIP150.prototype.resolve = function resolve(result) { - let job = this.cleanup(); + const job = this.cleanup(); job.resolve(result); }; @@ -387,7 +387,7 @@ BIP150.prototype.resolve = function resolve(result) { */ BIP150.prototype.reject = function reject(err) { - let job = this.cleanup(); + const job = this.cleanup(); job.reject(err); }; @@ -447,7 +447,7 @@ BIP150.prototype.getAddress = function getAddress() { */ BIP150.address = function address(key) { - let bw = new StaticWriter(27); + const bw = new StaticWriter(27); bw.writeU8(0x0f); bw.writeU16BE(0xff01); bw.writeBytes(digest.hash160(key)); @@ -578,8 +578,8 @@ AuthDB.prototype.addAuthorized = function addAuthorized(key) { AuthDB.prototype.setKnown = function setKnown(map) { this.known.clear(); - for (let host of Object.keys(map)) { - let key = map[host]; + for (const host of Object.keys(map)) { + const key = map[host]; this.addKnown(host, key); } }; @@ -592,7 +592,7 @@ AuthDB.prototype.setKnown = function setKnown(map) { AuthDB.prototype.setAuthorized = function setAuthorized(keys) { this.authorized.length = 0; - for (let key of keys) + for (const key of keys) this.addAuthorized(key); }; @@ -603,7 +603,7 @@ AuthDB.prototype.setAuthorized = function setAuthorized(keys) { */ AuthDB.prototype.getKnown = function getKnown(hostname) { - let known = this.known.get(hostname); + const known = this.known.get(hostname); let addr; if (known) @@ -621,9 +621,9 @@ AuthDB.prototype.getKnown = function getKnown(hostname) { */ AuthDB.prototype.lookup = async function lookup() { - let jobs = []; + const jobs = []; - for (let [addr, key] of this.dnsKnown) + for (const [addr, key] of this.dnsKnown) jobs.push(this.populate(addr, key)); await Promise.all(jobs); @@ -695,7 +695,7 @@ AuthDB.prototype.readKnown = async function readKnown() { */ AuthDB.prototype.parseKnown = function parseKnown(text) { - let lines = text.split(/\n+/); + const lines = text.split(/\n+/); for (let line of lines) { let parts, hostname, host, ip, key; @@ -774,7 +774,7 @@ AuthDB.prototype.readAuth = async function readAuth() { */ AuthDB.prototype.parseAuth = function parseAuth(text) { - let lines = text.split(/\n+/); + const lines = text.split(/\n+/); for (let line of lines) { let key; diff --git a/lib/net/bip151.js b/lib/net/bip151.js index 43f249432..a1ea5cf5d 100644 --- a/lib/net/bip151.js +++ b/lib/net/bip151.js @@ -95,7 +95,7 @@ function BIP151Stream(cipher) { */ BIP151Stream.prototype.init = function init(publicKey) { - let bw = new StaticWriter(33); + const bw = new StaticWriter(33); this.publicKey = publicKey; this.secret = secp256k1.ecdh(this.publicKey, this.privateKey); @@ -126,7 +126,7 @@ BIP151Stream.prototype.init = function init(publicKey) { */ BIP151Stream.prototype.shouldRekey = function shouldRekey(packet) { - let now = util.now(); + const now = util.now(); this.processed += packet.length; @@ -149,7 +149,7 @@ BIP151Stream.prototype.rekey = function rekey(k1, k2) { assert(this.prk, 'Cannot rekey before initialization.'); if (!k1) { - let seed = Buffer.allocUnsafe(64); + const seed = Buffer.allocUnsafe(64); this.sid.copy(seed, 0); @@ -354,7 +354,7 @@ BIP151.MAX_MESSAGE = 12 * 1000 * 1000; */ BIP151.prototype.error = function error() { - let msg = util.fmt.apply(util, arguments); + const msg = util.fmt.apply(util, arguments); this.emit('error', new Error(msg)); }; @@ -466,7 +466,7 @@ BIP151.prototype.encack = function encack(publicKey) { */ BIP151.prototype.cleanup = function cleanup() { - let job = this.job; + const job = this.job; assert(!this.completed, 'Already completed.'); assert(job, 'No completion job.'); @@ -493,7 +493,7 @@ BIP151.prototype.cleanup = function cleanup() { */ BIP151.prototype.resolve = function resolve(result) { - let job = this.cleanup(); + const job = this.cleanup(); job.resolve(result); }; @@ -503,7 +503,7 @@ BIP151.prototype.resolve = function resolve(result) { */ BIP151.prototype.reject = function reject(err) { - let job = this.cleanup(); + const job = this.cleanup(); job.reject(err); }; @@ -596,9 +596,9 @@ BIP151.prototype.packetSize = function packetSize(cmd, body) { */ BIP151.prototype.packet = function _packet(cmd, body) { - let size = this.packetSize(cmd, body); - let bw = new StaticWriter(size); - let payloadSize = size - 20; + const size = this.packetSize(cmd, body); + const bw = new StaticWriter(size); + const payloadSize = size - 20; let packet, payload; bw.writeU32(payloadSize); @@ -632,7 +632,7 @@ BIP151.prototype.feed = function feed(data) { this.pending.push(data); while (this.total >= this.waiting) { - let chunk = this.read(this.waiting); + const chunk = this.read(this.waiting); this.parse(chunk); } }; @@ -698,7 +698,7 @@ BIP151.prototype.parse = function parse(data) { let payload, tag, br; if (!this.hasSize) { - let size = this.input.decryptSize(data); + const size = this.input.decryptSize(data); assert(this.waiting === 4); assert(data.length === 4); diff --git a/lib/net/bip152.js b/lib/net/bip152.js index a5dee3406..c023c57d5 100644 --- a/lib/net/bip152.js +++ b/lib/net/bip152.js @@ -121,7 +121,7 @@ CompactBlock.prototype.verifyBody = function verifyBody() { */ CompactBlock.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); let count; this.readHead(br); @@ -141,7 +141,7 @@ CompactBlock.prototype.fromRaw = function fromRaw(data) { this.totalTX += count; for (let i = 0; i < count; i++) { - let index = br.readVarint(); + const index = br.readVarint(); let tx; assert(index <= 0xffff); @@ -214,7 +214,7 @@ CompactBlock.prototype.toNormalWriter = function toNormalWriter(bw) { */ CompactBlock.prototype.frameRaw = function frameRaw(witness) { - let size = this.getSize(witness); + const size = this.getSize(witness); return this.writeRaw(new StaticWriter(size), witness).render(); }; @@ -233,7 +233,7 @@ CompactBlock.prototype.getSize = function getSize(witness) { size += this.ids.length * 6; size += encoding.sizeVarint(this.ptx.length); - for (let [index, tx] of this.ptx) { + for (const [index, tx] of this.ptx) { size += encoding.sizeVarint(index); if (witness) @@ -259,8 +259,8 @@ CompactBlock.prototype.writeRaw = function writeRaw(bw, witness) { bw.writeVarint(this.ids.length); - for (let id of this.ids) { - let lo = id % 0x100000000; + for (const id of this.ids) { + const lo = id % 0x100000000; let hi = (id - lo) / 0x100000000; hi &= 0xffff; bw.writeU32(lo); @@ -269,7 +269,7 @@ CompactBlock.prototype.writeRaw = function writeRaw(bw, witness) { bw.writeVarint(this.ptx.length); - for (let [index, tx] of this.ptx) { + for (const [index, tx] of this.ptx) { bw.writeVarint(index); if (witness) @@ -306,7 +306,7 @@ CompactBlock.prototype.fillMempool = function fillMempool(witness, mempool) { have = new Set(); - for (let {tx} of mempool.map.values()) { + for (const {tx} of mempool.map.values()) { let hash = tx.hash(); let id, index; @@ -395,8 +395,8 @@ CompactBlock.prototype.hasIndex = function hasIndex(index) { */ CompactBlock.prototype.getKey = function getKey() { - let data = Buffer.concat([this.toHead(), this.keyNonce]); - let hash = digest.sha256(data); + const data = Buffer.concat([this.toHead(), this.keyNonce]); + const hash = digest.sha256(data); return hash.slice(0, 16); }; @@ -427,7 +427,7 @@ CompactBlock.prototype.init = function init() { this.available.push(null); for (let i = 0; i < this.ptx.length; i++) { - let [index, tx] = this.ptx[i]; + const [index, tx] = this.ptx[i]; last += index + 1; assert(last <= 0xffff); assert(last <= this.ids.length + i); @@ -436,7 +436,7 @@ CompactBlock.prototype.init = function init() { } for (let i = 0; i < this.ids.length; i++) { - let id = this.ids[i]; + const id = this.ids[i]; while (this.available[i + offset]) offset++; @@ -458,7 +458,7 @@ CompactBlock.prototype.init = function init() { */ CompactBlock.prototype.toBlock = function toBlock() { - let block = new Block(); + const block = new Block(); block.version = this.version; block.prevBlock = this.prevBlock; @@ -469,7 +469,7 @@ CompactBlock.prototype.toBlock = function toBlock() { block._hash = this._hash; block._hhash = this._hhash; - for (let tx of this.available) { + for (const tx of this.available) { assert(tx, 'Compact block is not full.'); block.txs.push(tx); } @@ -504,7 +504,7 @@ CompactBlock.prototype.fromBlock = function fromBlock(block, witness, nonce) { this.sipKey = this.getKey(); for (let i = 1; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; let hash = tx.hash(); let id; @@ -632,7 +632,7 @@ TXRequest.prototype.fromReader = function fromReader(br) { count = br.readVarint(); for (let i = 0; i < count; i++) { - let index = br.readVarint(); + const index = br.readVarint(); assert(index <= 0xffff); this.indexes.push(index); } @@ -730,7 +730,7 @@ TXRequest.prototype.toWriter = function toWriter(bw) { */ TXRequest.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -841,7 +841,7 @@ TXResponse.fromRaw = function fromRaw(data) { TXResponse.prototype.fromBlock = function fromBlock(block, req) { this.hash = req.hash; - for (let index of req.indexes) { + for (const index of req.indexes) { if (index >= block.txs.length) break; @@ -910,7 +910,7 @@ TXResponse.prototype.getSize = function getSize(witness) { size += 32; size += encoding.sizeVarint(this.txs.length); - for (let tx of this.txs) { + for (const tx of this.txs) { if (witness) size += tx.getSize(); else @@ -932,7 +932,7 @@ TXResponse.prototype.writeRaw = function writeRaw(bw, witness) { bw.writeVarint(this.txs.length); - for (let tx of this.txs) { + for (const tx of this.txs) { if (witness) tx.toWriter(bw); else @@ -950,7 +950,7 @@ TXResponse.prototype.writeRaw = function writeRaw(bw, witness) { */ TXResponse.prototype.frameRaw = function frameRaw(witness) { - let size = this.getSize(witness); + const size = this.getSize(witness); return this.writeRaw(new StaticWriter(size), witness).render(); }; diff --git a/lib/net/dns.js b/lib/net/dns.js index b6a8f64a8..5ad6517e8 100644 --- a/lib/net/dns.js +++ b/lib/net/dns.js @@ -59,7 +59,7 @@ exports.lookup = function lookup(host, proxy) { return socks.resolve(proxy, host); return new Promise((resolve, reject) => { - let addrs = []; + const addrs = []; dns.lookup(host, options, to((err, result) => { if (err) { @@ -72,7 +72,7 @@ exports.lookup = function lookup(host, proxy) { return; } - for (let addr of result) + for (const addr of result) addrs.push(addr.address); resolve(addrs); @@ -85,7 +85,7 @@ exports.lookup = function lookup(host, proxy) { */ function to(callback) { - let timeout = setTimeout(() => { + const timeout = setTimeout(() => { callback(new Error('DNS request timed out.')); callback = null; }, 5000); diff --git a/lib/net/hostlist.js b/lib/net/hostlist.js index 4ed8a0c5e..8e33a35c4 100644 --- a/lib/net/hostlist.js +++ b/lib/net/hostlist.js @@ -134,10 +134,10 @@ HostList.scores = { */ HostList.prototype._init = function init() { - let options = this.options; - let scores = HostList.scores; - let hosts = IP.getPublic(); - let port = this.address.port; + const options = this.options; + const scores = HostList.scores; + const hosts = IP.getPublic(); + const port = this.address.port; for (let i = 0; i < this.options.maxBuckets; i++) this.fresh.push(new Map()); @@ -151,7 +151,7 @@ HostList.prototype._init = function init() { this.pushLocal(this.address, scores.MANUAL); this.addLocal(options.host, options.port, scores.BIND); - for (let host of hosts) + for (const host of hosts) this.addLocal(host, port, scores.IF); }; @@ -227,10 +227,10 @@ HostList.prototype.stop = function stop() { */ HostList.prototype.injectSeeds = function injectSeeds() { - let nodes = seeds.get(this.network.type); + const nodes = seeds.get(this.network.type); - for (let node of nodes) { - let addr = NetAddress.fromHostname(node, this.network); + for (const node of nodes) { + const addr = NetAddress.fromHostname(node, this.network); if (!addr.isRoutable()) continue; @@ -252,7 +252,7 @@ HostList.prototype.injectSeeds = function injectSeeds() { */ HostList.prototype.loadFile = async function loadFile() { - let filename = this.options.filename; + const filename = this.options.filename; let data, json; if (fs.unsupported) @@ -284,7 +284,7 @@ HostList.prototype.loadFile = async function loadFile() { */ HostList.prototype.flush = async function flush() { - let filename = this.options.filename; + const filename = this.options.filename; let json, data; if (fs.unsupported) @@ -329,7 +329,7 @@ HostList.prototype.size = function size() { */ HostList.prototype.isFull = function isFull() { - let max = this.options.maxBuckets * this.options.maxEntries; + const max = this.options.maxBuckets * this.options.maxEntries; return this.size() >= max; }; @@ -340,10 +340,10 @@ HostList.prototype.isFull = function isFull() { HostList.prototype.reset = function reset() { this.map.clear(); - for (let bucket of this.fresh) + for (const bucket of this.fresh) bucket.clear(); - for (let bucket of this.used) + for (const bucket of this.used) bucket.reset(); this.totalFresh = 0; @@ -385,7 +385,7 @@ HostList.prototype.clearBanned = function clearBanned() { */ HostList.prototype.isBanned = function isBanned(host) { - let time = this.banned.get(host); + const time = this.banned.get(host); if (time == null) return false; @@ -404,7 +404,7 @@ HostList.prototype.isBanned = function isBanned(host) { */ HostList.prototype.getHost = function getHost() { - let now = this.network.now(); + const now = this.network.now(); let buckets = null; let factor = 1; @@ -421,7 +421,7 @@ HostList.prototype.getHost = function getHost() { for (;;) { let index = util.random(0, buckets.length); - let bucket = buckets[index]; + const bucket = buckets[index]; let entry, num; if (bucket.size === 0) @@ -458,11 +458,11 @@ HostList.prototype.getHost = function getHost() { */ HostList.prototype.freshBucket = function freshBucket(entry) { - let addr = entry.addr; - let src = entry.src; - let data = concat32(addr.raw, src.raw); - let hash = murmur3(data, 0xfba4c795); - let index = hash % this.fresh.length; + const addr = entry.addr; + const src = entry.src; + const data = concat32(addr.raw, src.raw); + const hash = murmur3(data, 0xfba4c795); + const index = hash % this.fresh.length; return this.fresh[index]; }; @@ -474,9 +474,9 @@ HostList.prototype.freshBucket = function freshBucket(entry) { */ HostList.prototype.usedBucket = function usedBucket(entry) { - let addr = entry.addr; - let hash = murmur3(addr.raw, 0xfba4c795); - let index = hash % this.used.length; + const addr = entry.addr; + const hash = murmur3(addr.raw, 0xfba4c795); + const index = hash % this.used.length; return this.used[index]; }; @@ -488,7 +488,7 @@ HostList.prototype.usedBucket = function usedBucket(entry) { */ HostList.prototype.add = function add(addr, src) { - let now = this.network.now(); + const now = this.network.now(); let penalty = 2 * 60 * 60; let interval = 24 * 60 * 60; let factor = 1; @@ -581,7 +581,7 @@ HostList.prototype.add = function add(addr, src) { HostList.prototype.evictFresh = function evictFresh(bucket) { let old; - for (let entry of bucket.values()) { + for (const entry of bucket.values()) { if (this.isStale(entry)) { bucket.delete(entry.key()); @@ -620,7 +620,7 @@ HostList.prototype.evictFresh = function evictFresh(bucket) { */ HostList.prototype.isStale = function isStale(entry) { - let now = this.network.now(); + const now = this.network.now(); if (entry.lastAttempt && entry.lastAttempt >= now - 60) return false; @@ -652,7 +652,7 @@ HostList.prototype.isStale = function isStale(entry) { */ HostList.prototype.remove = function remove(hostname) { - let entry = this.map.get(hostname); + const entry = this.map.get(hostname); if (!entry) return; @@ -665,7 +665,7 @@ HostList.prototype.remove = function remove(hostname) { while (head.prev) head = head.prev; - for (let bucket of this.used) { + for (const bucket of this.used) { if (bucket.head === head) { bucket.remove(entry); this.totalUsed--; @@ -676,7 +676,7 @@ HostList.prototype.remove = function remove(hostname) { assert(!head); } else { - for (let bucket of this.fresh) { + for (const bucket of this.fresh) { if (bucket.delete(entry.key())) entry.refCount--; } @@ -696,8 +696,8 @@ HostList.prototype.remove = function remove(hostname) { */ HostList.prototype.markAttempt = function markAttempt(hostname) { - let entry = this.map.get(hostname); - let now = this.network.now(); + const entry = this.map.get(hostname); + const now = this.network.now(); if (!entry) return; @@ -712,8 +712,8 @@ HostList.prototype.markAttempt = function markAttempt(hostname) { */ HostList.prototype.markSuccess = function markSuccess(hostname) { - let entry = this.map.get(hostname); - let now = this.network.now(); + const entry = this.map.get(hostname); + const now = this.network.now(); if (!entry) return; @@ -729,8 +729,8 @@ HostList.prototype.markSuccess = function markSuccess(hostname) { */ HostList.prototype.markAck = function markAck(hostname, services) { - let entry = this.map.get(hostname); - let now = this.network.now(); + const entry = this.map.get(hostname); + const now = this.network.now(); let bucket, evicted, old, fresh; if (!entry) @@ -749,7 +749,7 @@ HostList.prototype.markAck = function markAck(hostname, services) { assert(entry.refCount > 0); // Remove from fresh. - for (let bucket of this.fresh) { + for (const bucket of this.fresh) { if (bucket.delete(entry.key())) { entry.refCount--; old = bucket; @@ -812,9 +812,9 @@ HostList.prototype.evictUsed = function evictUsed(bucket) { */ HostList.prototype.toArray = function toArray() { - let out = []; + const out = []; - for (let entry of this.map.values()) + for (const entry of this.map.values()) out.push(entry.addr); assert.equal(out.length, this.size()); @@ -873,10 +873,10 @@ HostList.prototype.addNode = function addNode(host) { */ HostList.prototype.removeNode = function removeNode(host) { - let addr = IP.fromHostname(host, this.network.port); + const addr = IP.fromHostname(host, this.network.port); for (let i = 0; i < this.nodes.length; i++) { - let node = this.nodes[i]; + const node = this.nodes[i]; if (node.host !== addr.host) continue; @@ -900,7 +900,7 @@ HostList.prototype.removeNode = function removeNode(host) { HostList.prototype.setSeeds = function setSeeds(seeds) { this.dnsSeeds.length = 0; - for (let host of seeds) + for (const host of seeds) this.addSeed(host); }; @@ -913,7 +913,7 @@ HostList.prototype.setNodes = function setNodes(nodes) { this.dnsNodes.length = 0; this.nodes.length = 0; - for (let host of nodes) + for (const host of nodes) this.addNode(host); }; @@ -926,7 +926,7 @@ HostList.prototype.setNodes = function setNodes(nodes) { */ HostList.prototype.addLocal = function addLocal(host, port, score) { - let addr = NetAddress.fromHost(host, port, this.network); + const addr = NetAddress.fromHost(host, port, this.network); addr.services = this.options.services; return this.pushLocal(addr, score); }; @@ -971,8 +971,8 @@ HostList.prototype.getLocal = function getLocal(src) { if (this.local.size === 0) return null; - for (let dest of this.local.values()) { - let reach = src.getReachability(dest.addr); + for (const dest of this.local.values()) { + const reach = src.getReachability(dest.addr); if (reach < bestReach) continue; @@ -996,7 +996,7 @@ HostList.prototype.getLocal = function getLocal(src) { */ HostList.prototype.markLocal = function markLocal(addr) { - let local = this.local.get(addr.hostname); + const local = this.local.get(addr.hostname); if (!local) return false; @@ -1013,9 +1013,9 @@ HostList.prototype.markLocal = function markLocal(addr) { */ HostList.prototype.discoverSeeds = async function discoverSeeds() { - let jobs = []; + const jobs = []; - for (let seed of this.dnsSeeds) + for (const seed of this.dnsSeeds) jobs.push(this.populateSeed(seed)); await Promise.all(jobs); @@ -1028,9 +1028,9 @@ HostList.prototype.discoverSeeds = async function discoverSeeds() { */ HostList.prototype.discoverNodes = async function discoverNodes() { - let jobs = []; + const jobs = []; - for (let node of this.dnsNodes) + for (const node of this.dnsNodes) jobs.push(this.populateNode(node)); await Promise.all(jobs); @@ -1044,7 +1044,7 @@ HostList.prototype.discoverNodes = async function discoverNodes() { */ HostList.prototype.populateNode = async function populateNode(addr) { - let addrs = await this.populate(addr); + const addrs = await this.populate(addr); if (addrs.length === 0) return; @@ -1061,9 +1061,9 @@ HostList.prototype.populateNode = async function populateNode(addr) { */ HostList.prototype.populateSeed = async function populateSeed(seed) { - let addrs = await this.populate(seed); + const addrs = await this.populate(seed); - for (let addr of addrs) + for (const addr of addrs) this.add(addr); }; @@ -1075,7 +1075,7 @@ HostList.prototype.populateSeed = async function populateSeed(seed) { */ HostList.prototype.populate = async function populate(target) { - let addrs = []; + const addrs = []; let hosts; assert(target.type === IP.types.DNS, 'Resolved host passed.'); @@ -1089,8 +1089,8 @@ HostList.prototype.populate = async function populate(target) { return addrs; } - for (let host of hosts) { - let addr = NetAddress.fromHost(host, target.port, this.network); + for (const host of hosts) { + const addr = NetAddress.fromHost(host, target.port, this.network); addrs.push(addr); } @@ -1103,22 +1103,22 @@ HostList.prototype.populate = async function populate(target) { */ HostList.prototype.toJSON = function toJSON() { - let addrs = []; - let fresh = []; - let used = []; + const addrs = []; + const fresh = []; + const used = []; - for (let entry of this.map.values()) + for (const entry of this.map.values()) addrs.push(entry.toJSON()); - for (let bucket of this.fresh) { - let keys = []; - for (let key of bucket.keys()) + for (const bucket of this.fresh) { + const keys = []; + for (const key of bucket.keys()) keys.push(key); fresh.push(keys); } - for (let bucket of this.used) { - let keys = []; + for (const bucket of this.used) { + const keys = []; for (let entry = bucket.head; entry; entry = entry.next) keys.push(entry.key()); used.push(keys); @@ -1140,12 +1140,12 @@ HostList.prototype.toJSON = function toJSON() { */ HostList.prototype.fromJSON = function fromJSON(json) { - let sources = new Map(); - let map = new Map(); + const sources = new Map(); + const map = new Map(); let totalFresh = 0; let totalUsed = 0; - let fresh = []; - let used = []; + const fresh = []; + const used = []; assert(json && typeof json === 'object'); @@ -1154,8 +1154,8 @@ HostList.prototype.fromJSON = function fromJSON(json) { assert(Array.isArray(json.addrs)); - for (let addr of json.addrs) { - let entry = HostEntry.fromJSON(addr, this.network); + for (const addr of json.addrs) { + const entry = HostEntry.fromJSON(addr, this.network); let src = sources.get(entry.src.hostname); // Save some memory. @@ -1173,11 +1173,11 @@ HostList.prototype.fromJSON = function fromJSON(json) { assert(json.fresh.length <= this.options.maxBuckets, 'Buckets mismatch.'); - for (let keys of json.fresh) { - let bucket = new Map(); + for (const keys of json.fresh) { + const bucket = new Map(); - for (let key of keys) { - let entry = map.get(key); + for (const key of keys) { + const entry = map.get(key); assert(entry); if (entry.refCount === 0) totalFresh++; @@ -1198,11 +1198,11 @@ HostList.prototype.fromJSON = function fromJSON(json) { assert(json.used.length <= this.options.maxBuckets, 'Buckets mismatch.'); - for (let keys of json.used) { - let bucket = new List(); + for (const keys of json.used) { + const bucket = new List(); - for (let key of keys) { - let entry = map.get(key); + for (const key of keys) { + const entry = map.get(key); assert(entry); assert(entry.refCount === 0); assert(!entry.used); @@ -1220,7 +1220,7 @@ HostList.prototype.fromJSON = function fromJSON(json) { assert(used.length === this.used.length, 'Buckets mismatch.'); - for (let entry of map.values()) + for (const entry of map.values()) assert(entry.used || entry.refCount > 0); this.map = map; @@ -1312,7 +1312,7 @@ HostEntry.prototype.key = function key() { */ HostEntry.prototype.chance = function _chance(now) { - let attempts = this.attempts; + const attempts = this.attempts; let chance = 1; if (now - this.lastAttempt < 60 * 10) @@ -1518,7 +1518,7 @@ HostListOptions.prototype.fromOptions = function fromOptions(options) { if (options.host != null) { assert(typeof options.host === 'string'); - let raw = IP.toBuffer(options.host); + const raw = IP.toBuffer(options.host); this.host = IP.toString(raw); if (IP.isRoutable(raw)) this.address.setHost(this.host); @@ -1594,7 +1594,7 @@ HostListOptions.prototype.fromOptions = function fromOptions(options) { */ function concat32(left, right) { - let data = POOL32; + const data = POOL32; left.copy(data, 0); right.copy(data, 32); return data; diff --git a/lib/net/packets.js b/lib/net/packets.js index 443642d7c..849d715af 100644 --- a/lib/net/packets.js +++ b/lib/net/packets.js @@ -273,7 +273,7 @@ VersionPacket.prototype.toWriter = function toWriter(bw) { */ VersionPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -430,7 +430,7 @@ PingPacket.prototype.getSize = function getSize() { */ PingPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -664,7 +664,7 @@ AddrPacket.prototype.getSize = function getSize() { AddrPacket.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.items.length); - for (let item of this.items) + for (const item of this.items) item.toWriter(bw, true); return bw; @@ -676,7 +676,7 @@ AddrPacket.prototype.toWriter = function toWriter(bw) { */ AddrPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -687,8 +687,8 @@ AddrPacket.prototype.toRaw = function toRaw() { */ AddrPacket.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let count = br.readVarint(); + const br = new BufferReader(data); + const count = br.readVarint(); for (let i = 0; i < count; i++) this.items.push(NetAddress.fromReader(br, true)); @@ -762,7 +762,7 @@ InvPacket.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.items.length); - for (let item of this.items) + for (const item of this.items) item.toWriter(bw); return bw; @@ -774,7 +774,7 @@ InvPacket.prototype.toWriter = function toWriter(bw) { */ InvPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -785,7 +785,7 @@ InvPacket.prototype.toRaw = function toRaw() { */ InvPacket.prototype.fromReader = function fromReader(br) { - let count = br.readVarint(); + const count = br.readVarint(); assert(count <= 50000, 'Inv item count too high.'); @@ -962,7 +962,7 @@ GetBlocksPacket.prototype.toWriter = function toWriter(bw) { bw.writeU32(this.version); bw.writeVarint(this.locator.length); - for (let hash of this.locator) + for (const hash of this.locator) bw.writeHash(hash); bw.writeHash(this.stop || encoding.ZERO_HASH); @@ -976,7 +976,7 @@ GetBlocksPacket.prototype.toWriter = function toWriter(bw) { */ GetBlocksPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -1103,7 +1103,7 @@ HeadersPacket.prototype.getSize = function getSize() { size += encoding.sizeVarint(this.items.length); - for (let item of this.items) + for (const item of this.items) size += item.getSize(); return size; @@ -1119,7 +1119,7 @@ HeadersPacket.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.items.length); - for (let item of this.items) + for (const item of this.items) item.toWriter(bw); return bw; @@ -1131,7 +1131,7 @@ HeadersPacket.prototype.toWriter = function toWriter(bw) { */ HeadersPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -1142,7 +1142,7 @@ HeadersPacket.prototype.toRaw = function toRaw() { */ HeadersPacket.prototype.fromReader = function fromReader(br) { - let count = br.readVarint(); + const count = br.readVarint(); assert(count <= 2000, 'Too many headers.'); @@ -1535,7 +1535,7 @@ RejectPacket.prototype.rhash = function rhash() { */ RejectPacket.prototype.getCode = function getCode() { - let code = RejectPacket.codesByVal[this.code]; + const code = RejectPacket.codesByVal[this.code]; if (!code) return this.code + ''; @@ -1586,7 +1586,7 @@ RejectPacket.prototype.toWriter = function toWriter(bw) { */ RejectPacket.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -1709,8 +1709,8 @@ RejectPacket.fromError = function fromError(err, obj) { */ RejectPacket.prototype.inspect = function inspect() { - let code = RejectPacket.codesByVal[this.code] || this.code; - let hash = this.hash ? util.revHex(this.hash) : null; + const code = RejectPacket.codesByVal[this.code] || this.code; + const hash = this.hash ? util.revHex(this.hash) : null; return '= this.waiting) { - let chunk = Buffer.allocUnsafe(this.waiting); + const chunk = Buffer.allocUnsafe(this.waiting); let off = 0; let len = 0; diff --git a/lib/net/peer.js b/lib/net/peer.js index 245ee25a0..b77c1a109 100644 --- a/lib/net/peer.js +++ b/lib/net/peer.js @@ -229,7 +229,7 @@ Peer.TIMEOUT_INTERVAL = 20 * 60000; */ Peer.fromInbound = function fromInbound(options, socket) { - let peer = new Peer(options); + const peer = new Peer(options); peer.accept(socket); return peer; }; @@ -242,7 +242,7 @@ Peer.fromInbound = function fromInbound(options, socket) { */ Peer.fromOutbound = function fromOutbound(options, addr) { - let peer = new Peer(options); + const peer = new Peer(options); peer.connect(addr); return peer; }; @@ -359,9 +359,9 @@ Peer.prototype.setCipher = function setCipher(cipher) { */ Peer.prototype.setAuth = function setAuth(db, key) { - let bip151 = this.bip151; - let hostname = this.hostname(); - let outbound = this.outbound; + const bip151 = this.bip151; + const hostname = this.hostname(); + const outbound = this.outbound; assert(this.bip151, 'BIP151 not set.'); assert(!this.bip150, 'BIP150 already set.'); @@ -517,7 +517,7 @@ Peer.prototype.initConnect = function initConnect() { } return new Promise((resolve, reject) => { - let cleanup = () => { + const cleanup = () => { if (this.connectTimeout != null) { clearTimeout(this.connectTimeout); this.connectTimeout = null; @@ -705,7 +705,7 @@ Peer.prototype.finalize = async function finalize() { */ Peer.prototype.announceBlock = function announceBlock(blocks) { - let inv = []; + const inv = []; if (!this.handshake) return; @@ -716,7 +716,7 @@ Peer.prototype.announceBlock = function announceBlock(blocks) { if (!Array.isArray(blocks)) blocks = [blocks]; - for (let block of blocks) { + for (const block of blocks) { assert(block instanceof Block); // Don't send if they already have it. @@ -755,7 +755,7 @@ Peer.prototype.announceBlock = function announceBlock(blocks) { */ Peer.prototype.announceTX = function announceTX(txs) { - let inv = []; + const inv = []; if (!this.handshake) return; @@ -771,7 +771,7 @@ Peer.prototype.announceTX = function announceTX(txs) { if (!Array.isArray(txs)) txs = [txs]; - for (let tx of txs) { + for (const tx of txs) { assert(tx instanceof TX); // Don't send if they already have it. @@ -787,8 +787,8 @@ Peer.prototype.announceTX = function announceTX(txs) { // Check the fee filter. if (this.feeRate !== -1) { - let hash = tx.hash('hex'); - let rate = this.options.getRate(hash); + const hash = tx.hash('hex'); + const rate = this.options.getRate(hash); if (rate !== -1 && rate < this.feeRate) continue; } @@ -816,7 +816,7 @@ Peer.prototype.queueInv = function queueInv(items) { if (!Array.isArray(items)) items = [items]; - for (let item of items) { + for (const item of items) { if (item.type === invTypes.BLOCK) hasBlock = true; this.invQueue.push(item); @@ -832,8 +832,8 @@ Peer.prototype.queueInv = function queueInv(items) { */ Peer.prototype.flushInv = function flushInv() { - let queue = this.invQueue.slice(); - let items = []; + const queue = this.invQueue.slice(); + const items = []; if (this.destroyed) return; @@ -846,7 +846,7 @@ Peer.prototype.flushInv = function flushInv() { this.logger.spam('Serving %d inv items to %s.', queue.length, this.hostname()); - for (let item of queue) { + for (const item of queue) { if (!this.invFilter.added(item.hash, 'hex')) continue; @@ -854,7 +854,7 @@ Peer.prototype.flushInv = function flushInv() { } for (let i = 0; i < items.length; i += 1000) { - let chunk = items.slice(i, i + 1000); + const chunk = items.slice(i, i + 1000); this.send(new packets.InvPacket(chunk)); } }; @@ -874,7 +874,7 @@ Peer.prototype.sendInv = function sendInv(items) { if (!Array.isArray(items)) items = [items]; - for (let item of items) + for (const item of items) this.invFilter.add(item.hash, 'hex'); if (items.length === 0) @@ -884,7 +884,7 @@ Peer.prototype.sendInv = function sendInv(items) { items.length, this.hostname()); for (let i = 0; i < items.length; i += 1000) { - let chunk = items.slice(i, i + 1000); + const chunk = items.slice(i, i + 1000); this.send(new packets.InvPacket(chunk)); } }; @@ -904,7 +904,7 @@ Peer.prototype.sendHeaders = function sendHeaders(items) { if (!Array.isArray(items)) items = [items]; - for (let item of items) + for (const item of items) this.invFilter.add(item.hash()); if (items.length === 0) @@ -914,7 +914,7 @@ Peer.prototype.sendHeaders = function sendHeaders(items) { items.length, this.hostname()); for (let i = 0; i < items.length; i += 2000) { - let chunk = items.slice(i, i + 2000); + const chunk = items.slice(i, i + 2000); this.send(new packets.HeadersPacket(chunk)); } }; @@ -927,8 +927,8 @@ Peer.prototype.sendHeaders = function sendHeaders(items) { */ Peer.prototype.sendCompactBlock = function sendCompactBlock(block) { - let witness = this.compactWitness; - let compact = BIP152.CompactBlock.fromBlock(block, witness); + const witness = this.compactWitness; + const compact = BIP152.CompactBlock.fromBlock(block, witness); this.send(new packets.CmpctBlockPacket(compact, witness)); }; @@ -937,7 +937,7 @@ Peer.prototype.sendCompactBlock = function sendCompactBlock(block) { */ Peer.prototype.sendVersion = function sendVersion() { - let packet = new packets.VersionPacket(); + const packet = new packets.VersionPacket(); packet.version = this.options.version; packet.services = this.options.services; packet.time = this.network.now(); @@ -1021,7 +1021,7 @@ Peer.prototype.sendFeeRate = function sendFeeRate(rate) { */ Peer.prototype.destroy = function destroy() { - let connected = this.connected; + const connected = this.connected; let jobs; if (this.destroyed) @@ -1064,10 +1064,10 @@ Peer.prototype.destroy = function destroy() { this.drainSize = 0; this.drainQueue = []; - for (let job of jobs) + for (const job of jobs) job.reject(new Error('Peer was destroyed.')); - for (let [cmd, entry] of this.responseMap) { + for (const [cmd, entry] of this.responseMap) { this.responseMap.delete(cmd); entry.reject(new Error('Peer was destroyed.')); } @@ -1106,7 +1106,7 @@ Peer.prototype.send = function send(packet) { // Used cached hashes as the // packet checksum for speed. if (packet.type === packetTypes.TX) { - let tx = packet.tx; + const tx = packet.tx; if (packet.witness) { if (!tx.isCoinbase()) checksum = tx.witnessHash(); @@ -1126,7 +1126,7 @@ Peer.prototype.send = function send(packet) { */ Peer.prototype.sendRaw = function sendRaw(cmd, body, checksum) { - let payload = this.framePacket(cmd, body, checksum); + const payload = this.framePacket(cmd, body, checksum); this.write(payload); }; @@ -1153,7 +1153,7 @@ Peer.prototype.drain = function drain() { */ Peer.prototype.handleDrain = function handleDrain() { - let jobs = this.drainQueue; + const jobs = this.drainQueue; this.drainSize = 0; @@ -1162,7 +1162,7 @@ Peer.prototype.handleDrain = function handleDrain() { this.drainQueue = []; - for (let job of jobs) + for (const job of jobs) job.resolve(); }; @@ -1192,7 +1192,7 @@ Peer.prototype.needsDrain = function needsDrain(size) { */ Peer.prototype.addTimeout = function addTimeout(packet) { - let timeout = Peer.RESPONSE_TIMEOUT; + const timeout = Peer.RESPONSE_TIMEOUT; if (!this.outbound) return; @@ -1230,7 +1230,7 @@ Peer.prototype.fulfill = function fulfill(packet) { case packetTypes.MERKLEBLOCK: case packetTypes.TX: case packetTypes.NOTFOUND: { - let entry = this.response(packetTypes.DATA, packet); + const entry = this.response(packetTypes.DATA, packet); assert(!entry || entry.jobs.length === 0); break; } @@ -1245,11 +1245,11 @@ Peer.prototype.fulfill = function fulfill(packet) { */ Peer.prototype.maybeTimeout = function maybeTimeout() { - let now = util.ms(); + const now = util.ms(); - for (let [key, entry] of this.responseMap) { + for (const [key, entry] of this.responseMap) { if (now > entry.timeout) { - let name = packets.typesByVal[key]; + const name = packets.typesByVal[key]; this.error('Peer is stalling (%s).', name.toLowerCase()); this.destroy(); return; @@ -1274,7 +1274,7 @@ Peer.prototype.maybeTimeout = function maybeTimeout() { } if (this.options.isFull() || !this.syncing) { - for (let time of this.blockMap.values()) { + for (const time of this.blockMap.values()) { if (now > time + Peer.BLOCK_TIMEOUT) { this.error('Peer is stalling (block).'); this.destroy(); @@ -1282,7 +1282,7 @@ Peer.prototype.maybeTimeout = function maybeTimeout() { } } - for (let time of this.txMap.values()) { + for (const time of this.txMap.values()) { if (now > time + Peer.TX_TIMEOUT) { this.error('Peer is stalling (tx).'); this.destroy(); @@ -1290,7 +1290,7 @@ Peer.prototype.maybeTimeout = function maybeTimeout() { } } - for (let block of this.compactBlocks.values()) { + for (const block of this.compactBlocks.values()) { if (now > block.now + Peer.RESPONSE_TIMEOUT) { this.error('Peer is stalling (blocktxn).'); this.destroy(); @@ -1364,7 +1364,7 @@ Peer.prototype.request = function request(type, timeout) { */ Peer.prototype.response = function response(type, payload) { - let entry = this.responseMap.get(type); + const entry = this.responseMap.get(type); if (!entry) return; @@ -1477,9 +1477,9 @@ Peer.prototype.getData = function getData(items) { */ Peer.prototype.getItems = function getItems(type, hashes) { - let items = []; + const items = []; - for (let hash of hashes) + for (const hash of hashes) items.push(new InvItem(type, hash)); if (items.length === 0) @@ -1555,7 +1555,7 @@ Peer.prototype.readPacket = async function readPacket(packet) { break; } default: { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { this.socket.pause(); await this.handlePacket(packet); @@ -1757,8 +1757,8 @@ Peer.prototype.handlePing = async function handlePing(packet) { */ Peer.prototype.handlePong = async function handlePong(packet) { - let nonce = packet.nonce; - let now = util.ms(); + const nonce = packet.nonce; + const now = util.ms(); if (!this.challenge) { this.logger.debug('Peer sent an unsolicited pong (%s).', this.hostname()); @@ -1830,7 +1830,7 @@ Peer.prototype.handleFilterLoad = async function handleFilterLoad(packet) { */ Peer.prototype.handleFilterAdd = async function handleFilterAdd(packet) { - let data = packet.data; + const data = packet.data; if (data.length > consensus.MAX_SCRIPT_PUSH) { this.increaseBan(100); @@ -1865,7 +1865,7 @@ Peer.prototype.handleFilterClear = async function handleFilterClear(packet) { */ Peer.prototype.handleFeeFilter = async function handleFeeFilter(packet) { - let rate = packet.rate; + const rate = packet.rate; if (!(rate >= 0 && rate <= consensus.MAX_MONEY)) { this.increaseBan(100); @@ -2006,7 +2006,7 @@ Peer.prototype.handleAuthPropose = async function handleAuthPropose(packet) { */ Peer.prototype.sendGetHeaders = function sendGetHeaders(locator, stop) { - let packet = new packets.GetHeadersPacket(locator, stop); + const packet = new packets.GetHeadersPacket(locator, stop); let hash = null; let end = null; @@ -2034,7 +2034,7 @@ Peer.prototype.sendGetHeaders = function sendGetHeaders(locator, stop) { */ Peer.prototype.sendGetBlocks = function getBlocks(locator, stop) { - let packet = new packets.GetBlocksPacket(locator, stop); + const packet = new packets.GetBlocksPacket(locator, stop); let hash = null; let end = null; @@ -2086,7 +2086,7 @@ Peer.prototype.sendMempool = function sendMempool() { */ Peer.prototype.sendReject = function sendReject(code, reason, msg, hash) { - let reject = packets.RejectPacket.fromReason(code, reason, msg, hash); + const reject = packets.RejectPacket.fromReason(code, reason, msg, hash); if (msg) { this.logger.debug('Rejecting %s %s (%s): code=%s reason=%s.', @@ -2459,14 +2459,14 @@ RequestEntry.prototype.setTimeout = function setTimeout(timeout) { }; RequestEntry.prototype.reject = function reject(err) { - for (let job of this.jobs) + for (const job of this.jobs) job.reject(err); this.jobs.length = 0; }; RequestEntry.prototype.resolve = function resolve(result) { - for (let job of this.jobs) + for (const job of this.jobs) job.resolve(result); this.jobs.length = 0; diff --git a/lib/net/pool.js b/lib/net/pool.js index b53b203cc..6bfb532d6 100644 --- a/lib/net/pool.js +++ b/lib/net/pool.js @@ -155,7 +155,7 @@ Pool.prototype._init = function _init() { }); this.server.on('listening', () => { - let data = this.server.address(); + const data = this.server.address(); this.logger.info( 'Pool server listening on %s (port=%d).', data.address, data.port); @@ -229,7 +229,7 @@ Pool.prototype._open = async function _open() { this.logger.info('Pool loaded (maxpeers=%d).', this.options.maxOutbound); if (this.options.bip150) { - let key = secp256k1.publicKeyCreate(this.options.identityKey, true); + const key = secp256k1.publicKeyCreate(this.options.identityKey, true); this.logger.info('Identity public key: %s.', key.toString('hex')); this.logger.info('Identity address: %s.', BIP150.address(key)); } @@ -242,7 +242,7 @@ Pool.prototype._open = async function _open() { */ Pool.prototype.resetChain = function resetChain() { - let tip = this.chain.tip; + const tip = this.chain.tip; if (!this.options.checkpoints) return; @@ -282,7 +282,7 @@ Pool.prototype._close = async function close() { */ Pool.prototype.connect = async function connect() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._connect(); } finally { @@ -325,7 +325,7 @@ Pool.prototype._connect = async function connect() { */ Pool.prototype.disconnect = async function disconnect() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._disconnect(); } finally { @@ -347,7 +347,7 @@ Pool.prototype._disconnect = async function disconnect() { this.disconnecting = true; - for (let item of this.invMap.values()) + for (const item of this.invMap.values()) item.resolve(); this.peers.destroy(); @@ -458,8 +458,8 @@ Pool.prototype.discover = async function discover() { */ Pool.prototype.discoverGateway = async function discoverGateway() { - let src = this.options.publicPort; - let dest = this.options.port; + const src = this.options.publicPort; + const dest = this.options.port; let wan, host; // Pointless if we're not listening. @@ -513,8 +513,8 @@ Pool.prototype.discoverGateway = async function discoverGateway() { */ Pool.prototype.discoverSeeds = async function discoverSeeds(checkPeers) { - let max = Math.min(2, this.options.maxOutbound); - let size = this.hosts.size(); + const max = Math.min(2, this.options.maxOutbound); + const size = this.hosts.size(); let total = 0; if (this.hosts.dnsSeeds.length === 0) @@ -550,7 +550,7 @@ Pool.prototype.discoverSeeds = async function discoverSeeds(checkPeers) { */ Pool.prototype.discoverExternal = async function discoverExternal() { - let port = this.options.publicPort; + const port = this.options.publicPort; let host4, host6; // Pointless if we're not listening. @@ -901,7 +901,7 @@ Pool.prototype.sendGetAddr = function sendGetAddr() { */ Pool.prototype.resolveHeaders = function resolveHeaders(peer) { - let items = []; + const items = []; for (let node = this.headerNext; node; node = node.next) { this.headerNext = node.next; @@ -946,7 +946,7 @@ Pool.prototype.resolveHeight = function resolveHeight(hash, height) { */ Pool.prototype.getNextTip = function getNextTip(height) { - for (let next of this.network.checkpoints) { + for (const next of this.network.checkpoints) { if (next.height > height) return new HeaderEntry(next.hash, next.height); } @@ -960,10 +960,10 @@ Pool.prototype.getNextTip = function getNextTip(height) { */ Pool.prototype.announceList = function announceList(peer) { - let blocks = []; - let txs = []; + const blocks = []; + const txs = []; - for (let item of this.invMap.values()) { + for (const item of this.invMap.values()) { switch (item.type) { case invTypes.BLOCK: blocks.push(item.msg); @@ -993,8 +993,8 @@ Pool.prototype.announceList = function announceList(peer) { */ Pool.prototype.getBroadcasted = function getBroadcasted(peer, item) { - let type = item.isTX() ? invTypes.TX : invTypes.BLOCK; - let entry = this.invMap.get(item.hash); + const type = item.isTX() ? invTypes.TX : invTypes.BLOCK; + const entry = this.invMap.get(item.hash); if (!entry) return; @@ -1028,7 +1028,7 @@ Pool.prototype.getBroadcasted = function getBroadcasted(peer, item) { */ Pool.prototype.getItem = async function getItem(peer, item) { - let entry = this.getBroadcasted(peer, item); + const entry = this.getBroadcasted(peer, item); if (entry) return entry; @@ -1106,9 +1106,9 @@ Pool.prototype.sendBlock = async function sendBlock(peer, item, witness) { */ Pool.prototype.createOutbound = function createOutbound(addr) { - let cipher = BIP151.ciphers.CHACHAPOLY; - let identity = this.options.identityKey; - let peer = Peer.fromOutbound(this.options, addr); + const cipher = BIP151.ciphers.CHACHAPOLY; + const identity = this.options.identityKey; + const peer = Peer.fromOutbound(this.options, addr); this.hosts.markAttempt(addr.hostname); @@ -1135,9 +1135,9 @@ Pool.prototype.createOutbound = function createOutbound(addr) { */ Pool.prototype.createInbound = function createInbound(socket) { - let cipher = BIP151.ciphers.CHACHAPOLY; - let identity = this.options.identityKey; - let peer = Peer.fromInbound(this.options, socket); + const cipher = BIP151.ciphers.CHACHAPOLY; + const identity = this.options.identityKey; + const peer = Peer.fromInbound(this.options, socket); if (this.options.bip151) peer.setCipher(cipher); @@ -1158,7 +1158,7 @@ Pool.prototype.createInbound = function createInbound(socket) { */ Pool.prototype.uid = function uid() { - let MAX = Number.MAX_SAFE_INTEGER; + const MAX = Number.MAX_SAFE_INTEGER; if (this.id >= MAX - this.peers.size() - 1) this.id = 0; @@ -1350,7 +1350,7 @@ Pool.prototype.handleConnect = async function handleConnect(peer) { Pool.prototype.handleOpen = async function handleOpen(peer) { // Advertise our address. if (!this.options.selfish && this.options.listen) { - let addr = this.hosts.getLocal(peer.address); + const addr = this.hosts.getLocal(peer.address); if (addr) peer.send(new packets.AddrPacket([addr])); } @@ -1409,9 +1409,9 @@ Pool.prototype.handleOpen = async function handleOpen(peer) { */ Pool.prototype.handleClose = async function handleClose(peer, connected) { - let outbound = peer.outbound; - let loader = peer.loader; - let size = peer.blockMap.size; + const outbound = peer.outbound; + const loader = peer.loader; + const size = peer.blockMap.size; this.removePeer(peer); @@ -1524,7 +1524,7 @@ Pool.prototype.handlePong = async function handlePong(peer, packet) { */ Pool.prototype.handleGetAddr = async function handleGetAddr(peer, packet) { - let items = []; + const items = []; let addrs; if (this.options.selfish) @@ -1541,7 +1541,7 @@ Pool.prototype.handleGetAddr = async function handleGetAddr(peer, packet) { addrs = this.hosts.toArray(); - for (let addr of addrs) { + for (const addr of addrs) { if (!peer.addrFilter.added(addr.hostname, 'ascii')) continue; @@ -1571,11 +1571,11 @@ Pool.prototype.handleGetAddr = async function handleGetAddr(peer, packet) { */ Pool.prototype.handleAddr = async function handleAddr(peer, packet) { - let addrs = packet.items; - let now = this.network.now(); - let services = this.options.getRequiredServices(); + const addrs = packet.items; + const now = this.network.now(); + const services = this.options.getRequiredServices(); - for (let addr of addrs) { + for (const addr of addrs) { peer.addrFilter.add(addr.hostname, 'ascii'); if (!addr.isRoutable()) @@ -1612,7 +1612,7 @@ Pool.prototype.handleAddr = async function handleAddr(peer, packet) { */ Pool.prototype.handleInv = async function handleInv(peer, packet) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._handleInv(peer, packet); } finally { @@ -1629,9 +1629,9 @@ Pool.prototype.handleInv = async function handleInv(peer, packet) { */ Pool.prototype._handleInv = async function handleInv(peer, packet) { - let items = packet.items; - let blocks = []; - let txs = []; + const items = packet.items; + const blocks = []; + const txs = []; let unknown = -1; if (items.length > 50000) { @@ -1639,7 +1639,7 @@ Pool.prototype._handleInv = async function handleInv(peer, packet) { return; } - for (let item of items) { + for (const item of items) { switch (item.type) { case invTypes.BLOCK: blocks.push(item.hash); @@ -1681,7 +1681,7 @@ Pool.prototype._handleInv = async function handleInv(peer, packet) { */ Pool.prototype.handleBlockInv = async function handleBlockInv(peer, hashes) { - let items = []; + const items = []; let hash, exists; assert(hashes.length > 0); @@ -1712,7 +1712,7 @@ Pool.prototype.handleBlockInv = async function handleBlockInv(peer, hashes) { peer.hostname()); for (let i = 0; i < hashes.length; i++) { - let hash = hashes[i]; + const hash = hashes[i]; // Resolve orphan chain. if (this.chain.hasOrphan(hash)) { @@ -1745,7 +1745,7 @@ Pool.prototype.handleBlockInv = async function handleBlockInv(peer, hashes) { // Attempt to update the peer's best height // with the last existing hash we know of. if (exists && this.chain.synced) { - let height = await this.chain.db.getHeight(exists); + const height = await this.chain.db.getHeight(exists); if (height !== -1) peer.bestHeight = height; } @@ -1779,8 +1779,8 @@ Pool.prototype.handleTXInv = async function handleTXInv(peer, hashes) { */ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { - let items = packet.items; - let notFound = []; + const items = packet.items; + const notFound = []; let txs = 0; let blocks = 0; let compact = 0; @@ -1793,9 +1793,9 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { return; } - for (let item of items) { + for (const item of items) { if (item.isTX()) { - let tx = await this.getItem(peer, item); + const tx = await this.getItem(peer, item); if (!tx) { notFound.push(item); @@ -1822,7 +1822,7 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { switch (item.type) { case invTypes.BLOCK: case invTypes.WITNESS_BLOCK: { - let result = await this.sendBlock(peer, item, item.hasWitness()); + const result = await this.sendBlock(peer, item, item.hasWitness()); if (!result) { notFound.push(item); continue; @@ -1858,7 +1858,7 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { peer.send(new packets.MerkleBlockPacket(block)); - for (let tx of block.txs) { + for (const tx of block.txs) { peer.send(new packets.TXPacket(tx, item.hasWitness())); txs++; } @@ -1868,12 +1868,12 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { break; } case invTypes.CMPCT_BLOCK: { - let height = await this.chain.db.getHeight(item.hash); + const height = await this.chain.db.getHeight(item.hash); let block; // Fallback to full block. if (height < this.chain.tip.height - 10) { - let result = await this.sendBlock(peer, item, peer.compactWitness); + const result = await this.sendBlock(peer, item, peer.compactWitness); if (!result) { notFound.push(item); continue; @@ -1945,9 +1945,9 @@ Pool.prototype.handleGetData = async function handleGetData(peer, packet) { */ Pool.prototype.handleNotFound = async function handleNotFound(peer, packet) { - let items = packet.items; + const items = packet.items; - for (let item of items) { + for (const item of items) { if (!this.resolveItem(peer, item)) { this.logger.warning( 'Peer sent notfound for unrequested item: %s (%s).', @@ -1967,7 +1967,7 @@ Pool.prototype.handleNotFound = async function handleNotFound(peer, packet) { */ Pool.prototype.handleGetBlocks = async function handleGetBlocks(peer, packet) { - let blocks = []; + const blocks = []; let hash; if (!this.chain.synced) @@ -2013,7 +2013,7 @@ Pool.prototype.handleGetBlocks = async function handleGetBlocks(peer, packet) { */ Pool.prototype.handleGetHeaders = async function handleGetHeaders(peer, packet) { - let headers = []; + const headers = []; let hash, entry; if (!this.chain.synced) @@ -2064,7 +2064,7 @@ Pool.prototype.handleGetHeaders = async function handleGetHeaders(peer, packet) */ Pool.prototype.handleHeaders = async function handleHeaders(peer, packet) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._handleHeaders(peer, packet); } finally { @@ -2083,7 +2083,7 @@ Pool.prototype.handleHeaders = async function handleHeaders(peer, packet) { */ Pool.prototype._handleHeaders = async function handleHeaders(peer, packet) { - let headers = packet.items; + const headers = packet.items; let checkpoint = false; let node; @@ -2106,10 +2106,10 @@ Pool.prototype._handleHeaders = async function handleHeaders(peer, packet) { assert(this.headerChain.size > 0); - for (let header of headers) { - let last = this.headerChain.tail; - let hash = header.hash('hex'); - let height = last.height + 1; + for (const header of headers) { + const last = this.headerChain.tail; + const hash = header.hash('hex'); + const height = last.height + 1; if (!header.verify()) { this.logger.warning( @@ -2210,7 +2210,7 @@ Pool.prototype.handleSendHeaders = async function handleSendHeaders(peer, packet */ Pool.prototype.handleBlock = async function handleBlock(peer, packet) { - let flags = chainCommon.flags.DEFAULT_FLAGS; + const flags = chainCommon.flags.DEFAULT_FLAGS; if (this.options.spv) { this.logger.warning( @@ -2232,8 +2232,8 @@ Pool.prototype.handleBlock = async function handleBlock(peer, packet) { */ Pool.prototype.addBlock = async function addBlock(peer, block, flags) { - let hash = block.hash('hex'); - let unlock = await this.locker.lock(hash); + const hash = block.hash('hex'); + const unlock = await this.locker.lock(hash); try { return await this._addBlock(peer, block, flags); } finally { @@ -2251,7 +2251,7 @@ Pool.prototype.addBlock = async function addBlock(peer, block, flags) { */ Pool.prototype._addBlock = async function addBlock(peer, block, flags) { - let hash = block.hash('hex'); + const hash = block.hash('hex'); let entry; if (!this.syncing) @@ -2328,7 +2328,7 @@ Pool.prototype._addBlock = async function addBlock(peer, block, flags) { */ Pool.prototype.resolveChain = async function resolveChain(peer, hash) { - let node = this.headerChain.head; + const node = this.headerChain.head; if (!this.checkpoints) return; @@ -2410,7 +2410,7 @@ Pool.prototype.switchSync = async function switchSync(peer, hash) { */ Pool.prototype.handleBadOrphan = function handleBadOrphan(msg, err, id) { - let peer = this.peers.find(id); + const peer = this.peers.find(id); if (!peer) { this.logger.warning( @@ -2466,8 +2466,8 @@ Pool.prototype.logStatus = function logStatus(block) { */ Pool.prototype.handleTX = async function handleTX(peer, packet) { - let hash = packet.tx.hash('hex'); - let unlock = await this.locker.lock(hash); + const hash = packet.tx.hash('hex'); + const unlock = await this.locker.lock(hash); try { return await this._handleTX(peer, packet); } finally { @@ -2485,10 +2485,10 @@ Pool.prototype.handleTX = async function handleTX(peer, packet) { */ Pool.prototype._handleTX = async function handleTX(peer, packet) { - let tx = packet.tx; - let hash = tx.hash('hex'); - let flags = chainCommon.flags.VERIFY_NONE; - let block = peer.merkleBlock; + const tx = packet.tx; + const hash = tx.hash('hex'); + const flags = chainCommon.flags.VERIFY_NONE; + const block = peer.merkleBlock; let missing; if (block) { @@ -2592,7 +2592,7 @@ Pool.prototype.handleReject = async function handleReject(peer, packet) { */ Pool.prototype.handleMempool = async function handleMempool(peer, packet) { - let items = []; + const items = []; if (!this.mempool) return; @@ -2611,7 +2611,7 @@ Pool.prototype.handleMempool = async function handleMempool(peer, packet) { return; } - for (let hash of this.mempool.map.keys()) + for (const hash of this.mempool.map.keys()) items.push(new InvItem(invTypes.TX, hash)); this.logger.debug( @@ -2666,8 +2666,8 @@ Pool.prototype.handleFilterClear = async function handleFilterClear(peer, packet */ Pool.prototype.handleMerkleBlock = async function handleMerkleBlock(peer, packet) { - let hash = packet.block.hash('hex'); - let unlock = await this.locker.lock(hash); + const hash = packet.block.hash('hex'); + const unlock = await this.locker.lock(hash); try { return await this._handleMerkleBlock(peer, packet); } finally { @@ -2684,9 +2684,9 @@ Pool.prototype.handleMerkleBlock = async function handleMerkleBlock(peer, packet */ Pool.prototype._handleMerkleBlock = async function handleMerkleBlock(peer, packet) { - let block = packet.block; - let hash = block.hash('hex'); - let flags = chainCommon.flags.VERIFY_NONE; + const block = packet.block; + const hash = block.hash('hex'); + const flags = chainCommon.flags.VERIFY_NONE; let tree; if (!this.syncing) @@ -2771,10 +2771,10 @@ Pool.prototype.handleSendCmpct = async function handleSendCmpct(peer, packet) { */ Pool.prototype.handleCmpctBlock = async function handleCmpctBlock(peer, packet) { - let block = packet.block; - let hash = block.hash('hex'); - let witness = peer.compactWitness; - let flags = chainCommon.flags.VERIFY_BODY; + const block = packet.block; + const hash = block.hash('hex'); + const witness = peer.compactWitness; + const flags = chainCommon.flags.VERIFY_BODY; let result; if (!this.syncing) @@ -2896,7 +2896,7 @@ Pool.prototype.handleCmpctBlock = async function handleCmpctBlock(peer, packet) */ Pool.prototype.handleGetBlockTxn = async function handleGetBlockTxn(peer, packet) { - let req = packet.request; + const req = packet.request; let res, item, block, height; if (this.chain.options.spv) @@ -2948,9 +2948,9 @@ Pool.prototype.handleGetBlockTxn = async function handleGetBlockTxn(peer, packet */ Pool.prototype.handleBlockTxn = async function handleBlockTxn(peer, packet) { - let res = packet.response; - let block = peer.compactBlocks.get(res.hash); - let flags = chainCommon.flags.VERIFY_BODY; + const res = packet.response; + const block = peer.compactBlocks.get(res.hash); + const flags = chainCommon.flags.VERIFY_BODY; if (!block) { this.logger.debug( @@ -3082,10 +3082,10 @@ Pool.prototype.addInbound = function addInbound(socket) { */ Pool.prototype.getHost = function getHost() { - let services = this.options.getRequiredServices(); - let now = this.network.now(); + const services = this.options.getRequiredServices(); + const now = this.network.now(); - for (let addr of this.hosts.nodes) { + for (const addr of this.hosts.nodes) { if (this.peers.has(addr.hostname)) continue; @@ -3093,7 +3093,7 @@ Pool.prototype.getHost = function getHost() { } for (let i = 0; i < 100; i++) { - let entry = this.hosts.getHost(); + const entry = this.hosts.getHost(); let addr; if (!entry) @@ -3164,7 +3164,7 @@ Pool.prototype.addOutbound = function addOutbound() { */ Pool.prototype.fillOutbound = function fillOutbound() { - let need = this.options.maxOutbound - this.peers.outbound; + const need = this.options.maxOutbound - this.peers.outbound; if (!this.peers.load) this.addLoader(); @@ -3204,13 +3204,13 @@ Pool.prototype.refill = function refill() { Pool.prototype.removePeer = function removePeer(peer) { this.peers.remove(peer); - for (let hash of peer.blockMap.keys()) + for (const hash of peer.blockMap.keys()) this.resolveBlock(peer, hash); - for (let hash of peer.txMap.keys()) + for (const hash of peer.txMap.keys()) this.resolveTX(peer, hash); - for (let hash of peer.compactBlocks.keys()) { + for (const hash of peer.compactBlocks.keys()) { assert(this.compactBlocks.has(hash)); this.compactBlocks.delete(hash); } @@ -3224,7 +3224,7 @@ Pool.prototype.removePeer = function removePeer(peer) { */ Pool.prototype.ban = function ban(addr) { - let peer = this.peers.get(addr.hostname); + const peer = this.peers.get(addr.hostname); this.logger.debug('Banning peer (%s).', addr.hostname); @@ -3321,7 +3321,7 @@ Pool.prototype.sendFilterLoad = function sendFilterLoad() { */ Pool.prototype.watchAddress = function watchAddress(address) { - let hash = Address.getHash(address); + const hash = Address.getHash(address); this.watch(hash); }; @@ -3344,8 +3344,8 @@ Pool.prototype.watchOutpoint = function watchOutpoint(outpoint) { */ Pool.prototype.resolveOrphan = async function resolveOrphan(peer, orphan) { - let locator = await this.chain.getLocator(); - let root = this.chain.getOrphanRoot(orphan); + const locator = await this.chain.getLocator(); + const root = this.chain.getOrphanRoot(orphan); assert(root); @@ -3362,7 +3362,7 @@ Pool.prototype.resolveOrphan = async function resolveOrphan(peer, orphan) { */ Pool.prototype.getHeaders = async function getHeaders(peer, tip, stop) { - let locator = await this.chain.getLocator(tip); + const locator = await this.chain.getLocator(tip); peer.sendGetHeaders(locator, stop); }; @@ -3376,7 +3376,7 @@ Pool.prototype.getHeaders = async function getHeaders(peer, tip, stop) { */ Pool.prototype.getBlocks = async function getBlocks(peer, tip, stop) { - let locator = await this.chain.getLocator(tip); + const locator = await this.chain.getLocator(tip); peer.sendGetBlocks(locator, stop); }; @@ -3388,7 +3388,7 @@ Pool.prototype.getBlocks = async function getBlocks(peer, tip, stop) { Pool.prototype.getBlock = function getBlock(peer, hashes) { let now = util.ms(); - let items = []; + const items = []; if (!this.loaded) return; @@ -3399,7 +3399,7 @@ Pool.prototype.getBlock = function getBlock(peer, hashes) { if (peer.destroyed) throw new Error('Peer is destroyed (getdata).'); - for (let hash of hashes) { + for (const hash of hashes) { if (this.blockMap.has(hash)) continue; @@ -3432,7 +3432,7 @@ Pool.prototype.getBlock = function getBlock(peer, hashes) { Pool.prototype.getTX = function getTX(peer, hashes) { let now = util.ms(); - let items = []; + const items = []; if (!this.loaded) return; @@ -3443,7 +3443,7 @@ Pool.prototype.getTX = function getTX(peer, hashes) { if (peer.destroyed) throw new Error('Peer is destroyed (getdata).'); - for (let hash of hashes) { + for (const hash of hashes) { if (this.txMap.has(hash)) continue; @@ -3525,9 +3525,9 @@ Pool.prototype.hasTX = function hasTX(hash) { */ Pool.prototype.ensureTX = function ensureTX(peer, hashes) { - let items = []; + const items = []; - for (let hash of hashes) { + for (const hash of hashes) { if (this.hasTX(hash)) continue; @@ -3599,7 +3599,7 @@ Pool.prototype.resolveItem = function resolveItem(peer, item) { */ Pool.prototype.broadcast = function broadcast(msg) { - let hash = msg.hash('hex'); + const hash = msg.hash('hex'); let item = this.invMap.get(hash); if (item) { @@ -3768,7 +3768,7 @@ PoolOptions.prototype.fromOptions = function fromOptions(options) { if (options.host != null) { assert(typeof options.host === 'string'); - let raw = IP.toBuffer(options.host); + const raw = IP.toBuffer(options.host); this.host = IP.toString(raw); if (IP.isRoutable(raw)) this.publicHost = this.host; @@ -4326,7 +4326,7 @@ BroadcastItem.prototype.cleanup = function cleanup() { BroadcastItem.prototype.reject = function reject(err) { this.cleanup(); - for (let job of this.jobs) + for (const job of this.jobs) job.reject(err); this.jobs.length = 0; @@ -4339,7 +4339,7 @@ BroadcastItem.prototype.reject = function reject(err) { BroadcastItem.prototype.resolve = function resolve() { this.cleanup(); - for (let job of this.jobs) + for (const job of this.jobs) job.resolve(false); this.jobs.length = 0; @@ -4354,7 +4354,7 @@ BroadcastItem.prototype.handleAck = function handleAck(peer) { setTimeout(() => { this.emit('ack', peer); - for (let job of this.jobs) + for (const job of this.jobs) job.resolve(true); this.jobs.length = 0; @@ -4369,7 +4369,7 @@ BroadcastItem.prototype.handleAck = function handleAck(peer) { BroadcastItem.prototype.handleReject = function handleReject(peer) { this.emit('reject', peer); - for (let job of this.jobs) + for (const job of this.jobs) job.resolve(false); this.jobs.length = 0; @@ -4381,8 +4381,8 @@ BroadcastItem.prototype.handleReject = function handleReject(peer) { */ BroadcastItem.prototype.inspect = function inspect() { - let type = this.type === invTypes.TX ? 'tx' : 'block'; - let hash = util.revHex(this.hash); + const type = this.type === invTypes.TX ? 'tx' : 'block'; + const hash = util.revHex(this.hash); return ``; }; @@ -4415,12 +4415,12 @@ NonceList.prototype.alloc = function alloc(hostname) { }; NonceList.prototype.has = function has(nonce) { - let key = nonce.toString('hex'); + const key = nonce.toString('hex'); return this.map.has(key); }; NonceList.prototype.remove = function remove(hostname) { - let key = this.hosts.get(hostname); + const key = this.hosts.get(hostname); if (!key) return false; diff --git a/lib/net/proxysocket.js b/lib/net/proxysocket.js index db4d6249b..c24647219 100644 --- a/lib/net/proxysocket.js +++ b/lib/net/proxysocket.js @@ -83,7 +83,7 @@ ProxySocket.prototype._init = function _init() { }); this.socket.on('tcp error', (e) => { - let err = new Error(e.message); + const err = new Error(e.message); err.code = e.code; this.emit('error', err); }); @@ -140,7 +140,7 @@ ProxySocket.prototype.connect = function connect(port, host) { this.socket.emit('tcp connect', port, host, nonce); - for (let chunk of this.sendBuffer) + for (const chunk of this.sendBuffer) this.write(chunk); this.sendBuffer.length = 0; @@ -185,12 +185,12 @@ ProxySocket.prototype.pause = function pause() { }; ProxySocket.prototype.resume = function resume() { - let recv = this.recvBuffer; + const recv = this.recvBuffer; this.paused = false; this.recvBuffer = []; - for (let data of recv) { + for (const data of recv) { this.bytesRead += data.length; this.emit('data', data); } @@ -204,7 +204,7 @@ ProxySocket.prototype.destroy = function destroy() { }; ProxySocket.connect = function connect(uri, port, host) { - let socket = new ProxySocket(uri); + const socket = new ProxySocket(uri); socket.connect(port, host); return socket; }; diff --git a/lib/net/socks.js b/lib/net/socks.js index e368fe062..ba35bbae1 100644 --- a/lib/net/socks.js +++ b/lib/net/socks.js @@ -111,7 +111,7 @@ SOCKS.prototype.destroy = function destroy() { SOCKS.prototype.startTimeout = function startTimeout() { this.timeout = setTimeout(() => { - let state = SOCKS.statesByVal[this.state]; + const state = SOCKS.statesByVal[this.state]; this.timeout = null; this.error('SOCKS request timed out (state=%s).', state); }, 8000); @@ -210,7 +210,7 @@ SOCKS.prototype.handleError = function handleError(err) { SOCKS.prototype.handleClose = function handleClose() { if (this.state !== this.target) { - let state = SOCKS.statesByVal[this.state]; + const state = SOCKS.statesByVal[this.state]; this.error('SOCKS request destroyed (state=%s).', state); return; } @@ -298,8 +298,8 @@ SOCKS.prototype.handleHandshake = function handleHandshake(data) { }; SOCKS.prototype.sendAuth = function sendAuth() { - let user = this.username; - let pass = this.password; + const user = this.username; + const pass = this.password; let ulen, plen, size, packet; if (!user) { @@ -364,8 +364,8 @@ SOCKS.prototype.auth = function auth() { }; SOCKS.prototype.sendProxy = function sendProxy() { - let host = this.destHost; - let port = this.destPort; + const host = this.destHost; + const port = this.destPort; let ip, len, type, name, packet; switch (IP.getStringType(host)) { @@ -421,7 +421,7 @@ SOCKS.prototype.handleProxy = function handleProxy(data) { } if (data[1] !== 0x00) { - let msg = this.getError(data[1]); + const msg = this.getError(data[1]); this.error('SOCKS connect error: %s.', msg); return; } @@ -447,8 +447,8 @@ SOCKS.prototype.handleProxy = function handleProxy(data) { }; SOCKS.prototype.sendResolve = function sendResolve() { - let name = this.name; - let len = Buffer.byteLength(name, 'utf8'); + const name = this.name; + const len = Buffer.byteLength(name, 'utf8'); let packet = new StaticWriter(7 + len); packet.writeU8(0x05); @@ -478,7 +478,7 @@ SOCKS.prototype.handleResolve = function handleResolve(data) { } if (data[1] !== 0x00) { - let msg = this.getError(data[1]); + const msg = this.getError(data[1]); this.error('Tor resolve error: %s (%s).', msg, this.name); return; } @@ -507,7 +507,7 @@ SOCKS.prototype.handleResolve = function handleResolve(data) { }; SOCKS.resolve = function resolve(options) { - let socks = new SOCKS(); + const socks = new SOCKS(); return new Promise((resolve, reject) => { socks.resolve(options); socks.on('resolve', resolve); @@ -516,7 +516,7 @@ SOCKS.resolve = function resolve(options) { }; SOCKS.proxy = function proxy(options) { - let socks = new SOCKS(); + const socks = new SOCKS(); return new Promise((resolve, reject) => { socks.proxy(options); socks.on('proxy', resolve); @@ -602,7 +602,7 @@ Proxy.prototype.connect = async function connect(port, host) { this.emit('timeout'); }); - for (let op of this.ops) + for (const op of this.ops) op.call(this); this.ops.length = 0; @@ -672,11 +672,11 @@ Proxy.prototype.destroy = function destroy() { */ function parseProxy(host) { - let index = host.indexOf('@'); + const index = host.indexOf('@'); let addr, left, right, parts; if (index === -1) { - let addr = IP.fromHostname(host, 1080); + const addr = IP.fromHostname(host, 1080); return { host: addr.host, port: addr.port @@ -700,7 +700,7 @@ function parseProxy(host) { } function parseAddr(data, offset) { - let br = new BufferReader(data); + const br = new BufferReader(data); let type, len, host, port; if (br.left() < offset + 2) @@ -750,11 +750,11 @@ function parseAddr(data, offset) { */ exports.connect = function connect(proxy, destPort, destHost) { - let addr = parseProxy(proxy); - let host = addr.host; - let port = addr.port; - let user = addr.username; - let pass = addr.password; + const addr = parseProxy(proxy); + const host = addr.host; + const port = addr.port; + const user = addr.username; + const pass = addr.password; let socket; socket = new Proxy(host, port, user, pass); @@ -764,7 +764,7 @@ exports.connect = function connect(proxy, destPort, destHost) { }; exports.resolve = function resolve(proxy, name) { - let addr = parseProxy(proxy); + const addr = parseProxy(proxy); return SOCKS.resolve({ host: addr.host, port: addr.port, diff --git a/lib/net/tcp-browser.js b/lib/net/tcp-browser.js index 1bff94263..4bdd7644d 100644 --- a/lib/net/tcp-browser.js +++ b/lib/net/tcp-browser.js @@ -15,7 +15,7 @@ tcp.createSocket = function createSocket(port, host, proxy) { }; tcp.createServer = function createServer() { - let server = new EventEmitter(); + const server = new EventEmitter(); server.listen = async function listen(port, host) { server.emit('listening'); diff --git a/lib/net/tcp.js b/lib/net/tcp.js index f2c1b558e..7a2512ea3 100644 --- a/lib/net/tcp.js +++ b/lib/net/tcp.js @@ -36,8 +36,8 @@ tcp.createSocket = function createSocket(port, host, proxy) { */ tcp.createServer = function createServer() { - let server = new net.Server(); - let ee = new EventEmitter(); + const server = new net.Server(); + const ee = new EventEmitter(); ee.listen = function listen(port, host) { return new Promise((resolve, reject) => { diff --git a/lib/net/upnp.js b/lib/net/upnp.js index c38a6bf77..a99d61ffe 100644 --- a/lib/net/upnp.js +++ b/lib/net/upnp.js @@ -69,7 +69,7 @@ UPNP.RESPONSE_TIMEOUT = 1000; */ UPNP.prototype.cleanupJob = function cleanupJob() { - let job = this.job; + const job = this.job; assert(this.socket); assert(this.job); @@ -91,7 +91,7 @@ UPNP.prototype.cleanupJob = function cleanupJob() { */ UPNP.prototype.rejectJob = function rejectJob(err) { - let job = this.cleanupJob(); + const job = this.cleanupJob(); job.reject(err); }; @@ -102,7 +102,7 @@ UPNP.prototype.rejectJob = function rejectJob(err) { */ UPNP.prototype.resolveJob = function resolveJob(result) { - let job = this.cleanupJob(); + const job = this.cleanupJob(); job.resolve(result); }; @@ -137,7 +137,7 @@ UPNP.prototype.stopTimeout = function stopTimeout() { */ UPNP.prototype.discover = async function discover() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._discover(); } finally { @@ -152,7 +152,7 @@ UPNP.prototype.discover = async function discover() { */ UPNP.prototype._discover = async function discover() { - let socket = dgram.createSocket('udp4'); + const socket = dgram.createSocket('udp4'); let msg; socket.on('error', (err) => { @@ -160,7 +160,7 @@ UPNP.prototype._discover = async function discover() { }); socket.on('message', (data, rinfo) => { - let msg = data.toString('utf8'); + const msg = data.toString('utf8'); this.handleMsg(msg); }); @@ -217,7 +217,7 @@ UPNP.prototype.handleMsg = async function handleMsg(msg) { */ UPNP.prototype.resolve = async function resolve(location, targets) { - let host = parseHost(location); + const host = parseHost(location); let res, xml, services, service; if (!targets) @@ -261,8 +261,8 @@ UPNP.prototype.resolve = async function resolve(location, targets) { */ UPNP.parseHeader = function parseHeader(str) { - let lines = str.split(/\r?\n/); - let headers = Object.create(null); + const lines = str.split(/\r?\n/); + const headers = Object.create(null); for (let line of lines) { let index, left, right; @@ -304,9 +304,9 @@ UPNP.parseHeader = function parseHeader(str) { */ UPNP.discover = async function discover(host, port, gateway, targets) { - let upnp = new UPNP(host, port, gateway); - let location = await upnp.discover(); - let service = await upnp.resolve(location, targets); + const upnp = new UPNP(host, port, gateway); + const location = await upnp.discover(); + const service = await upnp.resolve(location, targets); return new UPNPService(service); }; @@ -337,10 +337,10 @@ function UPNPService(options) { */ UPNPService.prototype.createRequest = function createRequest(action, args) { - let type = JSON.stringify(this.serviceType); + const type = JSON.stringify(this.serviceType); let params = ''; - for (let [key, value] of args) { + for (const [key, value] of args) { params += `<${key}>`; if (value != null) params += value; @@ -369,8 +369,8 @@ UPNPService.prototype.createRequest = function createRequest(action, args) { */ UPNPService.prototype.soapRequest = async function soapRequest(action, args) { - let type = this.serviceType; - let req = this.createRequest(action, args); + const type = this.serviceType; + const req = this.createRequest(action, args); let res, xml, err; res = await request({ @@ -402,9 +402,9 @@ UPNPService.prototype.soapRequest = async function soapRequest(action, args) { */ UPNPService.prototype.getExternalIP = async function getExternalIP() { - let action = 'GetExternalIPAddress'; - let xml = await this.soapRequest(action, []); - let ip = findIP(xml); + const action = 'GetExternalIPAddress'; + const xml = await this.soapRequest(action, []); + const ip = findIP(xml); if (!ip) throw new Error('Could not find external IP.'); @@ -421,8 +421,8 @@ UPNPService.prototype.getExternalIP = async function getExternalIP() { */ UPNPService.prototype.addPortMapping = async function addPortMapping(remote, src, dest) { - let action = 'AddPortMapping'; - let local = IP.getPrivate(); + const action = 'AddPortMapping'; + const local = IP.getPrivate(); let xml, child; if (local.length === 0) @@ -455,7 +455,7 @@ UPNPService.prototype.addPortMapping = async function addPortMapping(remote, src */ UPNPService.prototype.removePortMapping = async function removePortMapping(remote, port) { - let action = 'DeletePortMapping'; + const action = 'DeletePortMapping'; let xml, child; xml = await this.soapRequest(action, [ @@ -492,9 +492,9 @@ function XMLElement(name) { */ XMLElement.fromRaw = function fromRaw(xml) { - let sentinel = new XMLElement(''); + const sentinel = new XMLElement(''); let current = sentinel; - let stack = []; + const stack = []; let decl = false; let m; @@ -510,9 +510,9 @@ XMLElement.fromRaw = function fromRaw(xml) { } if (m = /^<([\w:]+)[^<>]*?(\/?)>/i.exec(xml)) { - let name = m[1]; - let trailing = m[2] === '/'; - let element = new XMLElement(name); + const name = m[1]; + const trailing = m[2] === '/'; + const element = new XMLElement(name); xml = xml.substring(m[0].length); @@ -529,7 +529,7 @@ XMLElement.fromRaw = function fromRaw(xml) { } if (m = /^<\/([\w:]+)[^<>]*>/i.exec(xml)) { - let name = m[1]; + const name = m[1]; let element; xml = xml.substring(m[0].length); @@ -547,7 +547,7 @@ XMLElement.fromRaw = function fromRaw(xml) { } if (m = /^([^<]+)/i.exec(xml)) { - let text = m[1]; + const text = m[1]; xml = xml.substring(m[0].length); current.text = text.trim(); continue; @@ -590,7 +590,7 @@ XMLElement.prototype.collect = function collect(name) { */ XMLElement.prototype._collect = function _collect(name, result) { - for (let child of this.children) { + for (const child of this.children) { if (child.type === name) { result.push(child); continue; @@ -625,19 +625,19 @@ XMLElement.prototype.find = function find(name) { */ function parseServices(el) { - let children = el.collect('service'); - let services = []; + const children = el.collect('service'); + const services = []; - for (let child of children) + for (const child of children) services.push(parseService(child)); return services; } function parseService(el) { - let service = Object.create(null); + const service = Object.create(null); - for (let child of el.children) { + for (const child of el.children) { if (child.children.length > 0) continue; @@ -648,22 +648,22 @@ function parseService(el) { } function findService(services, name) { - for (let service of services) { + for (const service of services) { if (service.serviceType === name) return service; } } function extractServices(services, targets) { - for (let name of targets) { - let service = findService(services, name); + for (const name of targets) { + const service = findService(services, name); if (service) return service; } } function findIP(el) { - let child = el.find('NewExternalIPAddress'); + const child = el.find('NewExternalIPAddress'); if (!child) return; @@ -672,7 +672,7 @@ function findIP(el) { } function findError(el) { - let child = el.find('UPnPError'); + const child = el.find('UPnPError'); let code = -1; let desc = 'Unknown'; let ccode, cdesc; @@ -697,7 +697,7 @@ function findError(el) { */ function parseHost(uri) { - let {protocol, host} = url.parse(uri); + const {protocol, host} = url.parse(uri); assert(protocol === 'http:' || protocol === 'https:', 'Bad URL for location.'); diff --git a/lib/node/config.js b/lib/node/config.js index 0f45ae91a..87b161205 100644 --- a/lib/node/config.js +++ b/lib/node/config.js @@ -63,8 +63,8 @@ Config.alias = { */ Config.prototype.inject = function inject(options) { - for (let key of Object.keys(options)) { - let value = options[key]; + for (const key of Object.keys(options)) { + const value = options[key]; switch (key) { case 'hash': @@ -200,7 +200,7 @@ Config.prototype.get = function get(key, fallback) { if (Array.isArray(key)) { keys = key; - for (let key of keys) { + for (const key of keys) { value = this.get(key); if (value !== null) return value; @@ -248,7 +248,7 @@ Config.prototype.get = function get(key, fallback) { */ Config.prototype.str = function str(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -374,7 +374,7 @@ Config.prototype.amt = function amt(key, fallback) { */ Config.prototype.bool = function bool(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -405,7 +405,7 @@ Config.prototype.bool = function bool(key, fallback) { */ Config.prototype.buf = function buf(key, fallback) { - let value = this.get(key); + const value = this.get(key); let data; if (fallback === undefined) @@ -436,7 +436,7 @@ Config.prototype.buf = function buf(key, fallback) { */ Config.prototype.array = function array(key, fallback) { - let value = this.get(key); + const value = this.get(key); let result, parts; if (fallback === undefined) @@ -454,7 +454,7 @@ Config.prototype.array = function array(key, fallback) { parts = value.trim().split(/\s*,\s*/); result = []; - for (let part of parts) { + for (const part of parts) { if (part.length === 0) continue; @@ -472,7 +472,7 @@ Config.prototype.array = function array(key, fallback) { */ Config.prototype.obj = function obj(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -494,7 +494,7 @@ Config.prototype.obj = function obj(key, fallback) { */ Config.prototype.func = function func(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -546,7 +546,7 @@ Config.prototype.path = function _path(key, fallback) { */ Config.prototype.mb = function mb(key, fallback) { - let value = this.num(key); + const value = this.num(key); if (fallback === undefined) fallback = null; @@ -610,7 +610,7 @@ Config.prototype.getPrefix = function getPrefix() { */ Config.prototype.getFile = function getFile(file) { - let name = this.str('config'); + const name = this.str('config'); if (name) return name; @@ -881,8 +881,8 @@ Config.prototype.parseForm = function parseForm(query, map) { parts = query.split('&'); - for (let pair of parts) { - let index = pair.indexOf('='); + for (const pair of parts) { + const index = pair.indexOf('='); let key, value, alias; if (index === -1) { diff --git a/lib/node/fullnode.js b/lib/node/fullnode.js index 1e2369723..852c5688c 100644 --- a/lib/node/fullnode.js +++ b/lib/node/fullnode.js @@ -380,7 +380,7 @@ FullNode.prototype.getBlock = function getBlock(hash) { */ FullNode.prototype.getCoin = function getCoin(hash, index) { - let coin = this.mempool.getCoin(hash, index); + const coin = this.mempool.getCoin(hash, index); if (coin) return Promise.resolve(coin); @@ -399,12 +399,12 @@ FullNode.prototype.getCoin = function getCoin(hash, index) { */ FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { - let mempool = this.mempool.getCoinsByAddress(addrs); - let chain = await this.chain.db.getCoinsByAddress(addrs); - let out = []; + const mempool = this.mempool.getCoinsByAddress(addrs); + const chain = await this.chain.db.getCoinsByAddress(addrs); + const out = []; - for (let coin of chain) { - let spent = this.mempool.isSpent(coin.hash, coin.index); + for (const coin of chain) { + const spent = this.mempool.isSpent(coin.hash, coin.index); if (spent) continue; @@ -412,7 +412,7 @@ FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { out.push(coin); } - for (let coin of mempool) + for (const coin of mempool) out.push(coin); return out; @@ -426,8 +426,8 @@ FullNode.prototype.getCoinsByAddress = async function getCoinsByAddress(addrs) { */ FullNode.prototype.getMetaByAddress = async function getTXByAddress(addrs) { - let mempool = this.mempool.getMetaByAddress(addrs); - let chain = await this.chain.db.getMetaByAddress(addrs); + const mempool = this.mempool.getMetaByAddress(addrs); + const chain = await this.chain.db.getMetaByAddress(addrs); return chain.concat(mempool); }; @@ -438,7 +438,7 @@ FullNode.prototype.getMetaByAddress = async function getTXByAddress(addrs) { */ FullNode.prototype.getMeta = async function getMeta(hash) { - let meta = this.mempool.getMeta(hash); + const meta = this.mempool.getMeta(hash); if (meta) return meta; @@ -466,10 +466,10 @@ FullNode.prototype.getMetaView = async function getMetaView(meta) { */ FullNode.prototype.getTXByAddress = async function getTXByAddress(addrs) { - let mtxs = await this.getMetaByAddress(addrs); - let out = []; + const mtxs = await this.getMetaByAddress(addrs); + const out = []; - for (let mtx of mtxs) + for (const mtx of mtxs) out.push(mtx.tx); return out; @@ -482,7 +482,7 @@ FullNode.prototype.getTXByAddress = async function getTXByAddress(addrs) { */ FullNode.prototype.getTX = async function getTX(hash) { - let mtx = await this.getMeta(hash); + const mtx = await this.getMeta(hash); if (!mtx) return; return mtx.tx; diff --git a/lib/node/logger.js b/lib/node/logger.js index 569dc33aa..8f1d047ad 100644 --- a/lib/node/logger.js +++ b/lib/node/logger.js @@ -161,7 +161,7 @@ Logger.prototype.set = function set(options) { */ Logger.prototype.open = async function open() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._open(); } finally { @@ -206,7 +206,7 @@ Logger.prototype._open = async function open() { */ Logger.prototype.close = async function close() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._close(); } finally { @@ -253,7 +253,7 @@ Logger.prototype._close = async function close() { */ Logger.prototype.truncate = async function truncate() { - let maxSize = Logger.MAX_FILE_SIZE; + const maxSize = Logger.MAX_FILE_SIZE; let stat, data, fd; if (!this.filename) @@ -310,7 +310,7 @@ Logger.prototype.handleError = function handleError(err) { */ Logger.prototype.reopen = async function reopen() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._reopen(); } finally { @@ -377,7 +377,7 @@ Logger.prototype.setFile = function setFile(filename) { */ Logger.prototype.setLevel = function setLevel(name) { - let level = Logger.levels[name.toUpperCase()]; + const level = Logger.levels[name.toUpperCase()]; assert(level != null, 'Invalid log level.'); this.level = level; }; @@ -389,7 +389,7 @@ Logger.prototype.setLevel = function setLevel(name) { */ Logger.prototype.error = function error(...args) { - let err = args[0]; + const err = args[0]; if (this.level < Logger.levels.ERROR) return; @@ -407,7 +407,7 @@ Logger.prototype.error = function error(...args) { */ Logger.prototype.warning = function warning(...args) { - let err = args[0]; + const err = args[0]; if (this.level < Logger.levels.WARNING) return; @@ -425,7 +425,7 @@ Logger.prototype.warning = function warning(...args) { */ Logger.prototype.info = function info(...args) { - let err = args[0]; + const err = args[0]; if (this.level < Logger.levels.INFO) return; @@ -443,7 +443,7 @@ Logger.prototype.info = function info(...args) { */ Logger.prototype.debug = function debug(...args) { - let err = args[0]; + const err = args[0]; if (this.level < Logger.levels.DEBUG) return; @@ -461,7 +461,7 @@ Logger.prototype.debug = function debug(...args) { */ Logger.prototype.spam = function spam(...args) { - let err = args[0]; + const err = args[0]; if (this.level < Logger.levels.SPAM) return; @@ -516,7 +516,7 @@ Logger.prototype.context = function _context(module) { */ Logger.prototype.writeConsole = function writeConsole(level, module, args) { - let name = Logger.levelsByVal[level]; + const name = Logger.levelsByVal[level]; let msg = ''; let color; @@ -572,7 +572,7 @@ Logger.prototype.writeConsole = function writeConsole(level, module, args) { */ Logger.prototype.writeStream = function writeStream(level, module, args) { - let name = Logger.prefixByVal[level]; + const name = Logger.prefixByVal[level]; let msg = ''; assert(name, 'Invalid log level.'); @@ -633,7 +633,7 @@ Logger.prototype.logError = function logError(level, module, err) { */ Logger.prototype.memory = function memory(module) { - let mem = util.memoryUsage(); + const mem = util.memoryUsage(); this.log(Logger.levels.DEBUG, module, [ 'Memory: rss=%dmb, js-heap=%d/%dmb native-heap=%dmb', @@ -705,7 +705,7 @@ LoggerContext.prototype.setLevel = function setLevel(name) { */ LoggerContext.prototype.error = function error(...args) { - let err = args[0]; + const err = args[0]; if (this.logger.level < Logger.levels.ERROR) return; @@ -723,7 +723,7 @@ LoggerContext.prototype.error = function error(...args) { */ LoggerContext.prototype.warning = function warning(...args) { - let err = args[0]; + const err = args[0]; if (this.logger.level < Logger.levels.WARNING) return; @@ -741,7 +741,7 @@ LoggerContext.prototype.warning = function warning(...args) { */ LoggerContext.prototype.info = function info(...args) { - let err = args[0]; + const err = args[0]; if (this.logger.level < Logger.levels.INFO) return; @@ -759,7 +759,7 @@ LoggerContext.prototype.info = function info(...args) { */ LoggerContext.prototype.debug = function debug(...args) { - let err = args[0]; + const err = args[0]; if (this.logger.level < Logger.levels.DEBUG) return; @@ -777,7 +777,7 @@ LoggerContext.prototype.debug = function debug(...args) { */ LoggerContext.prototype.spam = function spam(...args) { - let err = args[0]; + const err = args[0]; if (this.logger.level < Logger.levels.SPAM) return; @@ -841,9 +841,9 @@ Logger.global = new Logger(); function openStream(filename) { return new Promise((resolve, reject) => { - let stream = fs.createWriteStream(filename, { flags: 'a' }); + const stream = fs.createWriteStream(filename, { flags: 'a' }); - let onError = (err) => { + const onError = (err) => { try { stream.close(); } catch (e) { @@ -853,7 +853,7 @@ function openStream(filename) { reject(err); }; - let onOpen = () => { + const onOpen = () => { cleanup(); resolve(stream); }; @@ -870,12 +870,12 @@ function openStream(filename) { function closeStream(stream) { return new Promise((resolve, reject) => { - let onError = (err) => { + const onError = (err) => { cleanup(); reject(err); }; - let onClose = () => { + const onClose = () => { cleanup(); resolve(stream); }; diff --git a/lib/node/node.js b/lib/node/node.js index aa6181dc7..7f11f8ebb 100644 --- a/lib/node/node.js +++ b/lib/node/node.js @@ -69,7 +69,7 @@ util.inherits(Node, AsyncObject); Node.prototype.initOptions = function initOptions() { let logger = new Logger(); - let config = this.config; + const config = this.config; if (config.has('logger')) logger = config.obj('logger'); @@ -214,7 +214,7 @@ Node.prototype.handlePreclose = async function handlePreclose() { */ Node.prototype.handleClose = async function handleClose() { - for (let [obj, event, listener] of this.bound) + for (const [obj, event, listener] of this.bound) obj.removeListener(event, listener); this.bound.length = 0; @@ -365,7 +365,7 @@ Node.prototype.get = function get(name) { */ Node.prototype.require = function require(name) { - let plugin = this.get(name); + const plugin = this.get(name); assert(plugin, `${name} is not loaded.`); return plugin; }; @@ -376,8 +376,8 @@ Node.prototype.require = function require(name) { */ Node.prototype.loadPlugins = function loadPlugins() { - let plugins = this.config.array('plugins', []); - let loader = this.config.func('loader'); + const plugins = this.config.array('plugins', []); + const loader = this.config.func('loader'); for (let plugin of plugins) { if (typeof plugin === 'string') { @@ -394,7 +394,7 @@ Node.prototype.loadPlugins = function loadPlugins() { */ Node.prototype.openPlugins = async function openPlugins() { - for (let plugin of this.stack) { + for (const plugin of this.stack) { if (plugin.open) await plugin.open(); } @@ -406,7 +406,7 @@ Node.prototype.openPlugins = async function openPlugins() { */ Node.prototype.closePlugins = async function closePlugins() { - for (let plugin of this.stack) { + for (const plugin of this.stack) { if (plugin.close) await plugin.close(); } diff --git a/lib/node/spvnode.js b/lib/node/spvnode.js index 8401fec88..8275bc5bd 100644 --- a/lib/node/spvnode.js +++ b/lib/node/spvnode.js @@ -199,8 +199,8 @@ SPVNode.prototype._close = async function close() { */ SPVNode.prototype.scan = async function scan(start, filter, iter) { - let unlock = await this.scanLock.lock(); - let height = this.chain.height; + const unlock = await this.scanLock.lock(); + const height = this.chain.height; try { await this.chain.replay(start); @@ -237,7 +237,7 @@ SPVNode.prototype.watchUntil = function watchUntil(height, iter) { */ SPVNode.prototype.watchBlock = async function watchBlock(entry, block) { - let unlock = await this.watchLock.lock(); + const unlock = await this.watchLock.lock(); try { if (entry.height < this.rescanJob.height) { await this.rescanJob.iter(entry, block.txs); diff --git a/lib/primitives/address.js b/lib/primitives/address.js index 43c187d03..eb6ebdd45 100644 --- a/lib/primitives/address.js +++ b/lib/primitives/address.js @@ -183,9 +183,9 @@ Address.prototype.getSize = function getSize() { */ Address.prototype.toRaw = function toRaw(network) { - let size = this.getSize(); - let bw = new StaticWriter(size); - let prefix = this.getPrefix(network); + const size = this.getSize(); + const bw = new StaticWriter(size); + const prefix = this.getPrefix(network); assert(prefix !== -1, 'Not a valid address prefix.'); @@ -221,8 +221,8 @@ Address.prototype.toBase58 = function toBase58(network) { */ Address.prototype.toBech32 = function toBech32(network) { - let version = this.version; - let hash = this.hash; + const version = this.version; + const hash = this.hash; let hrp; assert(version !== -1, @@ -307,7 +307,7 @@ Address.prototype.inspect = function inspect() { */ Address.prototype.fromRaw = function fromRaw(data, network) { - let br = new BufferReader(data, true); + const br = new BufferReader(data, true); let version = -1; let prefix, type, hash; @@ -381,7 +381,7 @@ Address.fromBase58 = function fromBase58(data, network) { */ Address.prototype.fromBech32 = function fromBech32(data, network) { - let type = Address.types.WITNESS; + const type = Address.types.WITNESS; let addr; assert(typeof data === 'string'); @@ -623,7 +623,7 @@ Address.fromHash = function fromHash(hash, type, version, network) { */ Address.prototype.fromPubkeyhash = function fromPubkeyhash(hash, network) { - let type = Address.types.PUBKEYHASH; + const type = Address.types.PUBKEYHASH; assert(hash.length === 20, 'P2PKH must be 20 bytes.'); return this.fromHash(hash, type, -1, network); }; @@ -648,7 +648,7 @@ Address.fromPubkeyhash = function fromPubkeyhash(hash, network) { */ Address.prototype.fromScripthash = function fromScripthash(hash, network) { - let type = Address.types.SCRIPTHASH; + const type = Address.types.SCRIPTHASH; assert(hash && hash.length === 20, 'P2SH must be 20 bytes.'); return this.fromHash(hash, type, -1, network); }; @@ -673,7 +673,7 @@ Address.fromScripthash = function fromScripthash(hash, network) { */ Address.prototype.fromWitnessPubkeyhash = function fromWitnessPubkeyhash(hash, network) { - let type = Address.types.WITNESS; + const type = Address.types.WITNESS; assert(hash && hash.length === 20, 'P2WPKH must be 20 bytes.'); return this.fromHash(hash, type, 0, network); }; @@ -698,7 +698,7 @@ Address.fromWitnessPubkeyhash = function fromWitnessPubkeyhash(hash, network) { */ Address.prototype.fromWitnessScripthash = function fromWitnessScripthash(hash, network) { - let type = Address.types.WITNESS; + const type = Address.types.WITNESS; assert(hash && hash.length === 32, 'P2WPKH must be 32 bytes.'); return this.fromHash(hash, type, 0, network); }; @@ -724,7 +724,7 @@ Address.fromWitnessScripthash = function fromWitnessScripthash(hash, network) { */ Address.prototype.fromProgram = function fromProgram(version, hash, network) { - let type = Address.types.WITNESS; + const type = Address.types.WITNESS; assert(version >= 0, 'Bad version for witness program.'); @@ -862,7 +862,7 @@ Address.getHash = function getHash(data, enc, network) { */ Address.getType = function getType(prefix, network) { - let prefixes = network.addressPrefix; + const prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: return Address.types.PUBKEYHASH; @@ -885,7 +885,7 @@ function isMixedCase(str) { let upper = false; for (let i = 0; i < str.length; i++) { - let ch = str.charCodeAt(i); + const ch = str.charCodeAt(i); if (ch >= 0x30 && ch <= 0x39) continue; diff --git a/lib/primitives/block.js b/lib/primitives/block.js index caf144447..6410f3f61 100644 --- a/lib/primitives/block.js +++ b/lib/primitives/block.js @@ -58,7 +58,7 @@ Block.prototype.fromOptions = function fromOptions(options) { if (options.txs) { assert(Array.isArray(options.txs)); - for (let tx of options.txs) { + for (const tx of options.txs) { assert(tx instanceof TX); this.txs.push(tx); } @@ -90,7 +90,7 @@ Block.prototype.refresh = function refresh(all) { if (!all) return; - for (let tx of this.txs) + for (const tx of this.txs) tx.refresh(); }; @@ -193,7 +193,7 @@ Block.prototype.getSizes = function getSizes() { */ Block.prototype.getVirtualSize = function getVirtualSize() { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; return (this.getWeight() + scale - 1) / scale | 0; }; @@ -203,8 +203,8 @@ Block.prototype.getVirtualSize = function getVirtualSize() { */ Block.prototype.getWeight = function getWeight() { - let raw = this.getSizes(); - let base = raw.size - raw.witness; + const raw = this.getSizes(); + const base = raw.size - raw.witness; return base * (consensus.WITNESS_SCALE_FACTOR - 1) + raw.size; }; @@ -223,7 +223,7 @@ Block.prototype.getSize = function getSize() { */ Block.prototype.getBaseSize = function getBaseSize() { - let raw = this.getSizes(); + const raw = this.getSizes(); return raw.size - raw.witness; }; @@ -237,7 +237,7 @@ Block.prototype.hasWitness = function hasWitness() { if (this._witness !== -1) return this._witness !== 0; - for (let tx of this.txs) { + for (const tx of this.txs) { if (tx.hasWitness()) return true; } @@ -263,7 +263,7 @@ Block.prototype.hasTX = function hasTX(hash) { Block.prototype.indexOf = function indexOf(hash) { for (let i = 0; i < this.txs.length; i++) { - let tx = this.txs[i]; + const tx = this.txs[i]; if (tx.hash('hex') === hash) return i; } @@ -279,10 +279,10 @@ Block.prototype.indexOf = function indexOf(hash) { */ Block.prototype.createMerkleRoot = function createMerkleRoot(enc) { - let leaves = []; + const leaves = []; let root, malleated; - for (let tx of this.txs) + for (const tx of this.txs) leaves.push(tx.hash()); [root, malleated] = merkle.createRoot(leaves); @@ -310,8 +310,8 @@ Block.prototype.createWitnessNonce = function createWitnessNonce() { */ Block.prototype.createCommitmentHash = function createCommitmentHash(enc) { - let nonce = this.getWitnessNonce(); - let leaves = []; + const nonce = this.getWitnessNonce(); + const leaves = []; let root, hash; assert(nonce, 'No witness nonce present.'); @@ -319,7 +319,7 @@ Block.prototype.createCommitmentHash = function createCommitmentHash(enc) { leaves.push(encoding.ZERO_HASH); for (let i = 1; i < this.txs.length; i++) { - let tx = this.txs[i]; + const tx = this.txs[i]; leaves.push(tx.witnessHash()); } @@ -391,7 +391,7 @@ Block.prototype.getCommitmentHash = function getCommitmentHash(enc) { coinbase = this.txs[0]; for (let i = coinbase.outputs.length - 1; i >= 0; i--) { - let output = coinbase.outputs[i]; + const output = coinbase.outputs[i]; if (output.script.isCommitment()) { hash = output.script.getCommitmentHash(); break; @@ -413,7 +413,7 @@ Block.prototype.getCommitmentHash = function getCommitmentHash(enc) { */ Block.prototype.verifyBody = function verifyBody() { - let [valid] = this.checkBody(); + const [valid] = this.checkBody(); return valid; }; @@ -425,7 +425,7 @@ Block.prototype.verifyBody = function verifyBody() { Block.prototype.checkBody = function checkBody() { let sigops = 0; - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; let root; // Check merkle root. @@ -452,7 +452,7 @@ Block.prototype.checkBody = function checkBody() { // Test all transactions. for (let i = 0; i < this.txs.length; i++) { - let tx = this.txs[i]; + const tx = this.txs[i]; let valid, reason, score; // The rest of the txs must not be coinbases. @@ -514,12 +514,12 @@ Block.prototype.getClaimed = function getClaimed() { */ Block.prototype.getPrevout = function getPrevout() { - let prevout = Object.create(null); + const prevout = Object.create(null); for (let i = 1; i < this.txs.length; i++) { - let tx = this.txs[i]; + const tx = this.txs[i]; - for (let input of tx.inputs) + for (const input of tx.inputs) prevout[input.prevout.hash] = true; } @@ -545,7 +545,7 @@ Block.prototype.inspect = function inspect() { */ Block.prototype.format = function format(view, height) { - let commitmentHash = this.getCommitmentHash('hex'); + const commitmentHash = this.getCommitmentHash('hex'); return { hash: this.rhash(), height: height != null ? height : -1, @@ -617,7 +617,7 @@ Block.prototype.fromJSON = function fromJSON(json) { this.parseJSON(json); - for (let tx of json.txs) + for (const tx of json.txs) this.txs.push(TX.fromJSON(tx)); return this; @@ -650,7 +650,7 @@ Block.prototype.fromReader = function fromReader(br) { count = br.readVarint(); for (let i = 0; i < count; i++) { - let tx = TX.fromReader(br); + const tx = TX.fromReader(br); witness += tx._witness; this.txs.push(tx); } @@ -723,7 +723,7 @@ Block.prototype.writeNormal = function writeNormal(bw) { bw.writeVarint(this.txs.length); - for (let tx of this.txs) + for (const tx of this.txs) tx.toNormalWriter(bw); return bw; @@ -742,7 +742,7 @@ Block.prototype.writeWitness = function writeWitness(bw) { bw.writeVarint(this.txs.length); - for (let tx of this.txs) + for (const tx of this.txs) tx.toWriter(bw); return bw; @@ -757,8 +757,8 @@ Block.prototype.writeWitness = function writeWitness(bw) { */ Block.prototype.frameNormal = function frameNormal() { - let raw = this.getNormalSizes(); - let bw = new StaticWriter(raw.size); + const raw = this.getNormalSizes(); + const bw = new StaticWriter(raw.size); this.writeNormal(bw); raw.data = bw.render(); return raw; @@ -772,8 +772,8 @@ Block.prototype.frameNormal = function frameNormal() { */ Block.prototype.frameWitness = function frameWitness() { - let raw = this.getWitnessSizes(); - let bw = new StaticWriter(raw.size); + const raw = this.getWitnessSizes(); + const bw = new StaticWriter(raw.size); this.writeWitness(bw); raw.data = bw.render(); return raw; @@ -799,7 +799,7 @@ Block.prototype.getNormalSizes = function getNormalSizes() { size += 80; size += encoding.sizeVarint(this.txs.length); - for (let tx of this.txs) + for (const tx of this.txs) size += tx.getBaseSize(); return new RawBlock(size, 0); @@ -817,8 +817,8 @@ Block.prototype.getWitnessSizes = function getWitnessSizes() { size += 80; size += encoding.sizeVarint(this.txs.length); - for (let tx of this.txs) { - let raw = tx.getSizes(); + for (const tx of this.txs) { + const raw = tx.getSizes(); size += raw.size; witness += raw.witness; } diff --git a/lib/primitives/coin.js b/lib/primitives/coin.js index 230a82382..f9e6a7f9b 100644 --- a/lib/primitives/coin.js +++ b/lib/primitives/coin.js @@ -330,7 +330,7 @@ Coin.prototype.toWriter = function toWriter(bw) { */ Coin.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; diff --git a/lib/primitives/headers.js b/lib/primitives/headers.js index c8ff62128..2c5ce7fcb 100644 --- a/lib/primitives/headers.js +++ b/lib/primitives/headers.js @@ -69,7 +69,7 @@ Headers.prototype.toWriter = function toWriter(bw) { */ Headers.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -138,7 +138,7 @@ Headers.fromHead = function fromHead(data, enc) { */ Headers.fromEntry = function fromEntry(entry) { - let headers = new Headers(); + const headers = new Headers(); headers.version = entry.version; headers.prevBlock = entry.prevBlock; headers.merkleRoot = entry.merkleRoot; @@ -166,7 +166,7 @@ Headers.prototype.toHeaders = function toHeaders() { */ Headers.fromBlock = function fromBlock(block) { - let headers = new Headers(block); + const headers = new Headers(block); headers._hash = block._hash; headers._hhash = block._hhash; return headers; diff --git a/lib/primitives/input.js b/lib/primitives/input.js index 95ddb04eb..d56336152 100644 --- a/lib/primitives/input.js +++ b/lib/primitives/input.js @@ -81,7 +81,7 @@ Input.fromOptions = function fromOptions(options) { */ Input.prototype.clone = function clone() { - let input = new Input(); + const input = new Input(); input.prevout = this.prevout; input.script.inject(this.script); input.sequence = this.sequence; @@ -202,7 +202,7 @@ Input.prototype.getAddress = function getAddress(coin) { */ Input.prototype.getHash = function getHash(enc) { - let addr = this.getAddress(); + const addr = this.getAddress(); if (!addr) return; return addr.getHash(enc); @@ -347,7 +347,7 @@ Input.prototype.getSize = function getSize() { */ Input.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; diff --git a/lib/primitives/keyring.js b/lib/primitives/keyring.js index 604a6eb7f..8224df85d 100644 --- a/lib/primitives/keyring.js +++ b/lib/primitives/keyring.js @@ -59,8 +59,8 @@ function KeyRing(options, network) { KeyRing.prototype.fromOptions = function fromOptions(options, network) { let key = toKey(options); - let script = options.script; - let compressed = options.compressed; + const script = options.script; + const compressed = options.compressed; if (!network) network = options.network; @@ -301,8 +301,8 @@ KeyRing.prototype.getSecretSize = function getSecretSize() { */ KeyRing.prototype.toSecret = function toSecret(network) { - let size = this.getSecretSize(); - let bw = new StaticWriter(size); + const size = this.getSecretSize(); + const bw = new StaticWriter(size); assert(this.privateKey, 'Cannot serialize without private key.'); @@ -330,7 +330,7 @@ KeyRing.prototype.toSecret = function toSecret(network) { */ KeyRing.prototype.fromSecret = function fromSecret(data, network) { - let br = new BufferReader(base58.decode(data), true); + const br = new BufferReader(base58.decode(data), true); let version, key, compressed; version = br.readU8(); @@ -868,7 +868,7 @@ KeyRing.prototype.toWriter = function toWriter(bw) { */ KeyRing.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -892,7 +892,7 @@ KeyRing.prototype.fromReader = function fromReader(br, network) { key = br.readVarBytes(); if (key.length === 32) { - let compressed = br.readU8() === 1; + const compressed = br.readU8() === 1; this.privateKey = key; this.publicKey = secp256k1.publicKeyCreate(key, compressed); } else { diff --git a/lib/primitives/memblock.js b/lib/primitives/memblock.js index e594957af..498fe2c93 100644 --- a/lib/primitives/memblock.js +++ b/lib/primitives/memblock.js @@ -108,7 +108,7 @@ MemBlock.prototype.getCoinbaseHeight = function getCoinbaseHeight() { */ MemBlock.prototype.parseCoinbaseHeight = function parseCoinbaseHeight() { - let br = new BufferReader(this._raw, true); + const br = new BufferReader(this._raw, true); let count, script; br.seek(80); @@ -144,7 +144,7 @@ MemBlock.prototype.parseCoinbaseHeight = function parseCoinbaseHeight() { */ MemBlock.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); + const br = new BufferReader(data, true); this.readHead(br); @@ -189,7 +189,7 @@ MemBlock.prototype.toNormal = function toNormal() { */ MemBlock.prototype.toBlock = function toBlock() { - let block = Block.fromRaw(this._raw); + const block = Block.fromRaw(this._raw); block._hash = this._hash; block._hhash = this._hhash; diff --git a/lib/primitives/merkleblock.js b/lib/primitives/merkleblock.js index ccc8d2a53..85c93ad89 100644 --- a/lib/primitives/merkleblock.js +++ b/lib/primitives/merkleblock.js @@ -103,7 +103,7 @@ MerkleBlock.prototype.refresh = function refresh(all) { if (!all) return; - for (let tx of this.txs) + for (const tx of this.txs) tx.refresh(); }; @@ -124,8 +124,8 @@ MerkleBlock.prototype.hasTX = function hasTX(hash) { */ MerkleBlock.prototype.indexOf = function indexOf(hash) { - let tree = this.getTree(); - let index = tree.map.get(hash); + const tree = this.getTree(); + const index = tree.map.get(hash); if (index == null) return -1; @@ -140,7 +140,7 @@ MerkleBlock.prototype.indexOf = function indexOf(hash) { */ MerkleBlock.prototype.verifyBody = function verifyBody() { - let [valid] = this.checkBody(); + const [valid] = this.checkBody(); return valid; }; @@ -151,7 +151,7 @@ MerkleBlock.prototype.verifyBody = function verifyBody() { */ MerkleBlock.prototype.checkBody = function checkBody() { - let tree = this.getTree(); + const tree = this.getTree(); if (tree.root !== this.merkleRoot) return [false, 'bad-txnmrklroot', 100]; @@ -186,21 +186,21 @@ MerkleBlock.prototype.getTree = function getTree() { MerkleBlock.prototype.extractTree = function extractTree() { let bitsUsed = 0; let hashUsed = 0; - let matches = []; - let indexes = []; - let map = new Map(); + const matches = []; + const indexes = []; + const map = new Map(); let failed = false; - let hashes = this.hashes; - let flags = this.flags; - let totalTX = this.totalTX; + const hashes = this.hashes; + const flags = this.flags; + const totalTX = this.totalTX; let height = 0; let root; - let width = (height) => { + const width = (height) => { return (totalTX + (1 << height) - 1) >>> height; }; - let traverse = (height, pos) => { + const traverse = (height, pos) => { let parent, hash, left, right; if (bitsUsed >= flags.length * 8) { @@ -220,7 +220,7 @@ MerkleBlock.prototype.extractTree = function extractTree() { hash = hashes[hashUsed++]; if (height === 0 && parent) { - let txid = hash.toString('hex'); + const txid = hash.toString('hex'); matches.push(hash); indexes.push(pos); map.set(txid, pos); @@ -347,7 +347,7 @@ MerkleBlock.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.hashes.length); - for (let hash of this.hashes) + for (const hash of this.hashes) bw.writeHash(hash); bw.writeVarBytes(this.flags); @@ -362,7 +362,7 @@ MerkleBlock.prototype.toWriter = function toWriter(bw) { */ MerkleBlock.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -507,9 +507,9 @@ MerkleBlock.fromJSON = function fromJSON(json) { */ MerkleBlock.fromBlock = function fromBlock(block, filter) { - let matches = []; + const matches = []; - for (let tx of block.txs) + for (const tx of block.txs) matches.push(tx.isWatched(filter) ? 1 : 0); return MerkleBlock.fromMatches(block, matches); @@ -524,8 +524,8 @@ MerkleBlock.fromBlock = function fromBlock(block, filter) { */ MerkleBlock.fromHashes = function fromHashes(block, hashes) { - let filter = new Set(); - let matches = []; + const filter = new Set(); + const matches = []; for (let hash of hashes) { if (Buffer.isBuffer(hash)) @@ -533,8 +533,8 @@ MerkleBlock.fromHashes = function fromHashes(block, hashes) { filter.add(hash); } - for (let tx of block.txs) { - let hash = tx.hash('hex'); + for (const tx of block.txs) { + const hash = tx.hash('hex'); matches.push(filter.has(hash) ? 1 : 0); } @@ -550,19 +550,19 @@ MerkleBlock.fromHashes = function fromHashes(block, hashes) { */ MerkleBlock.fromMatches = function fromMatches(block, matches) { - let txs = []; - let leaves = []; - let bits = []; - let hashes = []; - let totalTX = block.txs.length; + const txs = []; + const leaves = []; + const bits = []; + const hashes = []; + const totalTX = block.txs.length; let height = 0; let flags, merkle; - let width = (height) => { + const width = (height) => { return (totalTX + (1 << height) - 1) >>> height; }; - let hash = (height, pos, leaves) => { + const hash = (height, pos, leaves) => { let left, right; if (height === 0) @@ -578,7 +578,7 @@ MerkleBlock.fromMatches = function fromMatches(block, matches) { return digest.root256(left, right); }; - let traverse = (height, pos, leaves, matches) => { + const traverse = (height, pos, leaves, matches) => { let parent = 0; for (let p = (pos << height); p < ((pos + 1) << height) && p < totalTX; p++) @@ -598,7 +598,7 @@ MerkleBlock.fromMatches = function fromMatches(block, matches) { }; for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; if (matches[i]) txs.push(tx); diff --git a/lib/primitives/mtx.js b/lib/primitives/mtx.js index fa3dcb779..351e567ac 100644 --- a/lib/primitives/mtx.js +++ b/lib/primitives/mtx.js @@ -77,13 +77,13 @@ MTX.prototype.fromOptions = function fromOptions(options) { if (options.inputs) { assert(Array.isArray(options.inputs), 'Inputs must be an array.'); - for (let input of options.inputs) + for (const input of options.inputs) this.addInput(input); } if (options.outputs) { assert(Array.isArray(options.outputs), 'Outputs must be an array.'); - for (let output of options.outputs) + for (const output of options.outputs) this.addOutput(output); } @@ -122,7 +122,7 @@ MTX.fromOptions = function fromOptions(options) { */ MTX.prototype.clone = function clone() { - let mtx = new MTX(); + const mtx = new MTX(); mtx.inject(this); mtx.changeIndex = this.changeIndex; return mtx; @@ -139,7 +139,7 @@ MTX.prototype.clone = function clone() { */ MTX.prototype.addInput = function addInput(options) { - let input = Input.fromOptions(options); + const input = Input.fromOptions(options); this.inputs.push(input); return input; }; @@ -155,8 +155,8 @@ MTX.prototype.addInput = function addInput(options) { */ MTX.prototype.addOutpoint = function addOutpoint(outpoint) { - let prevout = Outpoint.fromOptions(outpoint); - let input = Input.fromOutpoint(prevout); + const prevout = Outpoint.fromOptions(outpoint); + const input = Input.fromOutpoint(prevout); this.inputs.push(input); return input; }; @@ -408,7 +408,7 @@ MTX.prototype.getSigopsSize = function getSigopsSize() { */ MTX.prototype.verifyInputs = function verifyInputs(height) { - let [fee] = this.checkInputs(height); + const [fee] = this.checkInputs(height); return fee !== -1; }; @@ -438,7 +438,7 @@ MTX.prototype.checkInputs = function checkInputs(height) { */ MTX.prototype.scriptInput = function scriptInput(index, coin, ring) { - let input = this.inputs[index]; + const input = this.inputs[index]; let prev; assert(input, 'Input does not exist.'); @@ -459,7 +459,7 @@ MTX.prototype.scriptInput = function scriptInput(index, coin, ring) { // figuring out where the redeem script // and witness redeem scripts go. if (prev.isScripthash()) { - let redeem = ring.getRedeem(prev.get(1)); + const redeem = ring.getRedeem(prev.get(1)); if (!redeem) return false; @@ -516,7 +516,7 @@ MTX.prototype.scriptInput = function scriptInput(index, coin, ring) { if (prev.isProgram()) { // Bare P2WSH. if (prev.isWitnessScripthash()) { - let redeem = ring.getRedeem(prev.get(1)); + const redeem = ring.getRedeem(prev.get(1)); if (!redeem) return false; @@ -634,10 +634,10 @@ MTX.prototype.signInputAsync = function signInputAsync(index, coin, ring, type, */ MTX.prototype.signInput = function signInput(index, coin, ring, type) { - let input = this.inputs[index]; + const input = this.inputs[index]; let version = 0; let redeem = false; - let key = ring.privateKey; + const key = ring.privateKey; let prev, value, vector, sig, result; assert(input, 'Input does not exist.'); @@ -742,14 +742,14 @@ MTX.prototype.signVector = function signVector(prev, vector, sig, ring) { // Multisig if (prev.isMultisig()) { let total = 0; - let keys = []; + const keys = []; let keyIndex; // Grab `m` value (number of sigs required). - let m = prev.getSmall(0); + const m = prev.getSmall(0); // Grab `n` value (number of keys). - let n = prev.getSmall(prev.length - 2); + const n = prev.getSmall(prev.length - 2); // Grab the redeem script's keys to figure // out where our key should go. @@ -841,8 +841,8 @@ MTX.prototype.signVector = function signVector(prev, vector, sig, ring) { MTX.prototype.isSigned = function isSigned() { for (let i = 0; i < this.inputs.length; i++) { - let {prevout} = this.inputs[i]; - let coin = this.view.getOutput(prevout); + const {prevout} = this.inputs[i]; + const coin = this.view.getOutput(prevout); if (!coin) return false; @@ -862,7 +862,7 @@ MTX.prototype.isSigned = function isSigned() { */ MTX.prototype.isInputSigned = function isInputSigned(index, coin) { - let input = this.inputs[index]; + const input = this.inputs[index]; let prev, vector, redeem, result; assert(input, 'Input does not exist.'); @@ -927,7 +927,7 @@ MTX.prototype.isVectorSigned = function isVectorSigned(prev, vector) { if (prev.isMultisig()) { // Grab `m` value (number of required sigs). - let m = prev.getSmall(0); + const m = prev.getSmall(0); // Ensure all members are signatures. for (let i = 1; i < vector.length; i++) { @@ -957,14 +957,14 @@ MTX.prototype.template = function template(ring) { let total = 0; if (Array.isArray(ring)) { - for (let key of ring) + for (const key of ring) total += this.template(key); return total; } for (let i = 0; i < this.inputs.length; i++) { - let {prevout} = this.inputs[i]; - let coin = this.view.getOutput(prevout); + const {prevout} = this.inputs[i]; + const coin = this.view.getOutput(prevout); if (!coin) continue; @@ -994,7 +994,7 @@ MTX.prototype.sign = function sign(ring, type) { let total = 0; if (Array.isArray(ring)) { - for (let key of ring) + for (const key of ring) total += this.sign(key, type); return total; } @@ -1002,8 +1002,8 @@ MTX.prototype.sign = function sign(ring, type) { assert(ring.privateKey, 'No private key available.'); for (let i = 0; i < this.inputs.length; i++) { - let {prevout} = this.inputs[i]; - let coin = this.view.getOutput(prevout); + const {prevout} = this.inputs[i]; + const coin = this.view.getOutput(prevout); if (!coin) continue; @@ -1048,7 +1048,7 @@ MTX.prototype.signAsync = function signAsync(ring, type, pool) { */ MTX.prototype.estimateSize = async function estimateSize(estimate) { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; let total = 0; // Calculate the size, minus the input scripts. @@ -1058,14 +1058,14 @@ MTX.prototype.estimateSize = async function estimateSize(estimate) { total += encoding.sizeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) total += output.getSize(); total += 4; // Add size for signatures and public keys - for (let {prevout} of this.inputs) { - let coin = this.view.getOutput(prevout); + for (const {prevout} of this.inputs) { + const coin = this.view.getOutput(prevout); let size = 0; let prev; @@ -1173,7 +1173,7 @@ MTX.prototype.estimateSize = async function estimateSize(estimate) { */ MTX.prototype.selectCoins = function selectCoins(coins, options) { - let selector = new CoinSelector(this, options); + const selector = new CoinSelector(this, options); return selector.select(coins); }; @@ -1185,7 +1185,7 @@ MTX.prototype.selectCoins = function selectCoins(coins, options) { MTX.prototype.subtractFee = function subtractFee(fee, index) { if (typeof index === 'number') { - let output = this.outputs[index]; + const output = this.outputs[index]; let min; if (!output) @@ -1201,8 +1201,8 @@ MTX.prototype.subtractFee = function subtractFee(fee, index) { return; } - for (let output of this.outputs) { - let min = fee + output.getDustThreshold(); + for (const output of this.outputs) { + const min = fee + output.getDustThreshold(); if (output.value >= min) { output.value -= fee; @@ -1231,7 +1231,7 @@ MTX.prototype.fund = async function fund(coins, options) { select = await this.selectCoins(coins, options); // Add coins to transaction. - for (let coin of select.chosen) + for (const coin of select.chosen) this.addCoin(coin); // Attempt to subtract fee. @@ -1306,7 +1306,7 @@ MTX.prototype.setLocktime = function setLocktime(locktime) { assert(util.isUInt32(locktime), 'Locktime must be a uint32.'); assert(this.inputs.length > 0, 'Cannot set sequence with no inputs.'); - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.sequence === 0xffffffff) input.sequence = 0xfffffffe; } @@ -1322,7 +1322,7 @@ MTX.prototype.setLocktime = function setLocktime(locktime) { */ MTX.prototype.setSequence = function setSequence(index, locktime, seconds) { - let input = this.inputs[index]; + const input = this.inputs[index]; assert(input, 'Input does not exist.'); assert(util.isUInt32(locktime), 'Locktime must be a uint32.'); @@ -1573,7 +1573,7 @@ CoinSelector.prototype.fromOptions = function fromOptions(options) { } if (options.changeAddress) { - let addr = options.changeAddress; + const addr = options.changeAddress; if (typeof addr === 'string') { this.changeAddress = Address.fromString(addr); } else { @@ -1704,7 +1704,7 @@ CoinSelector.prototype.getFee = function getFee(size) { CoinSelector.prototype.fund = function fund() { while (this.index < this.coins.length) { - let coin = this.coins[this.index++]; + const coin = this.coins[this.index++]; if (!this.isSpendable(coin)) continue; @@ -1782,7 +1782,7 @@ CoinSelector.prototype.selectEstimate = async function selectEstimate() { // Keep recalculating the fee and funding // until we reach some sort of equilibrium. do { - let size = await this.tx.estimateSize(this.estimate); + const size = await this.tx.estimateSize(this.estimate); this.fee = this.getFee(size); @@ -1861,9 +1861,9 @@ function sortValue(a, b) { } function sortInputs(a, b) { - let ahash = a.prevout.txid(); - let bhash = b.prevout.txid(); - let cmp = util.strcmp(ahash, bhash); + const ahash = a.prevout.txid(); + const bhash = b.prevout.txid(); + const cmp = util.strcmp(ahash, bhash); if (cmp !== 0) return cmp; @@ -1872,7 +1872,7 @@ function sortInputs(a, b) { } function sortOutputs(a, b) { - let cmp = a.value - b.value; + const cmp = a.value - b.value; if (cmp !== 0) return cmp; diff --git a/lib/primitives/netaddress.js b/lib/primitives/netaddress.js index b6ed4dd2f..1b7f77ea2 100644 --- a/lib/primitives/netaddress.js +++ b/lib/primitives/netaddress.js @@ -183,7 +183,7 @@ NetAddress.prototype.equal = function equal(addr) { */ NetAddress.prototype.compare = function compare(addr) { - let cmp = this.raw.compare(addr.raw); + const cmp = this.raw.compare(addr.raw); if (cmp !== 0) return cmp; @@ -306,8 +306,8 @@ NetAddress.fromHostname = function fromHostname(hostname, network) { */ NetAddress.prototype.fromSocket = function fromSocket(socket, network) { - let host = socket.remoteAddress; - let port = socket.remotePort; + const host = socket.remoteAddress; + const port = socket.remotePort; assert(typeof host === 'string'); assert(typeof port === 'number'); return this.fromHost(IP.normalize(host), port, network); @@ -415,7 +415,7 @@ NetAddress.prototype.getSize = function getSize(full) { */ NetAddress.prototype.toRaw = function toRaw(full) { - let size = this.getSize(full); + const size = this.getSize(full); return this.toWriter(new StaticWriter(size), full).render(); }; diff --git a/lib/primitives/output.js b/lib/primitives/output.js index 040c116e7..74cfeba15 100644 --- a/lib/primitives/output.js +++ b/lib/primitives/output.js @@ -112,7 +112,7 @@ Output.fromScript = function fromScript(script, value) { */ Output.prototype.clone = function clone() { - let output = new Output(); + const output = new Output(); output.value = this.value; output.script.inject(this.script); return output; @@ -143,7 +143,7 @@ Output.prototype.getAddress = function getAddress() { */ Output.prototype.getHash = function getHash(enc) { - let addr = this.getAddress(); + const addr = this.getAddress(); if (!addr) return; return addr.getHash(enc); @@ -203,7 +203,7 @@ Output.prototype.getJSON = function getJSON(network) { */ Output.prototype.getDustThreshold = function getDustThreshold(rate) { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; let size; if (this.script.isUnspendable()) @@ -282,7 +282,7 @@ Output.prototype.toWriter = function toWriter(bw) { */ Output.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; diff --git a/lib/primitives/tx.js b/lib/primitives/tx.js index a88e92d19..e1e104116 100644 --- a/lib/primitives/tx.js +++ b/lib/primitives/tx.js @@ -91,13 +91,13 @@ TX.prototype.fromOptions = function fromOptions(options) { if (options.inputs) { assert(Array.isArray(options.inputs), 'Inputs must be an array.'); - for (let input of options.inputs) + for (const input of options.inputs) this.inputs.push(new Input(input)); } if (options.outputs) { assert(Array.isArray(options.outputs), 'Outputs must be an array.'); - for (let output of options.outputs) + for (const output of options.outputs) this.outputs.push(new Output(output)); } @@ -140,10 +140,10 @@ TX.prototype.inject = function inject(tx) { this.version = tx.version; this.flag = tx.flag; - for (let input of tx.inputs) + for (const input of tx.inputs) this.inputs.push(input.clone()); - for (let output of tx.outputs) + for (const output of tx.outputs) this.outputs.push(output.clone()); this.locktime = tx.locktime; @@ -337,7 +337,7 @@ TX.prototype.getSizes = function getSizes() { */ TX.prototype.getVirtualSize = function getVirtualSize() { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; return (this.getWeight() + scale - 1) / scale | 0; }; @@ -349,9 +349,9 @@ TX.prototype.getVirtualSize = function getVirtualSize() { */ TX.prototype.getSigopsSize = function getSigopsSize(sigops) { - let scale = consensus.WITNESS_SCALE_FACTOR; - let bytes = policy.BYTES_PER_SIGOP; - let weight = Math.max(this.getWeight(), sigops * bytes); + const scale = consensus.WITNESS_SCALE_FACTOR; + const bytes = policy.BYTES_PER_SIGOP; + const weight = Math.max(this.getWeight(), sigops * bytes); return (weight + scale - 1) / scale | 0; }; @@ -362,8 +362,8 @@ TX.prototype.getSigopsSize = function getSigopsSize(sigops) { */ TX.prototype.getWeight = function getWeight() { - let raw = this.getSizes(); - let base = raw.size - raw.witness; + const raw = this.getSizes(); + const base = raw.size - raw.witness; return base * (consensus.WITNESS_SCALE_FACTOR - 1) + raw.size; }; @@ -385,7 +385,7 @@ TX.prototype.getSize = function getSize() { */ TX.prototype.getBaseSize = function getBaseSize() { - let raw = this.getSizes(); + const raw = this.getSizes(); return raw.size - raw.witness; }; @@ -398,7 +398,7 @@ TX.prototype.hasWitness = function hasWitness() { if (this._witness !== -1) return this._witness !== 0; - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.witness.items.length > 0) return true; } @@ -468,7 +468,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { if (type & hashType.ANYONECANPAY) { // Serialize only the current // input if ANYONECANPAY. - let input = this.inputs[index]; + const input = this.inputs[index]; // Count. bw.writeVarint(1); @@ -483,7 +483,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { } else { bw.writeVarint(this.inputs.length); for (let i = 0; i < this.inputs.length; i++) { - let input = this.inputs[i]; + const input = this.inputs[i]; // Outpoint. input.prevout.toWriter(bw); @@ -520,7 +520,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { break; } case hashType.SINGLE: { - let output = this.outputs[index]; + const output = this.outputs[index]; // Drop all outputs after the // current input index if SINGLE. @@ -542,7 +542,7 @@ TX.prototype.signatureHashV0 = function signatureHashV0(index, prev, type) { default: { // Regular output serialization if ALL. bw.writeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) output.toWriter(bw); break; } @@ -594,7 +594,7 @@ TX.prototype.hashSize = function hashSize(index, prev, type) { break; default: size += encoding.sizeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) size += output.getSize(); break; } @@ -618,16 +618,16 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type let prevouts = encoding.ZERO_HASH; let sequences = encoding.ZERO_HASH; let outputs = encoding.ZERO_HASH; - let input = this.inputs[index]; + const input = this.inputs[index]; let bw, size; if (!(type & hashType.ANYONECANPAY)) { if (this._hashPrevouts) { prevouts = this._hashPrevouts; } else { - let bw = new StaticWriter(this.inputs.length * 36); + const bw = new StaticWriter(this.inputs.length * 36); - for (let input of this.inputs) + for (const input of this.inputs) input.prevout.toWriter(bw); prevouts = digest.hash256(bw.render()); @@ -643,9 +643,9 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type if (this._hashSequence) { sequences = this._hashSequence; } else { - let bw = new StaticWriter(this.inputs.length * 4); + const bw = new StaticWriter(this.inputs.length * 4); - for (let input of this.inputs) + for (const input of this.inputs) bw.writeU32(input.sequence); sequences = digest.hash256(bw.render()); @@ -663,12 +663,12 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type let size = 0; let bw; - for (let output of this.outputs) + for (const output of this.outputs) size += output.getSize(); bw = new StaticWriter(size); - for (let output of this.outputs) + for (const output of this.outputs) output.toWriter(bw); outputs = digest.hash256(bw.render()); @@ -677,7 +677,7 @@ TX.prototype.signatureHashV1 = function signatureHashV1(index, prev, value, type this._hashOutputs = outputs; } } else if ((type & 0x1f) === hashType.SINGLE && index < this.outputs.length) { - let output = this.outputs[index]; + const output = this.outputs[index]; outputs = digest.hash256(output.toRaw()); } @@ -770,8 +770,8 @@ TX.prototype.check = function check(view, flags) { return; for (let i = 0; i < this.inputs.length; i++) { - let {prevout} = this.inputs[i]; - let coin = view.getOutput(prevout); + const {prevout} = this.inputs[i]; + const coin = view.getOutput(prevout); if (!coin) throw new ScriptError('UNKNOWN_ERROR', 'No coin available.'); @@ -790,7 +790,7 @@ TX.prototype.check = function check(view, flags) { */ TX.prototype.checkInput = function checkInput(index, coin, flags) { - let input = this.inputs[index]; + const input = this.inputs[index]; assert(input, 'Input does not exist.'); assert(coin, 'No coin passed.'); @@ -839,7 +839,7 @@ TX.prototype.checkAsync = async function checkAsync(view, flags, pool) { */ TX.prototype.checkInputAsync = async function checkInputAsync(index, coin, flags, pool) { - let input = this.inputs[index]; + const input = this.inputs[index]; assert(input, 'Input does not exist.'); assert(coin, 'No coin passed.'); @@ -949,7 +949,7 @@ TX.prototype.isRBF = function isRBF() { if (this.version === 2) return false; - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.isRBF()) return true; } @@ -979,8 +979,8 @@ TX.prototype.getFee = function getFee(view) { TX.prototype.getInputValue = function getInputValue(view) { let total = 0; - for (let {prevout} of this.inputs) { - let coin = view.getOutput(prevout); + for (const {prevout} of this.inputs) { + const coin = view.getOutput(prevout); if (!coin) return 0; @@ -999,7 +999,7 @@ TX.prototype.getInputValue = function getInputValue(view) { TX.prototype.getOutputValue = function getOutputValue() { let total = 0; - for (let output of this.outputs) + for (const output of this.outputs) total += output.value; return total; @@ -1013,15 +1013,15 @@ TX.prototype.getOutputValue = function getOutputValue() { */ TX.prototype._getInputAddresses = function getInputAddresses(view) { - let table = Object.create(null); - let addrs = []; + const table = Object.create(null); + const addrs = []; if (this.isCoinbase()) return [addrs, table]; - for (let input of this.inputs) { - let coin = view ? view.getOutputFor(input) : null; - let addr = input.getAddress(coin); + for (const input of this.inputs) { + const coin = view ? view.getOutputFor(input) : null; + const addr = input.getAddress(coin); let hash; if (!addr) @@ -1045,11 +1045,11 @@ TX.prototype._getInputAddresses = function getInputAddresses(view) { */ TX.prototype._getOutputAddresses = function getOutputAddresses() { - let table = Object.create(null); - let addrs = []; + const table = Object.create(null); + const addrs = []; - for (let output of this.outputs) { - let addr = output.getAddress(); + for (const output of this.outputs) { + const addr = output.getAddress(); let hash; if (!addr) @@ -1074,11 +1074,11 @@ TX.prototype._getOutputAddresses = function getOutputAddresses() { */ TX.prototype._getAddresses = function getAddresses(view) { - let [addrs, table] = this._getInputAddresses(view); - let output = this.getOutputAddresses(); + const [addrs, table] = this._getInputAddresses(view); + const output = this.getOutputAddresses(); - for (let addr of output) { - let hash = addr.getHash('hex'); + for (const addr of output) { + const hash = addr.getHash('hex'); if (!table[hash]) { table[hash] = true; @@ -1096,7 +1096,7 @@ TX.prototype._getAddresses = function getAddresses(view) { */ TX.prototype.getInputAddresses = function getInputAddresses(view) { - let [addrs] = this._getInputAddresses(view); + const [addrs] = this._getInputAddresses(view); return addrs; }; @@ -1106,7 +1106,7 @@ TX.prototype.getInputAddresses = function getInputAddresses(view) { */ TX.prototype.getOutputAddresses = function getOutputAddresses() { - let [addrs] = this._getOutputAddresses(); + const [addrs] = this._getOutputAddresses(); return addrs; }; @@ -1117,7 +1117,7 @@ TX.prototype.getOutputAddresses = function getOutputAddresses() { */ TX.prototype.getAddresses = function getAddresses(view) { - let [addrs] = this._getAddresses(view); + const [addrs] = this._getAddresses(view); return addrs; }; @@ -1128,17 +1128,17 @@ TX.prototype.getAddresses = function getAddresses(view) { */ TX.prototype.getInputHashes = function getInputHashes(view, enc) { - let hashes = []; + const hashes = []; let addrs; if (enc === 'hex') { - let [, table] = this._getInputAddresses(view); + const [, table] = this._getInputAddresses(view); return Object.keys(table); } addrs = this.getInputAddresses(view); - for (let addr of addrs) + for (const addr of addrs) hashes.push(addr.getHash()); return hashes; @@ -1150,17 +1150,17 @@ TX.prototype.getInputHashes = function getInputHashes(view, enc) { */ TX.prototype.getOutputHashes = function getOutputHashes(enc) { - let hashes = []; + const hashes = []; let addrs; if (enc === 'hex') { - let [, table] = this._getOutputAddresses(); + const [, table] = this._getOutputAddresses(); return Object.keys(table); } addrs = this.getOutputAddresses(); - for (let addr of addrs) + for (const addr of addrs) hashes.push(addr.getHash()); return hashes; @@ -1173,17 +1173,17 @@ TX.prototype.getOutputHashes = function getOutputHashes(enc) { */ TX.prototype.getHashes = function getHashes(view, enc) { - let hashes = []; + const hashes = []; let addrs; if (enc === 'hex') { - let [, table] = this._getAddresses(view); + const [, table] = this._getAddresses(view); return Object.keys(table); } addrs = this.getAddresses(view); - for (let addr of addrs) + for (const addr of addrs) hashes.push(addr.getHash()); return hashes; @@ -1200,7 +1200,7 @@ TX.prototype.hasCoins = function hasCoins(view) { if (this.inputs.length === 0) return false; - for (let {prevout} of this.inputs) { + for (const {prevout} of this.inputs) { if (!view.hasEntry(prevout)) return false; } @@ -1225,7 +1225,7 @@ TX.prototype.hasCoins = function hasCoins(view) { */ TX.prototype.isFinal = function isFinal(height, time) { - let THRESHOLD = consensus.LOCKTIME_THRESHOLD; + const THRESHOLD = consensus.LOCKTIME_THRESHOLD; if (this.locktime === 0) return true; @@ -1233,7 +1233,7 @@ TX.prototype.isFinal = function isFinal(height, time) { if (this.locktime < (this.locktime < THRESHOLD ? height : time)) return true; - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.sequence !== 0xffffffff) return false; } @@ -1250,8 +1250,8 @@ TX.prototype.isFinal = function isFinal(height, time) { */ TX.prototype.verifyLocktime = function verifyLocktime(index, locktime) { - let THRESHOLD = consensus.LOCKTIME_THRESHOLD; - let input = this.inputs[index]; + const THRESHOLD = consensus.LOCKTIME_THRESHOLD; + const input = this.inputs[index]; assert(input, 'Input does not exist.'); assert(locktime >= 0, 'Locktime must be non-negative.'); @@ -1279,10 +1279,10 @@ TX.prototype.verifyLocktime = function verifyLocktime(index, locktime) { */ TX.prototype.verifySequence = function verifySequence(index, locktime) { - let DISABLE_FLAG = consensus.SEQUENCE_DISABLE_FLAG; - let TYPE_FLAG = consensus.SEQUENCE_TYPE_FLAG; - let SEQUENCE_MASK = consensus.SEQUENCE_MASK; - let input = this.inputs[index]; + const DISABLE_FLAG = consensus.SEQUENCE_DISABLE_FLAG; + const TYPE_FLAG = consensus.SEQUENCE_TYPE_FLAG; + const SEQUENCE_MASK = consensus.SEQUENCE_MASK; + const input = this.inputs[index]; let mask, sequence, predicate; assert(input, 'Input does not exist.'); @@ -1320,10 +1320,10 @@ TX.prototype.verifySequence = function verifySequence(index, locktime) { TX.prototype.getLegacySigops = function getLegacySigops() { let total = 0; - for (let input of this.inputs) + for (const input of this.inputs) total += input.script.getSigops(false); - for (let output of this.outputs) + for (const output of this.outputs) total += output.script.getSigops(false); return total; @@ -1341,8 +1341,8 @@ TX.prototype.getScripthashSigops = function getScripthashSigops(view) { if (this.isCoinbase()) return 0; - for (let input of this.inputs) { - let coin = view.getOutputFor(input); + for (const input of this.inputs) { + const coin = view.getOutputFor(input); if (!coin) continue; @@ -1364,7 +1364,7 @@ TX.prototype.getScripthashSigops = function getScripthashSigops(view) { */ TX.prototype.getSigopsCost = function getSigopsCost(view, flags) { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; let cost = this.getLegacySigops() * scale; if (flags == null) @@ -1379,8 +1379,8 @@ TX.prototype.getSigopsCost = function getSigopsCost(view, flags) { if (!(flags & Script.flags.VERIFY_WITNESS)) return cost; - for (let input of this.inputs) { - let coin = view.getOutputFor(input); + for (const input of this.inputs) { + const coin = view.getOutputFor(input); if (!coin) continue; @@ -1399,7 +1399,7 @@ TX.prototype.getSigopsCost = function getSigopsCost(view, flags) { */ TX.prototype.getSigops = function getSigops(view, flags) { - let scale = consensus.WITNESS_SCALE_FACTOR; + const scale = consensus.WITNESS_SCALE_FACTOR; return (this.getSigopsCost(view, flags) + scale - 1) / scale | 0; }; @@ -1411,7 +1411,7 @@ TX.prototype.getSigops = function getSigops(view, flags) { */ TX.prototype.isSane = function isSane() { - let [valid] = this.checkSanity(); + const [valid] = this.checkSanity(); return valid; }; @@ -1423,7 +1423,7 @@ TX.prototype.isSane = function isSane() { */ TX.prototype.checkSanity = function checkSanity() { - let prevout = new Set(); + const prevout = new Set(); let total = 0; if (this.inputs.length === 0) @@ -1435,7 +1435,7 @@ TX.prototype.checkSanity = function checkSanity() { if (this.getBaseSize() > consensus.MAX_BLOCK_SIZE) return [false, 'bad-txns-oversize', 100]; - for (let output of this.outputs) { + for (const output of this.outputs) { if (output.value < 0) return [false, 'bad-txns-vout-negative', 100]; @@ -1448,19 +1448,19 @@ TX.prototype.checkSanity = function checkSanity() { return [false, 'bad-txns-txouttotal-toolarge', 100]; } - for (let input of this.inputs) { - let key = input.prevout.toKey(); + for (const input of this.inputs) { + const key = input.prevout.toKey(); if (prevout.has(key)) return [false, 'bad-txns-inputs-duplicate', 100]; prevout.add(key); } if (this.isCoinbase()) { - let size = this.inputs[0].script.getSize(); + const size = this.inputs[0].script.getSize(); if (size < 2 || size > 100) return [false, 'bad-cb-length', 100]; } else { - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.prevout.isNull()) return [false, 'bad-txns-prevout-null', 10]; } @@ -1480,7 +1480,7 @@ TX.prototype.checkSanity = function checkSanity() { */ TX.prototype.isStandard = function isStandard() { - let [valid] = this.checkStandard(); + const [valid] = this.checkStandard(); return valid; }; @@ -1503,7 +1503,7 @@ TX.prototype.checkStandard = function checkStandard() { if (this.getWeight() >= policy.MAX_TX_WEIGHT) return [false, 'tx-size', 0]; - for (let input of this.inputs) { + for (const input of this.inputs) { if (input.script.getSize() > 1650) return [false, 'scriptsig-size', 0]; @@ -1511,7 +1511,7 @@ TX.prototype.checkStandard = function checkStandard() { return [false, 'scriptsig-not-pushonly', 0]; } - for (let output of this.outputs) { + for (const output of this.outputs) { if (!output.script.isStandard()) return [false, 'scriptpubkey', 0]; @@ -1546,8 +1546,8 @@ TX.prototype.hasStandardInputs = function hasStandardInputs(view) { if (this.isCoinbase()) return true; - for (let input of this.inputs) { - let coin = view.getOutputFor(input); + for (const input of this.inputs) { + const coin = view.getOutputFor(input); if (!coin) return false; @@ -1556,7 +1556,7 @@ TX.prototype.hasStandardInputs = function hasStandardInputs(view) { continue; if (coin.script.isScripthash()) { - let redeem = input.script.getRedeem(); + const redeem = input.script.getRedeem(); if (!redeem) return false; @@ -1585,9 +1585,9 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { if (this.isCoinbase()) return true; - for (let input of this.inputs) { - let witness = input.witness; - let coin = view.getOutputFor(input); + for (const input of this.inputs) { + const witness = input.witness; + const coin = view.getOutputFor(input); let prev; if (!coin) @@ -1627,7 +1627,7 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { return false; for (let i = 0; i < witness.items.length - 1; i++) { - let item = witness.items[i]; + const item = witness.items[i]; if (item.length > policy.MAX_P2WSH_PUSH) return false; } @@ -1663,7 +1663,7 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { } if (prev.isMultisig()) { - let m = prev.getSmall(0); + const m = prev.getSmall(0); if (witness.items.length - 1 !== m + 1) return false; @@ -1672,7 +1672,7 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { return false; for (let i = 1; i < witness.items.length - 1; i++) { - let item = witness.items[i]; + const item = witness.items[i]; if (item.length > 73) return false; } @@ -1684,7 +1684,7 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { if (witness.items.length > policy.MAX_P2WSH_STACK) return false; - for (let item of witness.items) { + for (const item of witness.items) { if (item.length > policy.MAX_P2WSH_PUSH) return false; } @@ -1707,7 +1707,7 @@ TX.prototype.hasStandardWitness = function hasStandardWitness(view) { */ TX.prototype.verifyInputs = function verifyInputs(view, height) { - let [fee] = this.checkInputs(view, height); + const [fee] = this.checkInputs(view, height); return fee !== -1; }; @@ -1730,7 +1730,7 @@ TX.prototype.checkInputs = function checkInputs(view, height) { assert(typeof height === 'number'); - for (let {prevout} of this.inputs) { + for (const {prevout} of this.inputs) { let coin = view.getEntry(prevout); if (!coin) @@ -1784,7 +1784,7 @@ TX.prototype.getModifiedSize = function getModifiedSize(size) { if (size == null) size = this.getVirtualSize(); - for (let input of this.inputs) { + for (const input of this.inputs) { offset = 41 + Math.min(110, input.script.getSize()); if (size > offset) size -= offset; @@ -1813,8 +1813,8 @@ TX.prototype.getPriority = function getPriority(view, height, size) { if (size == null) size = this.getVirtualSize(); - for (let {prevout} of this.inputs) { - let coin = view.getOutput(prevout); + for (const {prevout} of this.inputs) { + const coin = view.getOutput(prevout); let coinHeight; if (!coin) @@ -1826,7 +1826,7 @@ TX.prototype.getPriority = function getPriority(view, height, size) { continue; if (coinHeight <= height) { - let age = height - coinHeight; + const age = height - coinHeight; sum += coin.value * age; } } @@ -1846,8 +1846,8 @@ TX.prototype.getChainValue = function getChainValue(view) { if (this.isCoinbase()) return value; - for (let {prevout} of this.inputs) { - let coin = view.getOutput(prevout); + for (const {prevout} of this.inputs) { + const coin = view.getOutput(prevout); let coinHeight; if (!coin) @@ -1878,7 +1878,7 @@ TX.prototype.getChainValue = function getChainValue(view) { */ TX.prototype.isFree = function isFree(view, height, size) { - let priority = this.getPriority(view, height, size); + const priority = this.getPriority(view, height, size); return priority > policy.FREE_THRESHOLD; }; @@ -1924,7 +1924,7 @@ TX.prototype.getRoundFee = function getRoundFee(size, rate) { */ TX.prototype.getRate = function getRate(view, size) { - let fee = this.getFee(view); + const fee = this.getFee(view); if (fee < 0) return 0; @@ -1941,12 +1941,12 @@ TX.prototype.getRate = function getRate(view, size) { */ TX.prototype.getPrevout = function getPrevout() { - let prevout = Object.create(null); + const prevout = Object.create(null); if (this.isCoinbase()) return []; - for (let input of this.inputs) + for (const input of this.inputs) prevout[input.prevout.hash] = true; return Object.keys(prevout); @@ -1973,15 +1973,15 @@ TX.prototype.isWatched = function isWatched(filter) { // 2. Test data elements in output scripts // (may need to update filter on match) for (let i = 0; i < this.outputs.length; i++) { - let output = this.outputs[i]; + const output = this.outputs[i]; // Test the output script if (output.script.test(filter)) { if (filter.update === Bloom.flags.ALL) { - let prevout = Outpoint.fromTX(this, i); + const prevout = Outpoint.fromTX(this, i); filter.add(prevout.toRaw()); } else if (filter.update === Bloom.flags.PUBKEY_ONLY) { if (output.script.isPubkey() || output.script.isMultisig()) { - let prevout = Outpoint.fromTX(this, i); + const prevout = Outpoint.fromTX(this, i); filter.add(prevout.toRaw()); } } @@ -1994,8 +1994,8 @@ TX.prototype.isWatched = function isWatched(filter) { // 3. Test prev_out structure // 4. Test data elements in input scripts - for (let input of this.inputs) { - let prevout = input.prevout; + for (const input of this.inputs) { + const prevout = input.prevout; // Test the COutPoint structure if (filter.test(prevout.toRaw())) @@ -2118,7 +2118,7 @@ TX.prototype.format = function format(view, entry, index) { version: this.version, flag: this.flag, inputs: this.inputs.map((input) => { - let coin = view ? view.getOutputFor(input) : null; + const coin = view ? view.getOutputFor(input) : null; return input.format(coin); }), outputs: this.outputs, @@ -2183,7 +2183,7 @@ TX.prototype.getJSON = function getJSON(network, view, entry, index) { version: this.version, flag: this.flag, inputs: this.inputs.map((input) => { - let coin = view ? view.getCoinFor(input) : null; + const coin = view ? view.getCoinFor(input) : null; return input.getJSON(network, coin); }), outputs: this.outputs.map((output) => { @@ -2210,10 +2210,10 @@ TX.prototype.fromJSON = function fromJSON(json) { this.version = json.version; this.flag = json.flag; - for (let input of json.inputs) + for (const input of json.inputs) this.inputs.push(Input.fromJSON(input)); - for (let output of json.outputs) + for (const output of json.outputs) this.outputs.push(Output.fromJSON(output)); this.locktime = json.locktime; @@ -2344,7 +2344,7 @@ TX.prototype.fromWitnessReader = function fromWitnessReader(br) { witness = br.offset; - for (let input of this.inputs) { + for (const input of this.inputs) { input.witness.fromReader(br); if (input.witness.items.length > 0) hasWitness = true; @@ -2382,8 +2382,8 @@ TX.prototype.fromWitnessReader = function fromWitnessReader(br) { */ TX.prototype.frameNormal = function frameNormal() { - let raw = this.getNormalSizes(); - let bw = new StaticWriter(raw.size); + const raw = this.getNormalSizes(); + const bw = new StaticWriter(raw.size); this.writeNormal(bw); raw.data = bw.render(); return raw; @@ -2397,8 +2397,8 @@ TX.prototype.frameNormal = function frameNormal() { */ TX.prototype.frameWitness = function frameWitness() { - let raw = this.getWitnessSizes(); - let bw = new StaticWriter(raw.size); + const raw = this.getWitnessSizes(); + const bw = new StaticWriter(raw.size); this.writeWitness(bw); raw.data = bw.render(); return raw; @@ -2419,12 +2419,12 @@ TX.prototype.writeNormal = function writeNormal(bw) { bw.writeVarint(this.inputs.length); - for (let input of this.inputs) + for (const input of this.inputs) input.toWriter(bw); bw.writeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) output.toWriter(bw); bw.writeU32(this.locktime); @@ -2452,17 +2452,17 @@ TX.prototype.writeWitness = function writeWitness(bw) { bw.writeVarint(this.inputs.length); - for (let input of this.inputs) + for (const input of this.inputs) input.toWriter(bw); bw.writeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) output.toWriter(bw); witness = bw.written; - for (let input of this.inputs) + for (const input of this.inputs) input.witness.toWriter(bw); witness = bw.written - witness; @@ -2488,12 +2488,12 @@ TX.prototype.getNormalSizes = function getNormalSizes() { base += encoding.sizeVarint(this.inputs.length); - for (let input of this.inputs) + for (const input of this.inputs) base += input.getSize(); base += encoding.sizeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) base += output.getSize(); base += 4; @@ -2516,14 +2516,14 @@ TX.prototype.getWitnessSizes = function getWitnessSizes() { base += encoding.sizeVarint(this.inputs.length); - for (let input of this.inputs) { + for (const input of this.inputs) { base += input.getSize(); witness += input.witness.getVarSize(); } base += encoding.sizeVarint(this.outputs.length); - for (let output of this.outputs) + for (const output of this.outputs) base += output.getSize(); base += 4; diff --git a/lib/primitives/txmeta.js b/lib/primitives/txmeta.js index 19f13ff0f..dbc1f727f 100644 --- a/lib/primitives/txmeta.js +++ b/lib/primitives/txmeta.js @@ -126,7 +126,7 @@ TXMeta.prototype.inspect = function inspect() { */ TXMeta.prototype.format = function format(view) { - let data = this.tx.format(view, null, this.index); + const data = this.tx.format(view, null, this.index); data.mtime = this.mtime; data.height = this.height; data.block = this.block ? util.revHex(this.block) : null; @@ -152,7 +152,7 @@ TXMeta.prototype.toJSON = function toJSON() { */ TXMeta.prototype.getJSON = function getJSON(network, view) { - let json = this.tx.getJSON(network, view, null, this.index); + const json = this.tx.getJSON(network, view, null, this.index); json.mtime = this.mtime; json.height = this.height; json.block = this.block ? util.revHex(this.block) : null; @@ -226,8 +226,8 @@ TXMeta.prototype.getSize = function getSize() { */ TXMeta.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); this.tx.toWriter(bw); @@ -253,7 +253,7 @@ TXMeta.prototype.toRaw = function toRaw() { */ TXMeta.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.tx.fromReader(br); diff --git a/lib/protocol/consensus.js b/lib/protocol/consensus.js index ea671eeb4..1cf8bc346 100644 --- a/lib/protocol/consensus.js +++ b/lib/protocol/consensus.js @@ -226,8 +226,8 @@ exports.BIP16_TIME = 1333238400; */ exports.fromCompact = function fromCompact(compact) { - let exponent = compact >>> 24; - let negative = (compact >>> 23) & 1; + const exponent = compact >>> 24; + const negative = (compact >>> 23) & 1; let mantissa = compact & 0x7fffff; let num; @@ -293,7 +293,7 @@ exports.toCompact = function toCompact(num) { */ exports.verifyPOW = function verifyPOW(hash, bits) { - let target = exports.fromCompact(bits); + const target = exports.fromCompact(bits); if (target.isNeg() || target.cmpn(0) === 0) return false; @@ -313,7 +313,7 @@ exports.verifyPOW = function verifyPOW(hash, bits) { */ exports.getReward = function getReward(height, interval) { - let halvings = Math.floor(height / interval); + const halvings = Math.floor(height / interval); assert(height >= 0, 'Bad height for reward.'); @@ -341,8 +341,8 @@ exports.getReward = function getReward(height, interval) { */ exports.hasBit = function hasBit(version, bit) { - let bits = version & exports.VERSION_TOP_MASK; - let topBits = exports.VERSION_TOP_BITS; - let mask = 1 << bit; + const bits = version & exports.VERSION_TOP_MASK; + const topBits = exports.VERSION_TOP_BITS; + const mask = 1 << bit; return (bits >>> 0) === topBits && (version & mask) !== 0; }; diff --git a/lib/protocol/network.js b/lib/protocol/network.js index ca25ca331..c68fbd836 100644 --- a/lib/protocol/network.js +++ b/lib/protocol/network.js @@ -91,16 +91,16 @@ Network.simnet = null; Network.prototype._init = function _init() { let bits = 0; - for (let deployment of this.deploys) + for (const deployment of this.deploys) bits |= 1 << deployment.bit; bits |= consensus.VERSION_TOP_MASK; this.unknownBits = ~bits; - for (let key of Object.keys(this.checkpointMap)) { - let hash = this.checkpointMap[key]; - let height = +key; + for (const key of Object.keys(this.checkpointMap)) { + const hash = this.checkpointMap[key]; + const height = +key; this.checkpoints.push({ hash: hash, height: height }); } @@ -115,7 +115,7 @@ Network.prototype._init = function _init() { */ Network.prototype.byBit = function byBit(bit) { - let index = util.binarySearch(this.deploys, bit, cmpBit); + const index = util.binarySearch(this.deploys, bit, cmpBit); if (index === -1) return null; return this.deploys[index]; @@ -245,7 +245,7 @@ Network.by = function by(value, compare, network, name) { throw new Error(`Network mismatch for ${name}.`); } - for (let type of networks.types) { + for (const type of networks.types) { network = networks[type]; if (compare(network, value)) return Network.get(type); @@ -415,7 +415,7 @@ function cmpPriv58(network, prefix) { } function cmpAddress(network, prefix) { - let prefixes = network.addressPrefix; + const prefixes = network.addressPrefix; switch (prefix) { case prefixes.pubkeyhash: diff --git a/lib/protocol/timedata.js b/lib/protocol/timedata.js index f09396201..2dfe1b5ad 100644 --- a/lib/protocol/timedata.js +++ b/lib/protocol/timedata.js @@ -49,7 +49,7 @@ util.inherits(TimeData, EventEmitter); */ TimeData.prototype.add = function add(id, time) { - let sample = time - util.now(); + const sample = time - util.now(); if (this.samples.length >= this.limit) return; @@ -69,7 +69,7 @@ TimeData.prototype.add = function add(id, time) { if (Math.abs(median) >= 70 * 60) { if (!this.checked) { let match = false; - for (let offset of this.samples) { + for (const 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 db804c82e..1cf1ace12 100644 --- a/lib/script/common.js +++ b/lib/script/common.js @@ -541,9 +541,9 @@ exports.isSignatureEncoding = function isSignatureEncoding(sig) { */ exports.formatStack = function formatStack(items) { - let out = []; + const out = []; - for (let item of items) + for (const item of items) out.push(item.toString('hex')); return out.join(' '); @@ -556,10 +556,10 @@ exports.formatStack = function formatStack(items) { */ exports.formatCode = function formatCode(code) { - let out = []; + const out = []; - for (let op of code) { - let data = op.data; + for (const op of code) { + const data = op.data; let value = op.value; if (data) { @@ -624,7 +624,7 @@ exports.formatItem = function formatItem(data, decode) { if (decode) { let symbol = ''; if (exports.isSignatureEncoding(data)) { - let type = data[data.length - 1]; + const type = data[data.length - 1]; symbol = exports.hashTypeByVal[type & 0x1f] || ''; @@ -650,12 +650,12 @@ exports.formatItem = function formatItem(data, decode) { */ exports.formatASM = function formatASM(code, decode) { - let out = []; + const out = []; if (code.length > 0 && code[0].value === exports.opcodes.OP_RETURN) decode = false; - for (let op of code) { + for (const op of code) { let data = op.data; let value = op.value; @@ -686,10 +686,10 @@ exports.formatASM = function formatASM(code, decode) { */ exports.formatStackASM = function formatStackASM(items, decode) { - let out = []; + const out = []; - for (let item of items) { - let data = exports.formatItem(item, decode); + for (const item of items) { + const data = exports.formatItem(item, decode); out.push(data); } diff --git a/lib/script/opcode.js b/lib/script/opcode.js index 57b98e9b9..a5ab8e909 100644 --- a/lib/script/opcode.js +++ b/lib/script/opcode.js @@ -150,7 +150,7 @@ Opcode.prototype.toWriter = function toWriter(bw) { */ Opcode.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -185,7 +185,7 @@ Opcode.prototype.getSize = function getSize() { */ Opcode.prototype.fromReader = function fromReader(br) { - let op = br.readU8(); + const op = br.readU8(); let size; if (op >= 0x01 && op <= 0x4b) { diff --git a/lib/script/program.js b/lib/script/program.js index 8c7e63212..f29339fc9 100644 --- a/lib/script/program.js +++ b/lib/script/program.js @@ -74,7 +74,7 @@ Program.prototype.getType = function getType() { */ Program.prototype.isUnknown = function isUnknown() { - let type = this.getType(); + const type = this.getType(); return type === scriptTypes.WITNESSMALFORMED || type === scriptTypes.NONSTANDARD; }; @@ -94,8 +94,8 @@ Program.prototype.isMalformed = function isMalformed() { */ Program.prototype.inspect = function inspect() { - let data = this.data.toString('hex'); - let type = common.typesByVal[this.getType()].toLowerCase(); + const data = this.data.toString('hex'); + const type = common.typesByVal[this.getType()].toLowerCase(); return ``; }; diff --git a/lib/script/script.js b/lib/script/script.js index b4ef532f0..527d53711 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -179,9 +179,9 @@ Script.fromOptions = function fromOptions(options) { */ Script.prototype.toArray = function toArray() { - let code = []; + const code = []; - for (let op of this.code) + for (const op of this.code) code.push(op.data || op.value); return code; @@ -204,7 +204,7 @@ Script.prototype.fromArray = function fromArray(code) { if (code[0] instanceof Opcode) return this.fromCode(code); - for (let op of code) { + for (const op of code) { if (Buffer.isBuffer(op)) { this.code.push(Opcode.fromData(op)); continue; @@ -331,7 +331,7 @@ Script.prototype.toASM = function toASM(decode) { Script.prototype.getCodeSize = function getCodeSize() { let size = 0; - for (let op of this.code) + for (const op of this.code) size += op.getSize(); return size; @@ -343,10 +343,10 @@ Script.prototype.getCodeSize = function getCodeSize() { */ Script.prototype.compile = function compile() { - let size = this.getCodeSize(); - let bw = new StaticWriter(size); + const size = this.getCodeSize(); + const bw = new StaticWriter(size); - for (let op of this.code) + for (const op of this.code) op.toWriter(bw); this.raw = bw.render(); @@ -411,13 +411,13 @@ Script.fromJSON = function fromJSON(json) { */ Script.prototype.getSubscript = function getSubscript(lastSep) { - let code = []; + const code = []; if (lastSep === 0) return this.clone(); for (let i = lastSep; i < this.code.length; i++) { - let op = this.code[i]; + const op = this.code[i]; if (op.value === -1) break; @@ -442,7 +442,7 @@ Script.prototype.removeSeparators = function removeSeparators() { // Optimizing for the common case: // Check for any separators first. - for (let op of this.code) { + for (const op of this.code) { if (op.value === -1) break; @@ -460,7 +460,7 @@ Script.prototype.removeSeparators = function removeSeparators() { // and remove them all. code = []; - for (let op of this.code) { + for (const op of this.code) { if (op.value === -1) break; @@ -488,8 +488,8 @@ Script.prototype.execute = function execute(stack, flags, tx, index, value, vers let opCount = 0; let negate = 0; let minimal = false; - let state = []; - let alt = []; + const state = []; + const alt = []; if (flags == null) flags = Script.flags.STANDARD_VERIFY_FLAGS; @@ -504,7 +504,7 @@ Script.prototype.execute = function execute(stack, flags, tx, index, value, vers throw new ScriptError('SCRIPT_SIZE'); for (let ip = 0; ip < this.code.length; ip++) { - let op = this.code[ip]; + const op = this.code[ip]; if (op.value === -1) throw new ScriptError('BAD_OPCODE', op, ip); @@ -1118,8 +1118,8 @@ Script.prototype.execute = function execute(stack, flags, tx, index, value, vers validateKey(key, flags, version); if (sig.length > 0) { - let type = sig[sig.length - 1]; - let hash = tx.signatureHash(index, subscript, value, type, version); + const type = sig[sig.length - 1]; + const hash = tx.signatureHash(index, subscript, value, type, version); res = checksig(hash, sig, key); } @@ -1185,22 +1185,22 @@ Script.prototype.execute = function execute(stack, flags, tx, index, value, vers subscript = this.getSubscript(lastSep); for (let j = 0; j < m; j++) { - let sig = stack.top(-isig - j); + const sig = stack.top(-isig - j); if (version === 0) subscript.removeData(sig); } res = true; while (res && m > 0) { - let sig = stack.top(-isig); - let key = stack.top(-ikey); + const sig = stack.top(-isig); + const key = stack.top(-ikey); validateSignature(sig, flags); validateKey(key, flags, version); if (sig.length > 0) { - let type = sig[sig.length - 1]; - let hash = tx.signatureHash(index, subscript, value, type, version); + const type = sig[sig.length - 1]; + const hash = tx.signatureHash(index, subscript, value, type, version); if (checksig(hash, sig, key)) { isig++; @@ -1328,13 +1328,13 @@ Script.array = function array(value) { */ Script.prototype.removeData = function removeData(data) { - let index = []; + const index = []; // We need to go forward first. We can't go // backwards (this is consensus code and we // need to be aware of bad pushes). for (let i = 0; i < this.code.length; i++) { - let op = this.code[i]; + const op = this.code[i]; if (op.value === -1) { // Can't reserialize @@ -1374,7 +1374,7 @@ Script.prototype.removeData = function removeData(data) { Script.prototype.indexOf = function indexOf(data) { for (let i = 0; i < this.code.length; i++) { - let op = this.code[i]; + const op = this.code[i]; if (op.value === -1) break; @@ -1396,7 +1396,7 @@ Script.prototype.indexOf = function indexOf(data) { */ Script.prototype.isCode = function isCode() { - for (let op of this.code) { + for (const op of this.code) { if (op.data) continue; @@ -1499,7 +1499,7 @@ Script.prototype.fromMultisig = function fromMultisig(m, n, keys) { this.push(Opcode.fromSmall(m)); - for (let key of keys) + for (const key of keys) this.push(key); this.push(Opcode.fromSmall(n)); @@ -1662,7 +1662,7 @@ Script.fromAddress = function fromAddress(address) { */ Script.prototype.fromCommitment = function fromCommitment(hash, flags) { - let bw = new StaticWriter(36); + const bw = new StaticWriter(36); bw.writeU32BE(0xaa21a9ed); bw.writeHash(hash); @@ -1759,12 +1759,12 @@ Script.prototype.isUnknown = function isUnknown() { */ Script.prototype.isStandard = function isStandard() { - let type = this.getType(); + const type = this.getType(); switch (type) { case scriptTypes.MULTISIG: { - let m = this.getSmall(0); - let n = this.getSmall(this.code.length - 2); + const m = this.getSmall(0); + const n = this.getSmall(this.code.length - 2); if (n < 1 || n > 3) return false; @@ -1925,7 +1925,7 @@ Script.prototype.isMultisig = function isMultisig(minimal) { return false; for (let i = 1; i < n + 1; i++) { - let op = this.code[i]; + const op = this.code[i]; if (!common.isKey(op.data)) return false; @@ -1985,7 +1985,7 @@ Script.prototype.isNulldata = function isNulldata(minimal) { } for (let i = 1; i < this.code.length; i++) { - let op = this.code[i]; + const op = this.code[i]; if (op.data) continue; @@ -2075,7 +2075,7 @@ Script.prototype.forWitness = function forWitness() { return this; if (this.isPubkey()) { - let hash = digest.hash160(this.get(0)); + const hash = digest.hash160(this.get(0)); return Script.fromProgram(0, hash); } @@ -2234,7 +2234,7 @@ Script.prototype.isMultisigInput = function isMultisigInput() { return false; for (let i = 1; i < this.code.length; i++) { - let op = this.code[i]; + const op = this.code[i]; if (!op.data) return false; @@ -2360,7 +2360,7 @@ Script.getCoinbaseHeight = function getCoinbaseHeight(raw) { */ Script.prototype.test = function test(filter) { - for (let op of this.code) { + for (const op of this.code) { if (op.value === -1) break; @@ -2400,7 +2400,7 @@ Script.prototype.push = function push(data) { */ Script.prototype.shift = function shift() { - let op = this.code.shift(); + const op = this.code.shift(); if (!op) return null; @@ -2414,7 +2414,7 @@ Script.prototype.shift = function shift() { */ Script.prototype.pop = function push(data) { - let op = this.code.pop(); + const op = this.code.pop(); if (!op) return null; @@ -2429,7 +2429,7 @@ Script.prototype.pop = function push(data) { */ Script.prototype.remove = function remove(i) { - let op = this.code.splice(i, 1)[0]; + const op = this.code.splice(i, 1)[0]; if (!op) return null; @@ -2455,7 +2455,7 @@ Script.prototype.insert = function insert(i, data) { */ Script.prototype.get = function get(i) { - let op = this.code[i]; + const op = this.code[i]; if (!op) return null; @@ -2470,7 +2470,7 @@ Script.prototype.get = function get(i) { */ Script.prototype.getSmall = function getSmall(i) { - let op = this.code[i]; + const op = this.code[i]; if (!op) return -1; @@ -2485,8 +2485,8 @@ Script.prototype.getSmall = function getSmall(i) { */ Script.prototype.getNumber = function getNumber(i) { - let small = this.getSmall(i); - let op = this.code[i]; + const small = this.getSmall(i); + const op = this.code[i]; if (small !== -1) return new BN(small); @@ -2504,7 +2504,7 @@ Script.prototype.getNumber = function getNumber(i) { */ Script.prototype.getString = function getString(i) { - let op = this.code[i]; + const op = this.code[i]; if (!op || !op.data) return null; @@ -2560,7 +2560,7 @@ Script.isSignature = function isSignature(sig) { */ Script.prototype.isPushOnly = function isPushOnly() { - for (let op of this.code) { + for (const op of this.code) { if (op.data) continue; @@ -2585,7 +2585,7 @@ Script.prototype.getSigops = function getSigops(accurate) { let total = 0; let lastOp = -1; - for (let op of this.code) { + for (const op of this.code) { if (op.data) continue; @@ -2659,7 +2659,7 @@ Script.witnessSigops = function witnessSigops(program, witness) { return 1; if (program.data.length === 32 && witness.items.length > 0) { - let redeem = witness.getRedeem(); + const redeem = witness.getRedeem(); return redeem.getSigops(true); } } @@ -2686,7 +2686,7 @@ Script.prototype.getWitnessSigops = function getWitnessSigops(input, witness) { // false if one is found. Even the bitcoind code // does not check the return value of GetOp. if (this.isScripthash() && input.isPushOnly()) { - let redeem = input.getRedeem(); + const redeem = input.getRedeem(); if (redeem && redeem.isProgram()) return Script.witnessSigops(redeem.toProgram(), witness); } @@ -2889,8 +2889,8 @@ Script.verify = function verify(input, witness, output, tx, i, value, flags) { */ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i, value) { - let program = output.toProgram(); - let stack = witness.toStack(); + const program = output.toProgram(); + const stack = witness.toStack(); let witnessScript, redeem; assert(program, 'verifyProgram called on non-witness-program.'); @@ -2963,7 +2963,7 @@ Script.verifyProgram = function verifyProgram(witness, output, flags, tx, i, val Script.verifyMast = function verifyMast(program, stack, output, flags, tx, i, value) { let mastRoot = new BufferWriter(); let scriptRoot = new BufferWriter(); - let scripts = new BufferWriter(); + const scripts = new BufferWriter(); let version = 0; let pathdata, depth, path, posdata, pos; let metadata, subscripts, ops, script; @@ -3100,7 +3100,7 @@ Script.prototype.fromReader = function fromReader(br) { */ Script.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); + const br = new BufferReader(data, true); this.raw = data; diff --git a/lib/script/sigcache.js b/lib/script/sigcache.js index c9940f821..dce50075f 100644 --- a/lib/script/sigcache.js +++ b/lib/script/sigcache.js @@ -64,8 +64,8 @@ SigCache.prototype.add = function add(hash, sig, key) { this.valid.set(hash, new SigCacheEntry(sig, key)); if (this.keys.length >= this.size) { - let i = Math.floor(Math.random() * this.keys.length); - let k = this.keys[i]; + const i = Math.floor(Math.random() * this.keys.length); + const k = this.keys[i]; this.valid.delete(k); this.keys[i] = hash; } else { @@ -82,7 +82,7 @@ SigCache.prototype.add = function add(hash, sig, key) { */ SigCache.prototype.has = function has(hash, sig, key) { - let entry = this.valid.get(hash); + const entry = this.valid.get(hash); if (!entry) return false; diff --git a/lib/script/witness.js b/lib/script/witness.js index 263a90ebb..44b329d84 100644 --- a/lib/script/witness.js +++ b/lib/script/witness.js @@ -278,7 +278,7 @@ Witness.prototype.isUnknownInput = function isUnknownInput() { */ Witness.prototype.test = function test(filter) { - for (let item of this.items) { + for (const item of this.items) { if (item.length === 0) continue; @@ -335,7 +335,7 @@ Witness.prototype.indexOf = function indexOf(data) { Witness.prototype.getSize = function getSize() { let size = 0; - for (let item of this.items) + for (const item of this.items) size += encoding.sizeVarBytes(item); return size; @@ -359,7 +359,7 @@ Witness.prototype.getVarSize = function getVarSize() { Witness.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.items.length); - for (let item of this.items) + for (const item of this.items) bw.writeVarBytes(item); return bw; @@ -372,7 +372,7 @@ Witness.prototype.toWriter = function toWriter(bw) { */ Witness.prototype.toRaw = function toRaw() { - let size = this.getVarSize(); + const size = this.getVarSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -482,7 +482,7 @@ Witness.prototype.get = function get(i) { */ Witness.prototype.getSmall = function getSmall(i) { - let item = this.items[i]; + const item = this.items[i]; if (!item || item.length > 1) return -1; if (item.length === 0) @@ -499,7 +499,7 @@ Witness.prototype.getSmall = function getSmall(i) { */ Witness.prototype.getNumber = function getNumber(i) { - let item = this.items[i]; + const item = this.items[i]; if (!item || item.length > 5) return; return common.num(item, false, 5); @@ -512,7 +512,7 @@ Witness.prototype.getNumber = function getNumber(i) { */ Witness.prototype.getString = function getString(i) { - let item = this.items[i]; + const item = this.items[i]; if (!item) return; return item.toString('utf8'); @@ -576,7 +576,7 @@ Witness.encodeItem = function encodeItem(data) { */ Witness.prototype.fromReader = function fromReader(br) { - let count = br.readVarint(); + const count = br.readVarint(); for (let i = 0; i < count; i++) this.items.push(br.readVarBytes()); @@ -634,7 +634,7 @@ Witness.prototype.fromString = function fromString(items) { items = items.split(/\s+/); } - for (let item of items) + for (const item of items) this.items.push(Buffer.from(item, 'hex')); return this; diff --git a/lib/utils/asn1.js b/lib/utils/asn1.js index cde6e0ced..6936be9b4 100644 --- a/lib/utils/asn1.js +++ b/lib/utils/asn1.js @@ -45,7 +45,7 @@ const ASN1 = exports; ASN1.readTag = function readTag(br) { let type = br.readU8(); - let primitive = (type & 0x20) === 0; + const primitive = (type & 0x20) === 0; let oct; if ((type & 0x1f) === 0x1f) { @@ -112,7 +112,7 @@ ASN1.readSize = function readSize(br, primitive) { */ ASN1.readSeq = function readSeq(br) { - let tag = ASN1.implicit(br, 0x10); + const tag = ASN1.implicit(br, 0x10); return br.readBytes(tag.size); }; @@ -125,7 +125,7 @@ ASN1.readSeq = function readSeq(br) { */ ASN1.implicit = function implicit(br, type) { - let tag = ASN1.readTag(br); + const tag = ASN1.readTag(br); if (tag.type !== type) throw new Error(`Unexpected tag: ${tag.type}.`); return tag; @@ -139,8 +139,8 @@ ASN1.implicit = function implicit(br, type) { */ ASN1.explicit = function explicit(br, type) { - let offset = br.offset; - let tag = ASN1.readTag(br); + const offset = br.offset; + const tag = ASN1.readTag(br); if (tag.type !== type) { br.offset = offset; return false; @@ -166,8 +166,8 @@ ASN1.seq = function seq(br) { */ ASN1.readInt = function readInt(br, readNum) { - let tag = ASN1.implicit(br, 0x02); - let num = br.readBytes(tag.size); + const tag = ASN1.implicit(br, 0x02); + const num = br.readBytes(tag.size); if (readNum) return num.readUIntBE(0, num.length); @@ -196,8 +196,8 @@ ASN1.readExplicitInt = function readExplicitInt(br, type, readNum) { */ ASN1.readBitstr = function readBitstr(br) { - let tag = ASN1.implicit(br, 0x03); - let str = br.readBytes(tag.size); + const tag = ASN1.implicit(br, 0x03); + const str = br.readBytes(tag.size); return ASN1.alignBitstr(str); }; @@ -208,7 +208,7 @@ ASN1.readBitstr = function readBitstr(br) { */ ASN1.readString = function readString(br) { - let tag = ASN1.readTag(br); + const tag = ASN1.readTag(br); let str; switch (tag.type) { @@ -243,10 +243,10 @@ ASN1.readString = function readString(br) { */ ASN1.alignBitstr = function alignBitstr(data) { - let padding = data[0]; - let bits = (data.length - 1) * 8 - padding; - let buf = data.slice(1); - let shift = 8 - (bits % 8); + const padding = data[0]; + const bits = (data.length - 1) * 8 - padding; + const buf = data.slice(1); + const shift = 8 - (bits % 8); let i, out; if (shift === 8 || buf.length === 0) @@ -270,7 +270,7 @@ ASN1.alignBitstr = function alignBitstr(data) { */ ASN1.readCert = function readCert(br) { - let buf = br; + const buf = br; buf.start(); @@ -291,7 +291,7 @@ ASN1.readCert = function readCert(br) { */ ASN1.readTBS = function readTBS(br) { - let buf = br; + const buf = br; buf.start(); @@ -330,7 +330,7 @@ ASN1.readPubkey = function readPubkey(br) { */ ASN1.readName = function readName(br) { - let values = []; + const values = []; br = ASN1.seq(br); @@ -367,8 +367,8 @@ ASN1.readValidity = function readValidity(br) { */ ASN1.readTime = function readTime(br) { - let tag = ASN1.readTag(br); - let str = br.readString('ascii', tag.size); + const tag = ASN1.readTag(br); + const str = br.readString('ascii', tag.size); let year, mon, day, hour, min, sec; switch (tag.type) { @@ -406,8 +406,8 @@ ASN1.readTime = function readTime(br) { */ ASN1.readOID = function readOID(br) { - let tag = ASN1.implicit(br, 0x06); - let data = br.readBytes(tag.size); + const tag = ASN1.implicit(br, 0x06); + const data = br.readBytes(tag.size); return ASN1.formatOID(data); }; @@ -418,8 +418,8 @@ ASN1.readOID = function readOID(br) { */ ASN1.formatOID = function formatOID(data) { - let br = new BufferReader(data); - let ids = []; + const br = new BufferReader(data); + const ids = []; let ident = 0; let subident = 0; let result, first, second; diff --git a/lib/utils/asyncemitter.js b/lib/utils/asyncemitter.js index 3e6c18f3f..7b16eac5e 100644 --- a/lib/utils/asyncemitter.js +++ b/lib/utils/asyncemitter.js @@ -180,7 +180,7 @@ AsyncEmitter.prototype.removeAllListeners = function removeAllListeners(type) { AsyncEmitter.prototype.listeners = function listeners(type) { let listeners, listener; - let result = []; + const result = []; assert(typeof type === 'string', '`type` must be a string.'); diff --git a/lib/utils/asyncobject.js b/lib/utils/asyncobject.js index e7546180b..d66229f38 100644 --- a/lib/utils/asyncobject.js +++ b/lib/utils/asyncobject.js @@ -43,7 +43,7 @@ util.inherits(AsyncObject, EventEmitter); */ AsyncObject.prototype.open = async function open() { - let unlock = await this._asyncLock.lock(); + const unlock = await this._asyncLock.lock(); try { return await this.__open(); } finally { @@ -87,7 +87,7 @@ AsyncObject.prototype.__open = async function open() { */ AsyncObject.prototype.close = async function close() { - let unlock = await this._asyncLock.lock(); + const unlock = await this._asyncLock.lock(); try { return await this.__close(); } finally { @@ -199,7 +199,7 @@ AsyncObject.prototype.fireHook = async function fireHook(type) { if (!listeners || listeners.length === 0) return; - for (let handler of listeners) { + for (const handler of listeners) { switch (arguments.length) { case 1: await handler(); diff --git a/lib/utils/base32.js b/lib/utils/base32.js index b6c41f357..8d3445239 100644 --- a/lib/utils/base32.js +++ b/lib/utils/base32.js @@ -78,7 +78,7 @@ exports.encode = function encode(data) { */ exports.decode = function decode(str) { - let data = Buffer.allocUnsafe(str.length * 5 / 8 | 0); + const data = Buffer.allocUnsafe(str.length * 5 / 8 | 0); let mode = 0; let left = 0; let j = 0; diff --git a/lib/utils/bech32.js b/lib/utils/bech32.js index f827de096..5258741f5 100644 --- a/lib/utils/bech32.js +++ b/lib/utils/bech32.js @@ -56,7 +56,7 @@ const TABLE = [ */ function polymod(pre) { - let b = pre >>> 25; + const b = pre >>> 25; return ((pre & 0x1ffffff) << 5) ^ (-((b >> 0) & 1) & 0x3b6a57b2) ^ (-((b >> 1) & 1) & 0x26508e6d) @@ -217,7 +217,7 @@ function deserialize(str) { function convert(data, output, frombits, tobits, pad, off) { let acc = 0; let bits = 0; - let maxv = (1 << tobits) - 1; + const maxv = (1 << tobits) - 1; let j = 0; let i, value; @@ -259,7 +259,7 @@ function convert(data, output, frombits, tobits, pad, off) { */ function encode(hrp, version, hash) { - let output = POOL65; + const output = POOL65; let data; if (version < 0 || version > 16) @@ -283,7 +283,7 @@ if (native) */ function decode(str) { - let [hrp, data] = deserialize(str); + const [hrp, data] = deserialize(str); let version, hash, output; if (data.length === 0 || data.length > 65) diff --git a/lib/utils/bloom.js b/lib/utils/bloom.js index fe7a6181b..752a2fb00 100644 --- a/lib/utils/bloom.js +++ b/lib/utils/bloom.js @@ -198,7 +198,7 @@ Bloom.prototype.add = function add(val, enc) { val = Buffer.from(val, enc); for (let i = 0; i < this.n; i++) { - let index = this.hash(val, i); + const index = this.hash(val, i); this.filter[index >>> 3] |= 1 << (7 & index); } }; @@ -215,7 +215,7 @@ Bloom.prototype.test = function test(val, enc) { val = Buffer.from(val, enc); for (let i = 0; i < this.n; i++) { - let index = this.hash(val, i); + const index = this.hash(val, i); if ((this.filter[index >>> 3] & (1 << (7 & index))) === 0) return false; } @@ -238,7 +238,7 @@ Bloom.prototype.added = function added(val, enc) { val = Buffer.from(val, enc); for (let i = 0; i < this.n; i++) { - let index = this.hash(val, i); + const index = this.hash(val, i); if (!ret && (this.filter[index >>> 3] & (1 << (7 & index))) === 0) ret = true; this.filter[index >>> 3] |= 1 << (7 & index); @@ -327,7 +327,7 @@ Bloom.prototype.toWriter = function toWriter(bw) { */ Bloom.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; diff --git a/lib/utils/co.js b/lib/utils/co.js index a3ef99cc6..55d4fbd27 100644 --- a/lib/utils/co.js +++ b/lib/utils/co.js @@ -21,7 +21,7 @@ const assert = require('assert'); function exec(gen) { return new Promise((resolve, reject) => { - let step = (value, rejection) => { + const step = (value, rejection) => { let next; try { @@ -68,7 +68,7 @@ function exec(gen) { */ function spawn(generator, self) { - let gen = generator.call(self); + const gen = generator.call(self); return exec(gen); } @@ -82,7 +82,7 @@ function spawn(generator, self) { function co(generator) { return function() { - let gen = generator.apply(this, arguments); + const gen = generator.apply(this, arguments); return exec(gen); }; } @@ -187,9 +187,9 @@ function callbackify(func) { */ async function every(jobs) { - let result = await Promise.all(jobs); + const result = await Promise.all(jobs); - for (let item of result) { + for (const item of result) { if (!item) return false; } @@ -207,12 +207,12 @@ async function every(jobs) { */ function startInterval(func, time, self) { - let ctx = { + const ctx = { timer: null, stopped: false }; - let cb = async () => { + const cb = async () => { assert(ctx.timer != null); ctx.timer = null; diff --git a/lib/utils/encoding.js b/lib/utils/encoding.js index 2176f8081..a248addf5 100644 --- a/lib/utils/encoding.js +++ b/lib/utils/encoding.js @@ -345,7 +345,7 @@ encoding.read53BE = function read53BE(data, off) { */ encoding._write64 = function _write64(dst, num, off, be) { - let negative = num < 0; + const negative = num < 0; let hi, lo; if (negative) { @@ -448,7 +448,7 @@ encoding.write64BE = function write64BE(dst, num, off) { */ encoding.readU64BN = function readU64BN(data, off) { - let num = data.slice(off, off + 8); + const num = data.slice(off, off + 8); return new BN(num, 'le'); }; @@ -460,7 +460,7 @@ encoding.readU64BN = function readU64BN(data, off) { */ encoding.readU64BEBN = function readU64BEBN(data, off) { - let num = data.slice(off, off + 8); + const num = data.slice(off, off + 8); return new BN(num, 'be'); }; @@ -472,7 +472,7 @@ encoding.readU64BEBN = function readU64BEBN(data, off) { */ encoding.read64BN = function read64BN(data, off) { - let num = data.slice(off, off + 8); + const num = data.slice(off, off + 8); if (num[num.length - 1] & 0x80) return new BN(num, 'le').notn(64).addn(1).neg(); @@ -487,7 +487,7 @@ encoding.read64BN = function read64BN(data, off) { */ encoding.read64BEBN = function read64BEBN(data, off) { - let num = data.slice(off, off + 8); + const num = data.slice(off, off + 8); if (num[0] & 0x80) return new BN(num, 'be').notn(64).addn(1).neg(); @@ -506,7 +506,7 @@ encoding.read64BEBN = function read64BEBN(data, off) { */ encoding._write64BN = function _write64BN(dst, num, off, be) { - let bits = num.bitLength(); + const bits = num.bitLength(); if (bits <= 53) return encoding._write64(dst, num.toNumber(), off, be); @@ -786,7 +786,7 @@ encoding.readVarint2 = function readVarint2(data, off) { */ encoding.writeVarint2 = function writeVarint2(dst, num, off) { - let tmp = []; + const tmp = []; let len = 0; for (;;) { @@ -903,7 +903,7 @@ encoding.readVarint2BN = function readVarint2BN(data, off) { */ encoding.writeVarint2BN = function writeVarint2BN(dst, num, off) { - let tmp = []; + const tmp = []; let len = 0; if (num.bitLength() <= 53) @@ -957,7 +957,7 @@ encoding.sizeVarint2BN = function sizeVarint2BN(num) { */ encoding.U8 = function U8(num) { - let data = Buffer.allocUnsafe(1); + const data = Buffer.allocUnsafe(1); data[0] = num >>> 0; return data; }; @@ -969,7 +969,7 @@ encoding.U8 = function U8(num) { */ encoding.U32 = function U32(num) { - let data = Buffer.allocUnsafe(4); + const data = Buffer.allocUnsafe(4); data.writeUInt32LE(num, 0, true); return data; }; @@ -981,7 +981,7 @@ encoding.U32 = function U32(num) { */ encoding.U32BE = function U32BE(num) { - let data = Buffer.allocUnsafe(4); + const data = Buffer.allocUnsafe(4); data.writeUInt32BE(num, 0, true); return data; }; diff --git a/lib/utils/fs.js b/lib/utils/fs.js index 0e35f3ecf..b696f2cd8 100644 --- a/lib/utils/fs.js +++ b/lib/utils/fs.js @@ -90,11 +90,11 @@ exports.mkdirpSync = function mkdirpSync(dir, mode) { if (mode == null) mode = 0o750; - for (let part of parts) { + for (const part of parts) { path += part; try { - let stat = exports.statSync(path); + const stat = exports.statSync(path); if (!stat.isDirectory()) throw new Error('Could not create directory.'); } catch (e) { @@ -114,11 +114,11 @@ exports.mkdirp = async function mkdirp(dir, mode) { if (mode == null) mode = 0o750; - for (let part of parts) { + for (const part of parts) { path += part; try { - let stat = await exports.stat(path); + const stat = await exports.stat(path); if (!stat.isDirectory()) throw new Error('Could not create directory.'); } catch (e) { diff --git a/lib/utils/gcs.js b/lib/utils/gcs.js index b11335472..1e98a6106 100644 --- a/lib/utils/gcs.js +++ b/lib/utils/gcs.js @@ -28,25 +28,25 @@ function GCSFilter() { } GCSFilter.prototype.hash = function _hash(enc) { - let hash = digest.hash256(this.data); + const hash = digest.hash256(this.data); return enc === 'hex' ? hash.toString('hex') : hash; }; GCSFilter.prototype.header = function header(prev) { - let data = SCRATCH; - let hash = this.hash(); + const data = SCRATCH; + const hash = this.hash(); hash.copy(data, 0); prev.copy(data, 32); return digest.hash256(data); }; GCSFilter.prototype.match = function match(key, data) { - let br = new BitReader(this.data); - let term = siphash(data, key).imod(this.m); + const br = new BitReader(this.data); + const term = siphash(data, key).imod(this.m); let last = new Int64(0); while (last.lt(term)) { - let value = this.readU64(br); + const value = this.readU64(br); if (value === EOF) return false; @@ -63,15 +63,15 @@ GCSFilter.prototype.match = function match(key, data) { }; GCSFilter.prototype.matchAny = function matchAny(key, items) { - let br = new BitReader(this.data); - let last1 = new Int64(0); - let values = []; + const br = new BitReader(this.data); + const last1 = new Int64(0); + const values = []; let i, last2; assert(items.length > 0); - for (let item of items) { - let hash = siphash(item, key).imod(this.m); + for (const item of items) { + const hash = siphash(item, key).imod(this.m); values.push(hash); } @@ -81,7 +81,7 @@ GCSFilter.prototype.matchAny = function matchAny(key, items) { i = 1; for (;;) { - let cmp = last1.cmp(last2); + const cmp = last1.cmp(last2); let value; if (cmp === 0) @@ -118,7 +118,7 @@ GCSFilter.prototype.readU64 = function readU64(br) { }; GCSFilter.prototype._readU64 = function _readU64(br) { - let num = new Int64(0); + const num = new Int64(0); let rem; // Unary @@ -135,21 +135,21 @@ GCSFilter.prototype.toBytes = function toBytes() { }; GCSFilter.prototype.toNBytes = function toNBytes() { - let data = Buffer.allocUnsafe(4 + this.data.length); + const data = Buffer.allocUnsafe(4 + this.data.length); data.writeUInt32BE(this.n, 0, true); this.data.copy(data, 4); return data; }; GCSFilter.prototype.toPBytes = function toPBytes() { - let data = Buffer.allocUnsafe(1 + this.data.length); + const data = Buffer.allocUnsafe(1 + this.data.length); data.writeUInt8(this.p, 0, true); this.data.copy(data, 1); return data; }; GCSFilter.prototype.toNPBytes = function toNPBytes() { - let data = Buffer.allocUnsafe(5 + this.data.length); + const data = Buffer.allocUnsafe(5 + this.data.length); data.writeUInt32BE(this.n, 0, true); data.writeUInt8(this.p, 4, true); this.data.copy(data, 5); @@ -162,9 +162,9 @@ GCSFilter.prototype.toRaw = function toRaw() { }; GCSFilter.prototype.fromItems = function fromItems(P, key, items) { - let bw = new BitWriter(); + const bw = new BitWriter(); let last = new Int64(0); - let values = []; + const values = []; assert(typeof P === 'number' && isFinite(P)); assert(P >= 0 && P <= 32); @@ -180,17 +180,17 @@ GCSFilter.prototype.fromItems = function fromItems(P, key, items) { this.p = P; this.m = Int64(this.n).ishln(this.p); - for (let item of items) { + for (const item of items) { assert(Buffer.isBuffer(item)); - let hash = siphash(item, key).imod(this.m); + const hash = siphash(item, key).imod(this.m); values.push(hash); } values.sort(compare); - for (let hash of values) { - let rem = hash.sub(last).imaskn(this.p); - let value = hash.sub(last).isub(rem).ishrn(this.p); + for (const hash of values) { + const rem = hash.sub(last).imaskn(this.p); + const value = hash.sub(last).isub(rem).ishrn(this.p); last = hash; @@ -264,19 +264,19 @@ GCSFilter.prototype.fromRaw = function fromRaw(data) { }; GCSFilter.prototype.fromBlock = function fromBlock(block) { - let hash = block.hash(); - let key = hash.slice(0, 16); - let items = []; + const hash = block.hash(); + const key = hash.slice(0, 16); + const items = []; for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; if (i > 0) { - for (let input of tx.inputs) + for (const input of tx.inputs) items.push(input.prevout.toRaw()); } - for (let output of tx.outputs) + for (const output of tx.outputs) getPushes(items, output.script); } @@ -284,17 +284,17 @@ GCSFilter.prototype.fromBlock = function fromBlock(block) { }; GCSFilter.prototype.fromExtended = function fromExtended(block) { - let hash = block.hash(); - let key = hash.slice(0, 16); - let items = []; + const hash = block.hash(); + const key = hash.slice(0, 16); + const items = []; for (let i = 0; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; items.push(tx.hash()); if (i > 0) { - for (let input of tx.inputs) { + for (const input of tx.inputs) { getWitness(items, input.witness); getPushes(items, input.script); } @@ -385,14 +385,14 @@ BitWriter.prototype.writeBits = function writeBits(num, count) { num <<= 32 - count; while (count >= 8) { - let ch = num >>> 24; + const ch = num >>> 24; this.writeByte(ch); num <<= 8; count -= 8; } while (count > 0) { - let bit = num >>> 31; + const bit = num >>> 31; this.writeBit(bit); num <<= 1; count -= 1; @@ -412,7 +412,7 @@ BitWriter.prototype.writeBits64 = function writeBits64(num, count) { }; BitWriter.prototype.render = function render() { - let data = Buffer.allocUnsafe(this.stream.length); + const data = Buffer.allocUnsafe(this.stream.length); for (let i = 0; i < this.stream.length; i++) data[i] = this.stream[i]; @@ -506,7 +506,7 @@ BitReader.prototype.readBits = function readBits(count) { }; BitReader.prototype.readBits64 = function readBits(count) { - let num = new Int64(); + const num = new Int64(); assert(count >= 0); assert(count <= 64); @@ -530,12 +530,12 @@ function compare(a, b) { } function siphash(data, key) { - let [hi, lo] = siphash24(data, key); + const [hi, lo] = siphash24(data, key); return new Int64().join(hi, lo); } function getPushes(items, script) { - for (let op of script.code) { + for (const op of script.code) { if (!op.data || op.data.length === 0) continue; @@ -544,7 +544,7 @@ function getPushes(items, script) { } function getWitness(items, witness) { - for (let item of witness.items) { + for (const item of witness.items) { if (item.length === 0) continue; diff --git a/lib/utils/heap.js b/lib/utils/heap.js index 5a6ef996c..37fab199f 100644 --- a/lib/utils/heap.js +++ b/lib/utils/heap.js @@ -31,7 +31,7 @@ function Heap(compare) { */ Heap.prototype.init = function init() { - let n = this.items.length; + const n = this.items.length; let i; if (n <= 1) @@ -127,8 +127,8 @@ Heap.prototype.remove = function remove(i) { */ Heap.prototype.swap = function swap(a, b) { - let x = this.items[a]; - let y = this.items[b]; + const x = this.items[a]; + const y = this.items[b]; this.items[a] = y; this.items[b] = x; }; @@ -208,8 +208,8 @@ Heap.prototype.up = function up(i) { */ Heap.prototype.toArray = function toArray() { - let heap = new Heap(); - let result = []; + const heap = new Heap(); + const result = []; heap.compare = this.compare; heap.items = this.items.slice(); @@ -228,7 +228,7 @@ Heap.prototype.toArray = function toArray() { */ Heap.fromArray = function fromArray(compare, items) { - let heap = new Heap(); + const heap = new Heap(); heap.set(compare); heap.items = items; heap.init(); diff --git a/lib/utils/ip.js b/lib/utils/ip.js index f7f9e0673..946e5e858 100644 --- a/lib/utils/ip.js +++ b/lib/utils/ip.js @@ -271,7 +271,7 @@ IP.isMapped = function isMapped(raw) { */ IP.toBuffer = function toBuffer(str) { - let raw = Buffer.allocUnsafe(16); + const raw = Buffer.allocUnsafe(16); assert(typeof str === 'string'); @@ -304,7 +304,7 @@ IP.toBuffer = function toBuffer(str) { */ IP.parseV4 = function parseV4(str, raw, offset) { - let parts = str.split('.'); + const parts = str.split('.'); assert(parts.length === 4); @@ -329,14 +329,14 @@ IP.parseV4 = function parseV4(str, raw, offset) { */ IP.parseV6 = function parseV6(str, raw, offset) { - let parts = str.split(':'); + const parts = str.split(':'); let missing = 8 - parts.length; - let start = offset; + const start = offset; let colon = false; assert(parts.length >= 2, 'Not an IPv6 address.'); - for (let word of parts) { + for (const word of parts) { if (IP.isV4String(word)) missing--; } @@ -857,9 +857,9 @@ IP.getReachability = function getReachability(src, dest) { const IPV6_STRONG = 5; const PRIVATE = 6; - let srcNet = IP.getNetwork(src); - let destNet = IP.getNetwork(dest); - let types = IP.types; + const srcNet = IP.getNetwork(src); + const destNet = IP.getNetwork(dest); + const types = IP.types; if (!IP.isRoutable(src)) return UNREACHABLE; @@ -980,14 +980,14 @@ IP.isEqual = function isEqual(a, b) { */ IP.getInterfaces = function _getInterfaces(name, family) { - let interfaces = os.networkInterfaces(); - let result = []; + const interfaces = os.networkInterfaces(); + const result = []; - for (let key of Object.keys(interfaces)) { - let items = interfaces[key]; + for (const key of Object.keys(interfaces)) { + const items = interfaces[key]; - for (let details of items) { - let type = details.family.toLowerCase(); + for (const details of items) { + const type = details.family.toLowerCase(); let raw; if (family && type !== family) diff --git a/lib/utils/list.js b/lib/utils/list.js index b66abf38a..03815eef3 100644 --- a/lib/utils/list.js +++ b/lib/utils/list.js @@ -52,7 +52,7 @@ List.prototype.reset = function reset() { */ List.prototype.shift = function shift() { - let item = this.head; + const item = this.head; if (!item) return; @@ -88,7 +88,7 @@ List.prototype.push = function push(item) { */ List.prototype.pop = function pop() { - let item = this.tail; + const item = this.tail; if (!item) return; @@ -209,7 +209,7 @@ List.prototype.replace = function replace(ref, item) { */ List.prototype.slice = function slice(total) { - let items = []; + const items = []; let item, next; if (total == null) @@ -245,7 +245,7 @@ List.prototype.slice = function slice(total) { */ List.prototype.toArray = function toArray() { - let items = []; + const items = []; for (let item = this.head; item; item = item.next) items.push(item); diff --git a/lib/utils/lock.js b/lib/utils/lock.js index 56c1f49e2..977e1cfa3 100644 --- a/lib/utils/lock.js +++ b/lib/utils/lock.js @@ -40,7 +40,7 @@ function Lock(named) { */ Lock.create = function create(named) { - let lock = new Lock(named); + const lock = new Lock(named); return function _lock(arg1, arg2) { return lock.lock(arg1, arg2); }; @@ -189,7 +189,7 @@ Lock.prototype.destroy = function destroy() { this.map.clear(); this.current = null; - for (let job of jobs) + for (const job of jobs) job.reject(new Error('Lock was destroyed.')); }; diff --git a/lib/utils/lru.js b/lib/utils/lru.js index 49ef33e19..0342ec9fc 100644 --- a/lib/utils/lru.js +++ b/lib/utils/lru.js @@ -298,7 +298,7 @@ LRU.prototype._removeList = function removeList(item) { */ LRU.prototype.keys = function _keys() { - let keys = []; + const keys = []; for (let item = this.head; item; item = item.next) { if (item === this.head) @@ -319,7 +319,7 @@ LRU.prototype.keys = function _keys() { */ LRU.prototype.values = function _values() { - let values = []; + const values = []; for (let item = this.head; item; item = item.next) values.push(item.value); @@ -333,7 +333,7 @@ LRU.prototype.values = function _values() { */ LRU.prototype.toArray = function toArray() { - let items = []; + const items = []; for (let item = this.head; item; item = item.next) items.push(item); @@ -477,7 +477,7 @@ LRUBatch.prototype.clear = function clear() { */ LRUBatch.prototype.commit = function commit() { - for (let op of this.ops) { + for (const op of this.ops) { if (op.remove) { this.lru.remove(op.key); continue; diff --git a/lib/utils/mappedlock.js b/lib/utils/mappedlock.js index 05081d14c..723c6fa3c 100644 --- a/lib/utils/mappedlock.js +++ b/lib/utils/mappedlock.js @@ -31,7 +31,7 @@ function MappedLock() { */ MappedLock.create = function create() { - let lock = new MappedLock(); + const lock = new MappedLock(); return function _lock(key, force) { return lock.lock(key, force); }; @@ -103,9 +103,9 @@ MappedLock.prototype.lock = function lock(key, force) { */ MappedLock.prototype.unlock = function unlock(key) { - let self = this; + const self = this; return function unlocker() { - let jobs = self.jobs.get(key); + const jobs = self.jobs.get(key); let job; assert(self.destroyed || self.busy.has(key)); @@ -133,7 +133,7 @@ MappedLock.prototype.unlock = function unlock(key) { */ MappedLock.prototype.destroy = function destroy() { - let map = this.jobs; + const map = this.jobs; assert(!this.destroyed, 'Lock is already destroyed.'); @@ -142,8 +142,8 @@ MappedLock.prototype.destroy = function destroy() { this.jobs = new Map(); this.busy = new Map(); - for (let jobs of map.values()) { - for (let job of jobs) + for (const jobs of map.values()) { + for (const job of jobs) job.reject(new Error('Lock was destroyed.')); } }; diff --git a/lib/utils/murmur3.js b/lib/utils/murmur3.js index f9bed6b55..0bb4c56ca 100644 --- a/lib/utils/murmur3.js +++ b/lib/utils/murmur3.js @@ -18,9 +18,9 @@ const native = require('../native').binding; */ function murmur3(data, seed) { - let tail = data.length - (data.length % 4); - let c1 = 0xcc9e2d51; - let c2 = 0x1b873593; + const tail = data.length - (data.length % 4); + const c1 = 0xcc9e2d51; + const c2 = 0x1b873593; let h1 = seed; let k1; @@ -68,10 +68,10 @@ if (native) murmur3 = native.murmur3; function mul32(a, b) { - let alo = a & 0xffff; - let blo = b & 0xffff; - let ahi = a >>> 16; - let bhi = b >>> 16; + const alo = a & 0xffff; + const blo = b & 0xffff; + const ahi = a >>> 16; + const bhi = b >>> 16; let r, lo, hi; lo = alo * blo; diff --git a/lib/utils/pem.js b/lib/utils/pem.js index 0878e7e6c..12338f582 100644 --- a/lib/utils/pem.js +++ b/lib/utils/pem.js @@ -23,7 +23,7 @@ const PEM = exports; PEM.parse = function parse(pem) { let buf = ''; - let chunks = []; + const chunks = []; let s, tag, type; while (pem.length) { @@ -69,9 +69,9 @@ PEM.parse = function parse(pem) { */ PEM.decode = function decode(pem) { - let chunks = PEM.parse(pem); - let body = chunks[0]; - let extra = chunks[1]; + const chunks = PEM.parse(pem); + const body = chunks[0]; + const extra = chunks[1]; let params, alg; if (extra) { diff --git a/lib/utils/protoreader.js b/lib/utils/protoreader.js index a037c6e36..505575858 100644 --- a/lib/utils/protoreader.js +++ b/lib/utils/protoreader.js @@ -39,13 +39,13 @@ function ProtoReader(data, zeroCopy) { util.inherits(ProtoReader, BufferReader); ProtoReader.prototype.readVarint = function _readVarint() { - let {size, value} = readVarint(this.data, this.offset); + const {size, value} = readVarint(this.data, this.offset); this.offset += size; return value; }; ProtoReader.prototype.readFieldValue = function readFieldValue(tag, opt) { - let field = this.readField(tag, opt); + const field = this.readField(tag, opt); if (!field) return -1; assert(field.value != null); @@ -53,7 +53,7 @@ ProtoReader.prototype.readFieldValue = function readFieldValue(tag, opt) { }; ProtoReader.prototype.readFieldU64 = function readFieldU64(tag, opt) { - let field = this.readField(tag, opt); + const field = this.readField(tag, opt); if (!field) return -1; assert(field.type === wireType.VARINT || field.type === wireType.FIXED64); @@ -61,7 +61,7 @@ ProtoReader.prototype.readFieldU64 = function readFieldU64(tag, opt) { }; ProtoReader.prototype.readFieldU32 = function readFieldU32(tag, opt) { - let field = this.readField(tag, opt); + const field = this.readField(tag, opt); if (!field) return -1; assert(field.type === wireType.VARINT || field.type === wireType.FIXED32); @@ -69,7 +69,7 @@ ProtoReader.prototype.readFieldU32 = function readFieldU32(tag, opt) { }; ProtoReader.prototype.readFieldBytes = function readFieldBytes(tag, opt) { - let field = this.readField(tag, opt); + const field = this.readField(tag, opt); if (!field) return null; assert(field.data); @@ -77,7 +77,7 @@ ProtoReader.prototype.readFieldBytes = function readFieldBytes(tag, opt) { }; ProtoReader.prototype.readFieldString = function readFieldString(tag, opt, enc) { - let field = this.readField(tag, opt); + const field = this.readField(tag, opt); if (!field) return null; assert(field.data); @@ -98,9 +98,9 @@ ProtoReader.prototype.nextTag = function nextTag() { }; ProtoReader.prototype.readField = function readField(tag, opt) { - let offset = this.offset; - let header = this.readVarint(); - let field = new Field(header); + const offset = this.offset; + const header = this.readVarint(); + const field = new Field(header); let inner; if (tag != null && field.tag !== tag) { diff --git a/lib/utils/protowriter.js b/lib/utils/protowriter.js index 58de3ec84..974b983d2 100644 --- a/lib/utils/protowriter.js +++ b/lib/utils/protowriter.js @@ -43,7 +43,7 @@ function ProtoWriter() { util.inherits(ProtoWriter, BufferWriter); ProtoWriter.prototype.writeVarint = function _writeVarint(num) { - let size = sizeVarint(num); + const size = sizeVarint(num); let value; // Avoid an extra allocation until @@ -86,7 +86,7 @@ ProtoWriter.prototype.writeVarint = function _writeVarint(num) { }; ProtoWriter.prototype.writeFieldVarint = function writeFieldVarint(tag, value) { - let header = (tag << 3) | wireType.VARINT; + const header = (tag << 3) | wireType.VARINT; this.writeVarint(header); this.writeVarint(value); }; @@ -102,7 +102,7 @@ ProtoWriter.prototype.writeFieldU32 = function writeFieldU32(tag, value) { }; ProtoWriter.prototype.writeFieldBytes = function writeFieldBytes(tag, data) { - let header = (tag << 3) | wireType.DELIMITED; + const header = (tag << 3) | wireType.DELIMITED; this.writeVarint(header); this.writeVarint(data.length); this.writeBytes(data); diff --git a/lib/utils/rbt.js b/lib/utils/rbt.js index 9b8c7de66..11c9549fb 100644 --- a/lib/utils/rbt.js +++ b/lib/utils/rbt.js @@ -48,7 +48,7 @@ RBT.prototype.search = function search(key) { let current = this.root; while (!current.isNull()) { - let cmp = this.compare(key, current.key); + const cmp = this.compare(key, current.key); if (cmp === 0) return current; @@ -72,7 +72,7 @@ RBT.prototype.insert = function insert(key, value) { let parent, node; while (!current.isNull()) { - let cmp = this.compare(key, current.key); + const cmp = this.compare(key, current.key); if (this.unique && cmp === 0) { current.key = key; @@ -171,7 +171,7 @@ RBT.prototype.remove = function remove(key) { let current = this.root; while (!current.isNull()) { - let cmp = this.compare(key, current.key); + const cmp = this.compare(key, current.key); if (cmp === 0) { this.removeNode(current); @@ -294,7 +294,7 @@ RBT.prototype.removeFixup = function removeFixup(x) { */ RBT.prototype.rotl = function rotl(x) { - let y = x.right; + const y = x.right; x.right = y.left; if (!y.left.isNull()) @@ -322,7 +322,7 @@ RBT.prototype.rotl = function rotl(x) { */ RBT.prototype.rotr = function rotr(x) { - let y = x.left; + const y = x.left; x.left = y.right; if (!y.right.isNull()) @@ -427,7 +427,7 @@ RBT.prototype.predecessor = function predecessor(x) { RBT.prototype.clone = function clone() { let current = this.root; - let stack = []; + const stack = []; let left = true; let parent, copy, snapshot; @@ -507,8 +507,8 @@ RBT.prototype.iterator = function iterator(snapshot) { */ RBT.prototype.range = function range(min, max) { - let iter = this.iterator(); - let items = []; + const iter = this.iterator(); + const items = []; if (min) iter.seekMin(min); @@ -614,7 +614,7 @@ Iterator.prototype.seekMin = function seekMin(key) { assert(key != null, 'No key passed to seek.'); while (!root.isNull()) { - let cmp = this.tree.compare(root.key, key); + const cmp = this.tree.compare(root.key, key); if (cmp === 0) { current = root; @@ -646,7 +646,7 @@ Iterator.prototype.seekMax = function seekMax(key) { assert(key != null, 'No key passed to seek.'); while (!root.isNull()) { - let cmp = this.tree.compare(root.key, key); + const cmp = this.tree.compare(root.key, key); if (cmp === 0) { current = root; @@ -744,7 +744,7 @@ function RBTNode(key, value) { */ RBTNode.prototype.clone = function clone() { - let node = new RBTNode(this.key, this.value); + const node = new RBTNode(this.key, this.value); node.color = this.color; node.parent = this.parent; node.left = this.left; diff --git a/lib/utils/reader.js b/lib/utils/reader.js index 513ff13b7..2c181fd2e 100644 --- a/lib/utils/reader.js +++ b/lib/utils/reader.js @@ -506,7 +506,7 @@ BufferReader.prototype.readDoubleBE = function readDoubleBE() { */ BufferReader.prototype.readVarint = function readVarint() { - let {size, value} = encoding.readVarint(this.data, this.offset); + const {size, value} = encoding.readVarint(this.data, this.offset); this.offset += size; return value; }; @@ -517,7 +517,7 @@ BufferReader.prototype.readVarint = function readVarint() { */ BufferReader.prototype.skipVarint = function skipVarint() { - let size = encoding.skipVarint(this.data, this.offset); + const size = encoding.skipVarint(this.data, this.offset); this.assert(this.offset + size <= this.data.length); this.offset += size; }; @@ -528,7 +528,7 @@ BufferReader.prototype.skipVarint = function skipVarint() { */ BufferReader.prototype.readVarintBN = function readVarintBN() { - let {size, value} = encoding.readVarintBN(this.data, this.offset); + const {size, value} = encoding.readVarintBN(this.data, this.offset); this.offset += size; return value; }; @@ -539,7 +539,7 @@ BufferReader.prototype.readVarintBN = function readVarintBN() { */ BufferReader.prototype.readVarint2 = function readVarint2() { - let {size, value} = encoding.readVarint2(this.data, this.offset); + const {size, value} = encoding.readVarint2(this.data, this.offset); this.offset += size; return value; }; @@ -550,7 +550,7 @@ BufferReader.prototype.readVarint2 = function readVarint2() { */ BufferReader.prototype.skipVarint2 = function skipVarint2() { - let size = encoding.skipVarint2(this.data, this.offset); + const size = encoding.skipVarint2(this.data, this.offset); this.assert(this.offset + size <= this.data.length); this.offset += size; }; @@ -561,7 +561,7 @@ BufferReader.prototype.skipVarint2 = function skipVarint2() { */ BufferReader.prototype.readVarint2BN = function readVarint2BN() { - let {size, value} = encoding.readVarint2BN(this.data, this.offset); + const {size, value} = encoding.readVarint2BN(this.data, this.offset); this.offset += size; return value; }; @@ -641,7 +641,7 @@ BufferReader.prototype.readHash = function readHash(enc) { */ BufferReader.prototype.readVarString = function readVarString(enc, limit) { - let size = this.readVarint(); + const size = this.readVarint(); this.enforce(!limit || size <= limit, 'String exceeds limit.'); return this.readString(enc, size); }; @@ -689,8 +689,8 @@ BufferReader.prototype.createChecksum = function createChecksum() { */ BufferReader.prototype.verifyChecksum = function verifyChecksum() { - let chk = this.createChecksum(); - let checksum = this.readU32(); + const chk = this.createChecksum(); + const checksum = this.readU32(); this.enforce(chk === checksum, 'Checksum mismatch.'); return checksum; }; diff --git a/lib/utils/rollingfilter.js b/lib/utils/rollingfilter.js index 77a03376c..c4ab55982 100644 --- a/lib/utils/rollingfilter.js +++ b/lib/utils/rollingfilter.js @@ -142,12 +142,12 @@ RollingFilter.prototype.add = function add(val, enc) { m2 = (this.generation >>> 1) * 0xffffffff; for (let i = 0; i < this.items; i += 2) { - let pos1 = i * 8; - let pos2 = (i + 1) * 8; - let v1 = read(this.filter, pos1); - let v2 = read(this.filter, pos2); - let mhi = (v1.hi ^ m1) | (v2.hi ^ m2); - let mlo = (v1.lo ^ m1) | (v2.lo ^ m2); + const pos1 = i * 8; + const pos2 = (i + 1) * 8; + const v1 = read(this.filter, pos1); + const v2 = read(this.filter, pos2); + const mhi = (v1.hi ^ m1) | (v2.hi ^ m2); + const mlo = (v1.lo ^ m1) | (v2.lo ^ m2); v1.hi &= mhi; v1.lo &= mlo; @@ -162,13 +162,13 @@ RollingFilter.prototype.add = function add(val, enc) { this.entries += 1; for (let i = 0; i < this.n; i++) { - let hash = this.hash(val, i); - let bits = hash & 0x3f; - let pos = (hash >>> 6) % this.items; + const hash = this.hash(val, i); + const bits = hash & 0x3f; + const pos = (hash >>> 6) % this.items; let pos1 = (pos & ~1) * 8; let pos2 = (pos | 1) * 8; - let bit = bits % 8; - let oct = (bits - bit) / 8; + const bit = bits % 8; + const oct = (bits - bit) / 8; pos1 += oct; pos2 += oct; @@ -196,13 +196,13 @@ RollingFilter.prototype.test = function test(val, enc) { val = Buffer.from(val, enc); for (let i = 0; i < this.n; i++) { - let hash = this.hash(val, i); + const hash = this.hash(val, i); let bits = hash & 0x3f; - let pos = (hash >>> 6) % this.items; + const pos = (hash >>> 6) % this.items; let pos1 = (pos & ~1) * 8; let pos2 = (pos | 1) * 8; - let bit = bits % 8; - let oct = (bits - bit) / 8; + const bit = bits % 8; + const oct = (bits - bit) / 8; pos1 += oct; pos2 += oct; @@ -247,8 +247,8 @@ function U64(hi, lo) { } function read(data, off) { - let hi = data.readUInt32LE(off + 4, true); - let lo = data.readUInt32LE(off, true); + const hi = data.readUInt32LE(off + 4, true); + const lo = data.readUInt32LE(off, true); return new U64(hi, lo); } diff --git a/lib/utils/staticwriter.js b/lib/utils/staticwriter.js index 83b414d73..3d9dfe898 100644 --- a/lib/utils/staticwriter.js +++ b/lib/utils/staticwriter.js @@ -32,7 +32,7 @@ function StaticWriter(size) { */ StaticWriter.prototype.render = function render(keep) { - let data = this.data; + const data = this.data; assert(this.written === data.length); @@ -335,7 +335,7 @@ StaticWriter.prototype.writeVarBytes = function writeVarBytes(value) { */ StaticWriter.prototype.copy = function copy(value, start, end) { - let len = end - start; + const len = end - start; if (len === 0) return; @@ -416,8 +416,8 @@ StaticWriter.prototype.writeNullString = function writeNullString(value, enc) { */ StaticWriter.prototype.writeChecksum = function writeChecksum() { - let data = this.data.slice(0, this.written); - let hash = digest.hash256(data); + const data = this.data.slice(0, this.written); + const hash = digest.hash256(data); hash.copy(this.data, this.written, 0, 4); this.written += 4; }; diff --git a/lib/utils/util.js b/lib/utils/util.js index 8bb2f8a2d..cd7451308 100644 --- a/lib/utils/util.js +++ b/lib/utils/util.js @@ -53,7 +53,7 @@ util.hrtime = function hrtime(time) { } if (time) { - let elapsed = process.hrtime(time); + const elapsed = process.hrtime(time); return elapsed[0] * 1000 + elapsed[1] / 1e6; } @@ -468,7 +468,7 @@ util.nonce = function _nonce(size) { */ util.strcmp = function strcmp(a, b) { - let len = Math.min(a.length, b.length); + const len = Math.min(a.length, b.length); for (let i = 0; i < len; i++) { if (a[i] < b[i]) @@ -523,7 +523,7 @@ util.indexOf = function indexOf(items, data) { assert(Buffer.isBuffer(data)); for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; assert(Buffer.isBuffer(item)); if (item.equals(data)) return i; @@ -652,9 +652,9 @@ util.hex32 = function hex32(num) { */ util.reverse = function reverse(obj) { - let reversed = {}; + const reversed = {}; - for (let key of Object.keys(obj)) + for (const key of Object.keys(obj)) reversed[obj[key]] = key; return reversed; @@ -674,8 +674,8 @@ util.binarySearch = function binarySearch(items, key, compare, insert) { let end = items.length - 1; while (start <= end) { - let pos = (start + end) >>> 1; - let cmp = compare(items[pos], key); + const pos = (start + end) >>> 1; + const cmp = compare(items[pos], key); if (cmp === 0) return pos; @@ -701,7 +701,7 @@ util.binarySearch = function binarySearch(items, key, compare, insert) { */ util.binaryInsert = function binaryInsert(items, item, compare, uniq) { - let i = util.binarySearch(items, item, compare, true); + const i = util.binarySearch(items, item, compare, true); if (uniq && i < items.length) { if (compare(items[i], item) === 0) @@ -727,7 +727,7 @@ util.binaryInsert = function binaryInsert(items, item, compare, uniq) { */ util.binaryRemove = function binaryRemove(items, item, compare) { - let i = util.binarySearch(items, item, compare, false); + const i = util.binarySearch(items, item, compare, false); if (i === -1) return false; diff --git a/lib/utils/validator.js b/lib/utils/validator.js index 922284362..28ed2f276 100644 --- a/lib/utils/validator.js +++ b/lib/utils/validator.js @@ -50,8 +50,8 @@ Validator.prototype.has = function has(key) { assert(typeof key === 'string' || typeof key === 'number', 'Key must be a string.'); - for (let map of this.data) { - let value = map[key]; + for (const map of this.data) { + const value = map[key]; if (value != null) return true; } @@ -71,9 +71,9 @@ Validator.prototype.get = function get(key, fallback) { fallback = null; if (Array.isArray(key)) { - let keys = key; - for (let key of keys) { - let value = this.get(key); + const keys = key; + for (const key of keys) { + const value = this.get(key); if (value !== null) return value; } @@ -83,7 +83,7 @@ Validator.prototype.get = function get(key, fallback) { assert(typeof key === 'string' || typeof key === 'number', 'Key must be a string.'); - for (let map of this.data) { + for (const map of this.data) { let value; if (!map || typeof map !== 'object') @@ -106,7 +106,7 @@ Validator.prototype.get = function get(key, fallback) { */ Validator.prototype.str = function str(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -194,7 +194,7 @@ Validator.prototype.flt = function flt(key, fallback) { */ Validator.prototype.u32 = function u32(key, fallback) { - let value = this.num(key); + const value = this.num(key); if (fallback === undefined) fallback = null; @@ -216,7 +216,7 @@ Validator.prototype.u32 = function u32(key, fallback) { */ Validator.prototype.u64 = function u64(key, fallback) { - let value = this.num(key); + const value = this.num(key); if (fallback === undefined) fallback = null; @@ -238,7 +238,7 @@ Validator.prototype.u64 = function u64(key, fallback) { */ Validator.prototype.i32 = function i32(key, fallback) { - let value = this.num(key); + const value = this.num(key); if (fallback === undefined) fallback = null; @@ -260,7 +260,7 @@ Validator.prototype.i32 = function i32(key, fallback) { */ Validator.prototype.i64 = function i64(key, fallback) { - let value = this.num(key); + const value = this.num(key); if (fallback === undefined) fallback = null; @@ -344,7 +344,7 @@ Validator.prototype.btc = function btc(key, fallback) { */ Validator.prototype.hash = function hash(key, fallback) { - let value = this.get(key); + const value = this.get(key); let out = ''; if (fallback === undefined) @@ -383,7 +383,7 @@ Validator.prototype.hash = function hash(key, fallback) { */ Validator.prototype.numhash = function numhash(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (value === null) return fallback; @@ -402,7 +402,7 @@ Validator.prototype.numhash = function numhash(key, fallback) { */ Validator.prototype.numstr = function numstr(key, fallback) { - let value = this.get(key); + const value = this.get(key); let num; if (fallback === undefined) @@ -433,7 +433,7 @@ Validator.prototype.numstr = function numstr(key, fallback) { */ Validator.prototype.bool = function bool(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -473,7 +473,7 @@ Validator.prototype.bool = function bool(key, fallback) { */ Validator.prototype.buf = function buf(key, fallback, enc) { - let value = this.get(key); + const value = this.get(key); let data; if (!enc) @@ -507,7 +507,7 @@ Validator.prototype.buf = function buf(key, fallback, enc) { */ Validator.prototype.array = function array(key, fallback) { - let value = this.get(key); + const value = this.get(key); let result, parts; if (fallback === undefined) @@ -525,7 +525,7 @@ Validator.prototype.array = function array(key, fallback) { parts = value.trim().split(/\s*,\s*/); result = []; - for (let part of parts) { + for (const part of parts) { if (part.length === 0) continue; @@ -543,7 +543,7 @@ Validator.prototype.array = function array(key, fallback) { */ Validator.prototype.obj = function obj(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; @@ -565,7 +565,7 @@ Validator.prototype.obj = function obj(key, fallback) { */ Validator.prototype.func = function func(key, fallback) { - let value = this.get(key); + const value = this.get(key); if (fallback === undefined) fallback = null; diff --git a/lib/utils/writer.js b/lib/utils/writer.js index 6bb7cf1a8..3f9d7f704 100644 --- a/lib/utils/writer.js +++ b/lib/utils/writer.js @@ -70,10 +70,10 @@ function BufferWriter() { */ BufferWriter.prototype.render = function render(keep) { - let data = Buffer.allocUnsafe(this.written); + const data = Buffer.allocUnsafe(this.written); let off = 0; - for (let op of this.ops) { + for (const 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 66ca8e78e..1c2cb2f37 100644 --- a/lib/wallet/account.js +++ b/lib/wallet/account.js @@ -194,7 +194,7 @@ Account.prototype.fromOptions = function fromOptions(options) { if (options.keys) { assert(Array.isArray(options.keys)); - for (let key of options.keys) + for (const key of options.keys) this.pushKey(key); } @@ -345,8 +345,8 @@ Account.prototype.spliceKey = function spliceKey(key) { */ Account.prototype.addSharedKey = async function addSharedKey(key) { - let result = this.pushKey(key); - let exists = await this._hasDuplicate(); + const result = this.pushKey(key); + const exists = await this._hasDuplicate(); if (exists) { this.spliceKey(key); @@ -385,7 +385,7 @@ Account.prototype._hasDuplicate = function _hasDuplicate() { */ Account.prototype.removeSharedKey = function removeSharedKey(key) { - let result = this.spliceKey(key); + const result = this.spliceKey(key); if (!result) return false; @@ -536,7 +536,7 @@ Account.prototype.derivePath = function derivePath(path, master) { */ Account.prototype.deriveKey = function deriveKey(branch, index, master) { - let keys = []; + const keys = []; let key, ring; assert(typeof branch === 'number'); @@ -613,7 +613,7 @@ Account.prototype.initDepth = async function initDepth() { // Lookahead for (let i = 0; i < this.lookahead; i++) { - let key = this.deriveReceive(i + 1); + const key = this.deriveReceive(i + 1); await this.saveKey(key); } @@ -625,7 +625,7 @@ Account.prototype.initDepth = async function initDepth() { // Lookahead for (let i = 0; i < this.lookahead; i++) { - let key = this.deriveChange(i + 1); + const key = this.deriveChange(i + 1); await this.saveKey(key); } @@ -638,7 +638,7 @@ Account.prototype.initDepth = async function initDepth() { // Lookahead for (let i = 0; i < this.lookahead; i++) { - let key = this.deriveNested(i + 1); + const key = this.deriveNested(i + 1); await this.saveKey(key); } } @@ -659,12 +659,12 @@ Account.prototype.syncDepth = async function syncDepth(receive, change, nested) let result = null; if (receive > this.receiveDepth) { - let depth = this.receiveDepth + this.lookahead; + const depth = this.receiveDepth + this.lookahead; assert(receive <= depth + 1); for (let i = depth; i < receive + this.lookahead; i++) { - let key = this.deriveReceive(i); + const key = this.deriveReceive(i); await this.saveKey(key); } @@ -676,12 +676,12 @@ Account.prototype.syncDepth = async function syncDepth(receive, change, nested) } if (change > this.changeDepth) { - let depth = this.changeDepth + this.lookahead; + const depth = this.changeDepth + this.lookahead; assert(change <= depth + 1); for (let i = depth; i < change + this.lookahead; i++) { - let key = this.deriveChange(i); + const key = this.deriveChange(i); await this.saveKey(key); } @@ -692,12 +692,12 @@ Account.prototype.syncDepth = async function syncDepth(receive, change, nested) } if (this.witness && nested > this.nestedDepth) { - let depth = this.nestedDepth + this.lookahead; + const depth = this.nestedDepth + this.lookahead; assert(nested <= depth + 1); for (let i = depth; i < nested + this.lookahead; i++) { - let key = this.deriveNested(i); + const key = this.deriveNested(i); await this.saveKey(key); } @@ -731,7 +731,7 @@ Account.prototype.setLookahead = async function setLookahead(lookahead) { } if (lookahead < this.lookahead) { - let diff = this.lookahead - lookahead; + const diff = this.lookahead - lookahead; this.receiveDepth += diff; this.receive = this.deriveReceive(this.receiveDepth - 1); @@ -755,7 +755,7 @@ Account.prototype.setLookahead = async function setLookahead(lookahead) { target = this.receiveDepth + lookahead; for (let i = depth; i < target; i++) { - let key = this.deriveReceive(i); + const key = this.deriveReceive(i); await this.saveKey(key); } @@ -763,16 +763,16 @@ Account.prototype.setLookahead = async function setLookahead(lookahead) { target = this.changeDepth + lookahead; for (let i = depth; i < target; i++) { - let key = this.deriveChange(i); + const key = this.deriveChange(i); await this.saveKey(key); } if (this.witness) { - let depth = this.nestedDepth + this.lookahead; - let target = this.nestedDepth + lookahead; + const depth = this.nestedDepth + this.lookahead; + const target = this.nestedDepth + lookahead; for (let i = depth; i < target; i++) { - let key = this.deriveNested(i); + const key = this.deriveNested(i); await this.saveKey(key); } } @@ -918,8 +918,8 @@ Account.prototype.getSize = function getSize() { */ Account.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeVarString(this.name, 'ascii'); bw.writeU8(this.initialized ? 1 : 0); @@ -935,7 +935,7 @@ Account.prototype.toRaw = function toRaw() { bw.writeBytes(this.accountKey.toRaw()); bw.writeU8(this.keys.length); - for (let key of this.keys) + for (const key of this.keys) bw.writeBytes(key.toRaw()); return bw.render(); @@ -949,7 +949,7 @@ Account.prototype.toRaw = function toRaw() { */ Account.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); let count; this.name = br.readVarString('ascii'); @@ -970,7 +970,7 @@ Account.prototype.fromRaw = function fromRaw(data) { count = br.readU8(); for (let i = 0; i < count; i++) { - let key = HD.PublicKey.fromRaw(br.readBytes(82)); + const key = HD.PublicKey.fromRaw(br.readBytes(82)); this.pushKey(key); } diff --git a/lib/wallet/client.js b/lib/wallet/client.js index 6b26eb4af..6921d39ce 100644 --- a/lib/wallet/client.js +++ b/lib/wallet/client.js @@ -325,8 +325,8 @@ function parseEntry(data, enc) { } function parseBlock(entry, txs) { - let block = parseEntry(entry); - let out = []; + const block = parseEntry(entry); + const out = []; for (let tx of txs) { tx = parseTX(tx); diff --git a/lib/wallet/common.js b/lib/wallet/common.js index 2ff7acff8..4cfd5845f 100644 --- a/lib/wallet/common.js +++ b/lib/wallet/common.js @@ -81,24 +81,24 @@ common.sortCoins = function sortCoins(coins) { */ common.sortDeps = function sortDeps(txs) { - let map = new Map(); - let depMap = new Map(); - let depCount = new Map(); - let result = []; - let top = []; - - for (let tx of txs) { - let hash = tx.hash('hex'); + const map = new Map(); + const depMap = new Map(); + const depCount = new Map(); + const result = []; + const top = []; + + for (const tx of txs) { + const hash = tx.hash('hex'); map.set(hash, tx); } - for (let [hash, tx] of map) { + for (const [hash, tx] of map) { let hasDeps = false; depCount.set(hash, 0); - for (let input of tx.inputs) { - let prev = input.prevout.hash; + for (const input of tx.inputs) { + const prev = input.prevout.hash; let count; if (!map.has(prev)) @@ -120,17 +120,17 @@ common.sortDeps = function sortDeps(txs) { top.push(tx); } - for (let tx of top) { - let hash = tx.hash('hex'); - let deps = depMap.get(hash); + for (const tx of top) { + const hash = tx.hash('hex'); + const deps = depMap.get(hash); result.push(tx); if (!deps) continue; - for (let tx of deps) { - let hash = tx.hash('hex'); + for (const tx of deps) { + const hash = tx.hash('hex'); let count = depCount.get(hash); if (--count === 0) diff --git a/lib/wallet/http.js b/lib/wallet/http.js index 466ce15eb..79c47cfda 100644 --- a/lib/wallet/http.js +++ b/lib/wallet/http.js @@ -107,7 +107,7 @@ HTTPServer.prototype.initRouter = function initRouter() { this.use(this.jsonRPC(this.rpc)); this.hook(async (req, res) => { - let valid = req.valid(); + const valid = req.valid(); let id, token, wallet; if (req.path.length === 0) @@ -155,8 +155,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Rescan this.post('/_admin/rescan', async (req, res) => { - let valid = req.valid(); - let height = valid.u32('height'); + const valid = req.valid(); + const height = valid.u32('height'); res.send(200, { success: true }); @@ -171,8 +171,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Backup WalletDB this.post('/_admin/backup', async (req, res) => { - let valid = req.valid(); - let path = valid.str('path'); + const valid = req.valid(); + const path = valid.str('path'); enforce(path, 'Path is required.'); @@ -183,7 +183,7 @@ HTTPServer.prototype.initRouter = function initRouter() { // List wallets this.get('/_admin/wallets', async (req, res) => { - let wallets = await this.walletdb.getWallets(); + const wallets = await this.walletdb.getWallets(); res.send(200, wallets); }); @@ -199,7 +199,7 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create wallet (compat) this.post('/', async (req, res) => { - let valid = req.valid(); + const valid = req.valid(); let wallet; wallet = await this.walletdb.create({ @@ -220,7 +220,7 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create wallet this.put('/:id', async (req, res) => { - let valid = req.valid(); + const valid = req.valid(); let wallet; wallet = await this.walletdb.create({ @@ -241,15 +241,15 @@ HTTPServer.prototype.initRouter = function initRouter() { // List accounts this.get('/:id/account', async (req, res) => { - let accounts = await req.wallet.getAccounts(); + const accounts = await req.wallet.getAccounts(); res.send(200, accounts); }); // Get account this.get('/:id/account/:account', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let account = await req.wallet.getAccount(acct); + const valid = req.valid(); + const acct = valid.str('account'); + const account = await req.wallet.getAccount(acct); if (!account) { res.send(404); @@ -261,8 +261,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create account (compat) this.post('/:id/account', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); let options, account; options = { @@ -288,8 +288,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create account this.put('/:id/account/:account', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); let options, account; options = { @@ -315,9 +315,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Change passphrase this.post('/:id/passphrase', async (req, res) => { - let valid = req.valid(); - let old = valid.str('old'); - let new_ = valid.str('new'); + const valid = req.valid(); + const old = valid.str('old'); + const new_ = valid.str('new'); enforce(old || new_, 'Passphrase is required.'); await req.wallet.setPassphrase(old, new_); res.send(200, { success: true }); @@ -325,9 +325,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Unlock wallet this.post('/:id/unlock', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); - let timeout = valid.u32('timeout'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); + const timeout = valid.u32('timeout'); enforce(passphrase, 'Passphrase is required.'); await req.wallet.unlock(passphrase, timeout); res.send(200, { success: true }); @@ -341,11 +341,11 @@ HTTPServer.prototype.initRouter = function initRouter() { // Import key this.post('/:id/import', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let pub = valid.str('publicKey'); - let priv = valid.str('privateKey'); - let address = valid.str('address'); + const valid = req.valid(); + const acct = valid.str('account'); + const pub = valid.str('publicKey'); + const priv = valid.str('privateKey'); + const address = valid.str('address'); if (pub) { await req.wallet.importKey(acct, pub); @@ -370,17 +370,17 @@ HTTPServer.prototype.initRouter = function initRouter() { // Generate new token this.post('/:id/retoken', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); - let token = await req.wallet.retoken(passphrase); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); + const token = await req.wallet.retoken(passphrase); res.send(200, { token: token.toString('hex') }); }); // Send TX this.post('/:id/send', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); - let outputs = valid.array('outputs'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); + const outputs = valid.array('outputs'); let options, tx, details; options = { @@ -394,8 +394,8 @@ HTTPServer.prototype.initRouter = function initRouter() { outputs: [] }; - for (let output of outputs) { - let valid = new Validator([output]); + for (const output of outputs) { + const valid = new Validator([output]); let script = null; if (valid.has('script')) { @@ -419,9 +419,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create TX this.post('/:id/create', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); - let outputs = valid.array('outputs'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); + const outputs = valid.array('outputs'); let options, tx; options = { @@ -434,8 +434,8 @@ HTTPServer.prototype.initRouter = function initRouter() { outputs: [] }; - for (let output of outputs) { - let valid = new Validator([output]); + for (const output of outputs) { + const valid = new Validator([output]); let script = null; if (valid.has('script')) { @@ -457,9 +457,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Sign TX this.post('/:id/sign', async (req, res) => { - let valid = req.valid(); - let passphrase = valid.str('passphrase'); - let raw = valid.buf('tx'); + const valid = req.valid(); + const passphrase = valid.str('passphrase'); + const raw = valid.buf('tx'); let tx; enforce(raw, 'TX is required.'); @@ -473,9 +473,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Zap Wallet TXs this.post('/:id/zap', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let age = valid.u32('age'); + const valid = req.valid(); + const acct = valid.str('account'); + const age = valid.u32('age'); enforce(age, 'Age is required.'); await req.wallet.zap(acct, age); res.send(200, { success: true }); @@ -483,8 +483,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Abandon Wallet TX this.del('/:id/tx/:hash', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); + const valid = req.valid(); + const hash = valid.hash('hash'); enforce(hash, 'Hash is required.'); await req.wallet.abandon(hash); res.send(200, { success: true }); @@ -492,14 +492,14 @@ HTTPServer.prototype.initRouter = function initRouter() { // List blocks this.get('/:id/block', async (req, res) => { - let heights = await req.wallet.getBlocks(); + const heights = await req.wallet.getBlocks(); res.send(200, heights); }); // Get Block Record this.get('/:id/block/:height', async (req, res) => { - let valid = req.valid(); - let height = valid.u32('height'); + const valid = req.valid(); + const height = valid.u32('height'); let block; enforce(height != null, 'Height is required.'); @@ -516,9 +516,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Add key this.put('/:id/shared-key', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let key = valid.str('accountKey'); + const valid = req.valid(); + const acct = valid.str('account'); + const key = valid.str('accountKey'); enforce(key, 'Key is required.'); await req.wallet.addSharedKey(acct, key); res.send(200, { success: true }); @@ -526,9 +526,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Remove key this.del('/:id/shared-key', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let key = valid.str('accountKey'); + const valid = req.valid(); + const acct = valid.str('account'); + const key = valid.str('accountKey'); enforce(key, 'Key is required.'); await req.wallet.removeSharedKey(acct, key); res.send(200, { success: true }); @@ -536,8 +536,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Get key by address this.get('/:id/key/:address', async (req, res) => { - let valid = req.valid(); - let address = valid.str('address'); + const valid = req.valid(); + const address = valid.str('address'); let key; enforce(address, 'Address is required.'); @@ -554,9 +554,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Get private key this.get('/:id/wif/:address', async (req, res) => { - let valid = req.valid(); - let address = valid.str('address'); - let passphrase = valid.str('passphrase'); + const valid = req.valid(); + const address = valid.str('address'); + const passphrase = valid.str('passphrase'); let key; enforce(address, 'Address is required.'); @@ -573,33 +573,33 @@ HTTPServer.prototype.initRouter = function initRouter() { // Create address this.post('/:id/address', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let address = await req.wallet.createReceive(acct); + const valid = req.valid(); + const acct = valid.str('account'); + const address = await req.wallet.createReceive(acct); res.send(200, address.toJSON()); }); // Create change address this.post('/:id/change', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let address = await req.wallet.createChange(acct); + const valid = req.valid(); + const acct = valid.str('account'); + const address = await req.wallet.createChange(acct); res.send(200, address.toJSON()); }); // Create nested address this.post('/:id/nested', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let address = await req.wallet.createNested(acct); + const valid = req.valid(); + const acct = valid.str('account'); + const address = await req.wallet.createNested(acct); res.send(200, address.toJSON()); }); // Wallet Balance this.get('/:id/balance', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let balance = await req.wallet.getBalance(acct); + const valid = req.valid(); + const acct = valid.str('account'); + const balance = await req.wallet.getBalance(acct); if (!balance) { res.send(404); @@ -611,14 +611,14 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet UTXOs this.get('/:id/coin', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let coins = await req.wallet.getCoins(acct); - let result = []; + const valid = req.valid(); + const acct = valid.str('account'); + const coins = await req.wallet.getCoins(acct); + const result = []; common.sortCoins(coins); - for (let coin of coins) + for (const coin of coins) result.push(coin.getJSON(this.network)); res.send(200, result); @@ -626,10 +626,10 @@ HTTPServer.prototype.initRouter = function initRouter() { // Locked coins this.get('/:id/locked', async (req, res) => { - let locked = this.wallet.getLocked(); - let result = []; + const locked = this.wallet.getLocked(); + const result = []; - for (let outpoint of locked) + for (const outpoint of locked) result.push(outpoint.toJSON()); res.send(200, result); @@ -637,9 +637,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Lock coin this.put('/:id/locked/:hash/:index', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); - let index = valid.u32('index'); + const valid = req.valid(); + const hash = valid.hash('hash'); + const index = valid.u32('index'); let outpoint; enforce(hash, 'Hash is required.'); @@ -652,9 +652,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Unlock coin this.del('/:id/locked/:hash/:index', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); - let index = valid.u32('index'); + const valid = req.valid(); + const hash = valid.hash('hash'); + const index = valid.u32('index'); let outpoint; enforce(hash, 'Hash is required.'); @@ -667,9 +667,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet Coin this.get('/:id/coin/:hash/:index', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); - let index = valid.u32('index'); + const valid = req.valid(); + const hash = valid.hash('hash'); + const index = valid.u32('index'); let coin; enforce(hash, 'Hash is required.'); @@ -687,17 +687,17 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet TXs this.get('/:id/tx/history', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let txs = await req.wallet.getHistory(acct); - let result = []; + const valid = req.valid(); + const acct = valid.str('account'); + const txs = await req.wallet.getHistory(acct); + const result = []; let details; common.sortTX(txs); details = await req.wallet.toDetails(txs); - for (let item of details) + for (const item of details) result.push(item.toJSON()); res.send(200, result); @@ -705,17 +705,17 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet Pending TXs this.get('/:id/tx/unconfirmed', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let txs = await req.wallet.getPending(acct); - let result = []; + const valid = req.valid(); + const acct = valid.str('account'); + const txs = await req.wallet.getPending(acct); + const result = []; let details; common.sortTX(txs); details = await req.wallet.toDetails(txs); - for (let item of details) + for (const item of details) result.push(item.toJSON()); res.send(200, result); @@ -723,9 +723,9 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet TXs within time range this.get('/:id/tx/range', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let result = []; + const valid = req.valid(); + const acct = valid.str('account'); + const result = []; let options, txs, details; options = { @@ -739,7 +739,7 @@ HTTPServer.prototype.initRouter = function initRouter() { details = await req.wallet.toDetails(txs); - for (let item of details) + for (const item of details) result.push(item.toJSON()); res.send(200, result); @@ -747,14 +747,14 @@ HTTPServer.prototype.initRouter = function initRouter() { // Last Wallet TXs this.get('/:id/tx/last', async (req, res) => { - let valid = req.valid(); - let acct = valid.str('account'); - let limit = valid.u32('limit'); - let txs = await req.wallet.getLast(acct, limit); - let details = await req.wallet.toDetails(txs); - let result = []; - - for (let item of details) + const valid = req.valid(); + const acct = valid.str('account'); + const limit = valid.u32('limit'); + const txs = await req.wallet.getLast(acct, limit); + const details = await req.wallet.toDetails(txs); + const result = []; + + for (const item of details) result.push(item.toJSON()); res.send(200, result); @@ -762,8 +762,8 @@ HTTPServer.prototype.initRouter = function initRouter() { // Wallet TX this.get('/:id/tx/:hash', async (req, res) => { - let valid = req.valid(); - let hash = valid.hash('hash'); + const valid = req.valid(); + const hash = valid.hash('hash'); let tx, details; enforce(hash, 'Hash is required.'); @@ -801,45 +801,45 @@ HTTPServer.prototype.initSockets = function initSockets() { }); this.walletdb.on('tx', (id, tx, details) => { - let json = details.toJSON(); - let channel = 'w:' + id; + const json = details.toJSON(); + const channel = 'w:' + id; this.to(channel, 'wallet tx', json); this.to('!all', 'wallet tx', id, json); }); this.walletdb.on('confirmed', (id, tx, details) => { - let json = details.toJSON(); - let channel = 'w:' + id; + const json = details.toJSON(); + const channel = 'w:' + id; this.to(channel, 'wallet confirmed', json); this.to('!all', 'wallet confirmed', id, json); }); this.walletdb.on('unconfirmed', (id, tx, details) => { - let json = details.toJSON(); - let channel = 'w:' + id; + const json = details.toJSON(); + const channel = 'w:' + id; this.to(channel, 'wallet unconfirmed', json); this.to('!all', 'wallet unconfirmed', id, json); }); this.walletdb.on('conflict', (id, tx, details) => { - let json = details.toJSON(); - let channel = 'w:' + id; + const json = details.toJSON(); + const channel = 'w:' + id; this.to(channel, 'wallet conflict', json); this.to('!all', 'wallet conflict', id, json); }); this.walletdb.on('balance', (id, balance) => { - let json = balance.toJSON(); - let channel = 'w:' + id; + const json = balance.toJSON(); + const channel = 'w:' + id; this.to(channel, 'wallet balance', json); this.to('!all', 'wallet balance', id, json); }); this.walletdb.on('address', (id, receive) => { - let channel = 'w:' + id; - let json = []; + const channel = 'w:' + id; + const json = []; - for (let addr of receive) + for (const addr of receive) json.push(addr.toJSON()); this.to(channel, 'wallet address', json); @@ -855,8 +855,8 @@ HTTPServer.prototype.initSockets = function initSockets() { HTTPServer.prototype.handleSocket = function handleSocket(socket) { socket.hook('wallet auth', (args) => { - let valid = new Validator([args]); - let key = valid.str(0); + const valid = new Validator([args]); + const key = valid.str(0); let hash; if (socket.auth) @@ -886,10 +886,10 @@ HTTPServer.prototype.handleSocket = function handleSocket(socket) { HTTPServer.prototype.handleAuth = function handleAuth(socket) { socket.hook('wallet join', async (args) => { - let valid = new Validator([args]); - let id = valid.str(0, ''); - let token = valid.buf(1); - let channel = 'w:' + id; + const valid = new Validator([args]); + const id = valid.str(0, ''); + const token = valid.buf(1); + const channel = 'w:' + id; let wallet; if (!id) @@ -921,9 +921,9 @@ HTTPServer.prototype.handleAuth = function handleAuth(socket) { }); socket.hook('wallet leave', (args) => { - let valid = new Validator([args]); - let id = valid.str(0, ''); - let channel = 'w:' + id; + const valid = new Validator([args]); + const id = valid.str(0, ''); + const channel = 'w:' + id; if (!id) throw new Error('Invalid parameter.'); @@ -1074,7 +1074,7 @@ function hash256(data) { function enforce(value, msg) { if (!value) { - let err = new Error(msg); + const err = new Error(msg); err.statusCode = 400; throw err; } diff --git a/lib/wallet/layout.js b/lib/wallet/layout.js index 6aaa83293..fa81f6e23 100644 --- a/lib/wallet/layout.js +++ b/lib/wallet/layout.js @@ -29,7 +29,7 @@ const layouts = exports; layouts.walletdb = { binary: true, p: function p(hash) { - let key = Buffer.allocUnsafe(1 + (hash.length / 2)); + const key = Buffer.allocUnsafe(1 + (hash.length / 2)); assert(typeof hash === 'string'); key[0] = 0x70; key.write(hash, 1, 'hex'); @@ -41,7 +41,7 @@ layouts.walletdb = { return key.toString('hex', 1); }, P: function P(wid, hash) { - let key = Buffer.allocUnsafe(1 + 4 + (hash.length / 2)); + const key = Buffer.allocUnsafe(1 + 4 + (hash.length / 2)); assert(typeof wid === 'number'); assert(typeof hash === 'string'); key[0] = 0x50; @@ -55,7 +55,7 @@ layouts.walletdb = { return key.toString('hex', 5); }, r: function r(wid, index, hash) { - let key = Buffer.allocUnsafe(1 + 4 + 4 + (hash.length / 2)); + const key = Buffer.allocUnsafe(1 + 4 + 4 + (hash.length / 2)); assert(typeof wid === 'number'); assert(typeof index === 'number'); assert(typeof hash === 'string'); @@ -71,7 +71,7 @@ layouts.walletdb = { return key.toString('hex', 9); }, w: function w(wid) { - let key = Buffer.allocUnsafe(5); + const key = Buffer.allocUnsafe(5); assert(typeof wid === 'number'); key[0] = 0x77; key.writeUInt32BE(wid, 1, true); @@ -83,8 +83,8 @@ layouts.walletdb = { return key.readUInt32BE(1, true); }, l: function l(id) { - let len = Buffer.byteLength(id, 'ascii'); - let key = Buffer.allocUnsafe(1 + len); + const len = Buffer.byteLength(id, 'ascii'); + const key = Buffer.allocUnsafe(1 + len); assert(typeof id === 'string'); key[0] = 0x6c; if (len > 0) @@ -97,7 +97,7 @@ layouts.walletdb = { return key.toString('ascii', 1); }, a: function a(wid, index) { - let key = Buffer.allocUnsafe(9); + const key = Buffer.allocUnsafe(9); assert(typeof wid === 'number'); assert(typeof index === 'number'); key[0] = 0x61; @@ -106,8 +106,8 @@ layouts.walletdb = { return key; }, i: function i(wid, name) { - let len = Buffer.byteLength(name, 'ascii'); - let key = Buffer.allocUnsafe(5 + len); + const len = Buffer.byteLength(name, 'ascii'); + const key = Buffer.allocUnsafe(5 + len); assert(typeof wid === 'number'); assert(typeof name === 'string'); key[0] = 0x69; @@ -122,7 +122,7 @@ layouts.walletdb = { return [key.readUInt32BE(1, true), key.toString('ascii', 5)]; }, n: function n(wid, index) { - let key = Buffer.allocUnsafe(9); + const key = Buffer.allocUnsafe(9); assert(typeof wid === 'number'); assert(typeof index === 'number'); key[0] = 0x6e; @@ -132,14 +132,14 @@ layouts.walletdb = { }, R: Buffer.from([0x52]), h: function h(height) { - let key = Buffer.allocUnsafe(5); + const key = Buffer.allocUnsafe(5); assert(typeof height === 'number'); key[0] = 0x68; key.writeUInt32BE(height, 1, true); return key; }, b: function b(height) { - let key = Buffer.allocUnsafe(5); + const key = Buffer.allocUnsafe(5); assert(typeof height === 'number'); key[0] = 0x62; key.writeUInt32BE(height, 1, true); @@ -151,7 +151,7 @@ layouts.walletdb = { return key.readUInt32BE(1, true); }, o: function o(hash, index) { - let key = Buffer.allocUnsafe(37); + const key = Buffer.allocUnsafe(37); assert(typeof hash === 'string'); assert(typeof index === 'number'); key[0] = 0x6f; @@ -187,7 +187,7 @@ layouts.walletdb = { layouts.txdb = { binary: true, prefix: function prefix(wid, key) { - let out = Buffer.allocUnsafe(5 + key.length); + const out = Buffer.allocUnsafe(5 + key.length); assert(typeof wid === 'number'); assert(Buffer.isBuffer(key)); out[0] = 0x74; @@ -202,7 +202,7 @@ layouts.txdb = { }, R: Buffer.from([0x52]), hi: function hi(ch, hash, index) { - let key = Buffer.allocUnsafe(37); + const key = Buffer.allocUnsafe(37); assert(typeof hash === 'string'); assert(typeof index === 'number'); key[0] = ch; @@ -217,7 +217,7 @@ layouts.txdb = { return [key.toString('hex', 0, 32), key.readUInt32BE(32, true)]; }, ih: function ih(ch, index, hash) { - let key = Buffer.allocUnsafe(37); + const key = Buffer.allocUnsafe(37); assert(typeof index === 'number'); assert(typeof hash === 'string'); key[0] = ch; @@ -232,7 +232,7 @@ layouts.txdb = { return [key.readUInt32BE(0, true), key.toString('hex', 4, 36)]; }, iih: function iih(ch, index, num, hash) { - let key = Buffer.allocUnsafe(41); + const key = Buffer.allocUnsafe(41); assert(typeof index === 'number'); assert(typeof num === 'number'); assert(typeof hash === 'string'); @@ -253,7 +253,7 @@ layouts.txdb = { ]; }, ihi: function ihi(ch, index, hash, num) { - let key = Buffer.allocUnsafe(41); + const key = Buffer.allocUnsafe(41); assert(typeof index === 'number'); assert(typeof hash === 'string'); assert(typeof num === 'number'); @@ -274,7 +274,7 @@ layouts.txdb = { ]; }, ha: function ha(ch, hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); assert(typeof hash === 'string'); key[0] = ch; key.write(hash, 1, 'hex'); @@ -362,7 +362,7 @@ layouts.txdb = { return this.ha(0x72, hash); }, b: function b(height) { - let key = Buffer.allocUnsafe(5); + const key = Buffer.allocUnsafe(5); assert(typeof height === 'number'); key[0] = 0x62; key.writeUInt32BE(height, 1, true); diff --git a/lib/wallet/masterkey.js b/lib/wallet/masterkey.js index 6cc158da1..869fc1e5a 100644 --- a/lib/wallet/masterkey.js +++ b/lib/wallet/masterkey.js @@ -170,7 +170,7 @@ MasterKey.fromOptions = function fromOptions(options) { */ MasterKey.prototype.unlock = async function _unlock(passphrase, timeout) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._unlock(passphrase, timeout); } finally { @@ -253,10 +253,10 @@ MasterKey.prototype.stop = function stop() { */ MasterKey.prototype.derive = async function derive(passwd) { - let salt = MasterKey.SALT; - let N = this.N; - let r = this.r; - let p = this.p; + const salt = MasterKey.SALT; + const N = this.N; + const r = this.r; + const p = this.p; if (typeof passwd === 'string') passwd = Buffer.from(passwd, 'utf8'); @@ -313,7 +313,7 @@ MasterKey.prototype.decipher = function decipher(data, iv) { */ MasterKey.prototype.lock = async function _lock() { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._lock(); } finally { @@ -363,7 +363,7 @@ MasterKey.prototype.destroy = async function destroy() { */ MasterKey.prototype.decrypt = async function decrypt(passphrase, clean) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._decrypt(passphrase, clean); } finally { @@ -412,7 +412,7 @@ MasterKey.prototype._decrypt = async function decrypt(passphrase, clean) { */ MasterKey.prototype.encrypt = async function encrypt(passphrase, clean) { - let unlock = await this.locker.lock(); + const unlock = await this.locker.lock(); try { return await this._encrypt(passphrase, clean); } finally { @@ -481,7 +481,7 @@ MasterKey.prototype.getKeySize = function getKeySize() { */ MasterKey.prototype.toKeyRaw = function toKeyRaw() { - let bw = new StaticWriter(this.getKeySize()); + const bw = new StaticWriter(this.getKeySize()); this.key.toWriter(bw); @@ -501,7 +501,7 @@ MasterKey.prototype.toKeyRaw = function toKeyRaw() { */ MasterKey.prototype.fromKeyRaw = function fromKeyRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.key = HD.PrivateKey.fromReader(br); @@ -541,7 +541,7 @@ MasterKey.prototype.getSize = function getSize() { MasterKey.prototype.toRaw = function toRaw() { let size = this.getSize(); - let bw = new StaticWriter(size); + const bw = new StaticWriter(size); if (this.encrypted) { bw.writeU8(1); @@ -581,7 +581,7 @@ MasterKey.prototype.toRaw = function toRaw() { */ MasterKey.prototype.fromRaw = function fromRaw(raw) { - let br = new BufferReader(raw); + const br = new BufferReader(raw); this.encrypted = br.readU8() === 1; @@ -681,7 +681,7 @@ MasterKey.prototype.toJSON = function toJSON(unsafe) { */ MasterKey.prototype.inspect = function inspect() { - let json = this.toJSON(true); + const json = this.toJSON(true); if (this.key) json.key = this.key.toJSON(); diff --git a/lib/wallet/nodeclient.js b/lib/wallet/nodeclient.js index 9c94ffe8a..ec32d94dd 100644 --- a/lib/wallet/nodeclient.js +++ b/lib/wallet/nodeclient.js @@ -103,7 +103,7 @@ NodeClient.prototype.getTip = function getTip() { */ NodeClient.prototype.getEntry = async function getEntry(hash) { - let entry = await this.node.chain.db.getEntry(hash); + const entry = await this.node.chain.db.getEntry(hash); if (!entry) return; diff --git a/lib/wallet/path.js b/lib/wallet/path.js index 88db8b55a..5e0288b59 100644 --- a/lib/wallet/path.js +++ b/lib/wallet/path.js @@ -104,7 +104,7 @@ Path.fromOptions = function fromOptions(options) { */ Path.prototype.clone = function clone() { - let path = new Path(); + const path = new Path(); path.keyType = this.keyType; @@ -132,7 +132,7 @@ Path.prototype.clone = function clone() { */ Path.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.account = br.readU32(); this.keyType = br.readU8(); @@ -204,8 +204,8 @@ Path.prototype.getSize = function getSize() { */ Path.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU32(this.account); bw.writeU8(this.keyType); diff --git a/lib/wallet/plugin.js b/lib/wallet/plugin.js index d0b35b547..e924a861d 100644 --- a/lib/wallet/plugin.js +++ b/lib/wallet/plugin.js @@ -29,8 +29,8 @@ plugin.id = 'walletdb'; */ plugin.init = function init(node) { - let config = node.config; - let client = new NodeClient(node); + const config = node.config; + const client = new NodeClient(node); let wdb; wdb = new WalletDB({ diff --git a/lib/wallet/records.js b/lib/wallet/records.js index c00383a45..94ca0dcd1 100644 --- a/lib/wallet/records.js +++ b/lib/wallet/records.js @@ -38,7 +38,7 @@ function ChainState() { */ ChainState.prototype.clone = function clone() { - let state = new ChainState(); + const state = new ChainState(); state.startHeight = this.startHeight; state.startHash = this.startHash; state.height = this.height; @@ -53,7 +53,7 @@ ChainState.prototype.clone = function clone() { */ ChainState.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.startHeight = br.readU32(); this.startHash = br.readHash('hex'); @@ -83,7 +83,7 @@ ChainState.fromRaw = function fromRaw(data) { */ ChainState.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(41); + const bw = new StaticWriter(41); bw.writeU32(this.startHeight); bw.writeHash(this.startHash); @@ -161,7 +161,7 @@ BlockMeta.prototype.fromJSON = function fromJSON(json) { */ BlockMeta.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.hash = br.readHash('hex'); this.height = br.readU32(); this.time = br.readU32(); @@ -205,7 +205,7 @@ BlockMeta.fromRaw = function fromRaw(data) { */ BlockMeta.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(42); + const bw = new StaticWriter(42); bw.writeHash(this.hash); bw.writeU32(this.height); bw.writeU32(this.time); @@ -248,12 +248,12 @@ function BlockMapRecord(height) { */ BlockMapRecord.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let count = br.readU32(); + const br = new BufferReader(data); + const count = br.readU32(); for (let i = 0; i < count; i++) { - let hash = br.readHash('hex'); - let tx = TXMapRecord.fromReader(hash, br); + const hash = br.readHash('hex'); + const tx = TXMapRecord.fromReader(hash, br); this.txs.set(tx.hash, tx); } @@ -281,7 +281,7 @@ BlockMapRecord.prototype.getSize = function getSize() { size += 4; - for (let tx of this.txs.values()) { + for (const tx of this.txs.values()) { size += 32; size += tx.getSize(); } @@ -296,12 +296,12 @@ BlockMapRecord.prototype.getSize = function getSize() { */ BlockMapRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU32(this.txs.size); - for (let [hash, tx] of this.txs) { + for (const [hash, tx] of this.txs) { bw.writeHash(hash); tx.toWriter(bw); } @@ -335,7 +335,7 @@ BlockMapRecord.prototype.add = function add(hash, wid) { */ BlockMapRecord.prototype.remove = function remove(hash, wid) { - let tx = this.txs.get(hash); + const tx = this.txs.get(hash); if (!tx) return false; @@ -355,9 +355,9 @@ BlockMapRecord.prototype.remove = function remove(hash, wid) { */ BlockMapRecord.prototype.toArray = function toArray() { - let txs = []; + const txs = []; - for (let tx of this.txs.values()) + for (const tx of this.txs.values()) txs.push(tx); return txs; @@ -394,7 +394,7 @@ TXMapRecord.prototype.getSize = function getSize() { }; TXMapRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -447,7 +447,7 @@ OutpointMapRecord.prototype.getSize = function getSize() { }; OutpointMapRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -499,7 +499,7 @@ PathMapRecord.prototype.getSize = function getSize() { }; PathMapRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -650,8 +650,8 @@ TXRecord.prototype.getSize = function getSize() { */ TXRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); let index = this.index; this.tx.toWriter(bw); @@ -681,7 +681,7 @@ TXRecord.prototype.toRaw = function toRaw() { */ TXRecord.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.tx = new TX(); this.tx.fromReader(br); @@ -717,8 +717,8 @@ TXRecord.fromRaw = function fromRaw(data) { */ function parseWallets(br) { - let count = br.readU32(); - let wids = new Set(); + const count = br.readU32(); + const wids = new Set(); for (let i = 0; i < count; i++) wids.add(br.readU32()); @@ -733,7 +733,7 @@ function sizeWallets(wids) { function serializeWallets(bw, wids) { bw.writeU32(wids.size); - for (let wid of wids) + for (const wid of wids) bw.writeU32(wid); return bw; diff --git a/lib/wallet/rpc.js b/lib/wallet/rpc.js index b64e9d0a3..14b0dc459 100644 --- a/lib/wallet/rpc.js +++ b/lib/wallet/rpc.js @@ -135,9 +135,9 @@ RPC.prototype.stop = async function stop(args, help) { RPC.prototype.fundRawTransaction = async function fundRawTransaction(args, help) { let valid = new Validator([args]); - let data = valid.buf(0); + const data = valid.buf(0); let options = valid.obj(1); - let wallet = this.wallet; + const wallet = this.wallet; let rate = this.feeRate; let change, tx; @@ -184,8 +184,8 @@ RPC.prototype.fundRawTransaction = async function fundRawTransaction(args, help) */ RPC.prototype.resendWalletTransactions = async function resendWalletTransactions(args, help) { - let wallet = this.wallet; - let hashes = []; + const wallet = this.wallet; + const hashes = []; let txs; if (help || args.length !== 0) @@ -193,7 +193,7 @@ RPC.prototype.resendWalletTransactions = async function resendWalletTransactions txs = await wallet.resend(); - for (let tx of txs) + for (const tx of txs) hashes.push(tx.txid()); return hashes; @@ -218,8 +218,8 @@ RPC.prototype.addWitnessAddress = async function addWitnessAddress(args, help) { }; RPC.prototype.backupWallet = async function backupWallet(args, help) { - let valid = new Validator([args]); - let dest = valid.str(0); + const valid = new Validator([args]); + const dest = valid.str(0); if (help || args.length !== 1 || !dest) throw new RPCError(errs.MISC_ERROR, 'backupwallet "destination"'); @@ -230,9 +230,9 @@ RPC.prototype.backupWallet = async function backupWallet(args, help) { }; RPC.prototype.dumpPrivKey = async function dumpPrivKey(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let addr = valid.str(0, ''); + const wallet = this.wallet; + const valid = new Validator([args]); + const addr = valid.str(0, ''); let hash, ring; if (help || args.length !== 1) @@ -248,10 +248,10 @@ RPC.prototype.dumpPrivKey = async function dumpPrivKey(args, help) { }; RPC.prototype.dumpWallet = async function dumpWallet(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let file = valid.str(0); - let time = util.date(); + const wallet = this.wallet; + const valid = new Validator([args]); + const file = valid.str(0); + const time = util.date(); let tip, out, hashes; if (help || args.length !== 1) @@ -273,8 +273,8 @@ RPC.prototype.dumpWallet = async function dumpWallet(args, help) { hashes = await wallet.getAddressHashes(); - for (let hash of hashes) { - let ring = await wallet.getPrivateKey(hash); + for (const hash of hashes) { + const ring = await wallet.getPrivateKey(hash); let addr, fmt, str; if (!ring) @@ -306,9 +306,9 @@ RPC.prototype.dumpWallet = async function dumpWallet(args, help) { }; RPC.prototype.encryptWallet = async function encryptWallet(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let passphrase = valid.str(0, ''); + const wallet = this.wallet; + const valid = new Validator([args]); + const passphrase = valid.str(0, ''); if (!wallet.master.encrypted && (help || args.length !== 1)) throw new RPCError(errs.MISC_ERROR, 'encryptwallet "passphrase"'); @@ -331,8 +331,8 @@ RPC.prototype.encryptWallet = async function encryptWallet(args, help) { }; RPC.prototype.getAccountAddress = async function getAccountAddress(args, help) { - let valid = new Validator([args]); - let wallet = this.wallet; + const valid = new Validator([args]); + const wallet = this.wallet; let name = valid.str(0, ''); let account; @@ -351,9 +351,9 @@ RPC.prototype.getAccountAddress = async function getAccountAddress(args, help) { }; RPC.prototype.getAccount = async function getAccount(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let addr = valid.str(0, ''); + const wallet = this.wallet; + const valid = new Validator([args]); + const addr = valid.str(0, ''); let hash, path; if (help || args.length !== 1) @@ -369,10 +369,10 @@ RPC.prototype.getAccount = async function getAccount(args, help) { }; RPC.prototype.getAddressesByAccount = async function getAddressesByAccount(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0, ''); - let addrs = []; + const addrs = []; let paths; if (help || args.length !== 1) @@ -383,8 +383,8 @@ RPC.prototype.getAddressesByAccount = async function getAddressesByAccount(args, paths = await wallet.getPaths(name); - for (let path of paths) { - let addr = path.toAddress(); + for (const path of paths) { + const addr = path.toAddress(); addrs.push(addr.toString(this.network)); } @@ -392,11 +392,11 @@ RPC.prototype.getAddressesByAccount = async function getAddressesByAccount(args, }; RPC.prototype.getBalance = async function getBalance(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0); - let minconf = valid.u32(1, 0); - let watchOnly = valid.bool(2, false); + const minconf = valid.u32(1, 0); + const watchOnly = valid.bool(2, false); let value, balance; if (help || args.length > 3) { @@ -424,8 +424,8 @@ RPC.prototype.getBalance = async function getBalance(args, help) { }; RPC.prototype.getNewAddress = async function getNewAddress(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0); let addr; @@ -441,7 +441,7 @@ RPC.prototype.getNewAddress = async function getNewAddress(args, help) { }; RPC.prototype.getRawChangeAddress = async function getRawChangeAddress(args, help) { - let wallet = this.wallet; + const wallet = this.wallet; let addr; if (help || args.length > 1) @@ -453,12 +453,12 @@ RPC.prototype.getRawChangeAddress = async function getRawChangeAddress(args, hel }; RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0); - let minconf = valid.u32(0, 0); - let height = this.wdb.state.height; - let filter = new Set(); + const minconf = valid.u32(0, 0); + const height = this.wdb.state.height; + const filter = new Set(); let total = 0; let lastConf = -1; let paths, txs; @@ -473,13 +473,13 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h paths = await wallet.getPaths(name); - for (let path of paths) + for (const path of paths) filter.add(path.hash); txs = await wallet.getHistory(name); - for (let wtx of txs) { - let conf = wtx.getDepth(height); + for (const wtx of txs) { + const conf = wtx.getDepth(height); if (conf < minconf) continue; @@ -487,8 +487,8 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h if (lastConf === -1 || conf < lastConf) lastConf = conf; - for (let output of wtx.tx.outputs) { - let hash = output.getHash('hex'); + for (const output of wtx.tx.outputs) { + const hash = output.getHash('hex'); if (hash && filter.has(hash)) total += output.value; } @@ -498,11 +498,11 @@ RPC.prototype.getReceivedByAccount = async function getReceivedByAccount(args, h }; RPC.prototype.getReceivedByAddress = async function getReceivedByAddress(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let addr = valid.str(0, ''); - let minconf = valid.u32(1, 0); - let height = this.wdb.state.height; + const wallet = this.wallet; + const valid = new Validator([args]); + const addr = valid.str(0, ''); + const minconf = valid.u32(1, 0); + const height = this.wdb.state.height; let total = 0; let hash, txs; @@ -514,11 +514,11 @@ RPC.prototype.getReceivedByAddress = async function getReceivedByAddress(args, h hash = parseHash(addr, this.network); txs = await wallet.getHistory(); - for (let wtx of txs) { + for (const wtx of txs) { if (wtx.getDepth(height) < minconf) continue; - for (let output of wtx.tx.outputs) { + for (const output of wtx.tx.outputs) { if (output.getHash('hex') === hash) total += output.value; } @@ -528,9 +528,9 @@ RPC.prototype.getReceivedByAddress = async function getReceivedByAddress(args, h }; RPC.prototype._toWalletTX = async function _toWalletTX(wtx) { - let wallet = this.wallet; - let details = await wallet.toDetails(wtx); - let det = []; + const wallet = this.wallet; + const details = await wallet.toDetails(wtx); + const det = []; let sent = 0; let received = 0; let receive = true; @@ -538,7 +538,7 @@ RPC.prototype._toWalletTX = async function _toWalletTX(wtx) { if (!details) throw new RPCError(errs.WALLET_ERROR, 'TX not found.'); - for (let member of details.inputs) { + for (const member of details.inputs) { if (member.path) { receive = false; break; @@ -546,7 +546,7 @@ RPC.prototype._toWalletTX = async function _toWalletTX(wtx) { } for (let i = 0; i < details.outputs.length; i++) { - let member = details.outputs[i]; + const member = details.outputs[i]; if (member.path) { if (member.path.branch === 1) @@ -600,10 +600,10 @@ RPC.prototype._toWalletTX = async function _toWalletTX(wtx) { }; RPC.prototype.getTransaction = async function getTransaction(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let hash = valid.hash(0); - let watchOnly = valid.bool(1, false); + const wallet = this.wallet; + const valid = new Validator([args]); + const hash = valid.hash(0); + const watchOnly = valid.bool(1, false); let wtx; if (help || args.length < 1 || args.length > 2) { @@ -623,9 +623,9 @@ RPC.prototype.getTransaction = async function getTransaction(args, help) { }; RPC.prototype.abandonTransaction = async function abandonTransaction(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let hash = valid.hash(0); + const wallet = this.wallet; + const valid = new Validator([args]); + const hash = valid.hash(0); let result; if (help || args.length !== 1) @@ -643,7 +643,7 @@ RPC.prototype.abandonTransaction = async function abandonTransaction(args, help) }; RPC.prototype.getUnconfirmedBalance = async function getUnconfirmedBalance(args, help) { - let wallet = this.wallet; + const wallet = this.wallet; let balance; if (help || args.length > 0) @@ -655,7 +655,7 @@ RPC.prototype.getUnconfirmedBalance = async function getUnconfirmedBalance(args, }; RPC.prototype.getWalletInfo = async function getWalletInfo(args, help) { - let wallet = this.wallet; + const wallet = this.wallet; let balance; if (help || args.length !== 0) @@ -679,10 +679,10 @@ RPC.prototype.getWalletInfo = async function getWalletInfo(args, help) { }; RPC.prototype.importPrivKey = async function importPrivKey(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let secret = valid.str(0); - let rescan = valid.bool(2, false); + const wallet = this.wallet; + const valid = new Validator([args]); + const secret = valid.str(0); + const rescan = valid.bool(2, false); let key; if (help || args.length < 1 || args.length > 3) { @@ -701,11 +701,11 @@ RPC.prototype.importPrivKey = async function importPrivKey(args, help) { }; RPC.prototype.importWallet = async function importWallet(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let file = valid.str(0); - let rescan = valid.bool(1, false); - let keys = []; + const wallet = this.wallet; + const valid = new Validator([args]); + const file = valid.str(0); + const rescan = valid.bool(1, false); + const keys = []; let data, lines; if (help || args.length !== 1) @@ -739,7 +739,7 @@ RPC.prototype.importWallet = async function importWallet(args, help) { keys.push(secret); } - for (let key of keys) + for (const key of keys) await wallet.importKey(0, key); if (rescan) @@ -749,11 +749,11 @@ RPC.prototype.importWallet = async function importWallet(args, help) { }; RPC.prototype.importAddress = async function importAddress(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let addr = valid.str(0, ''); - let rescan = valid.bool(2, false); - let p2sh = valid.bool(3, false); + const rescan = valid.bool(2, false); + const p2sh = valid.bool(3, false); let script; if (help || args.length < 1 || args.length > 4) { @@ -784,10 +784,10 @@ RPC.prototype.importAddress = async function importAddress(args, help) { }; RPC.prototype.importPubkey = async function importPubkey(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let data = valid.buf(0); - let rescan = valid.bool(2, false); + const wallet = this.wallet; + const valid = new Validator([args]); + const data = valid.buf(0); + const rescan = valid.bool(2, false); let key; if (help || args.length < 1 || args.length > 4) { @@ -815,11 +815,11 @@ RPC.prototype.keyPoolRefill = async function keyPoolRefill(args, help) { }; RPC.prototype.listAccounts = async function listAccounts(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let minconf = valid.u32(0, 0); - let watchOnly = valid.bool(1, false); - let map = {}; + const wallet = this.wallet; + const valid = new Validator([args]); + const minconf = valid.u32(0, 0); + const watchOnly = valid.bool(1, false); + const map = {}; let accounts; if (help || args.length > 2) { @@ -829,8 +829,8 @@ RPC.prototype.listAccounts = async function listAccounts(args, help) { accounts = await wallet.getAccounts(); - for (let account of accounts) { - let balance = await wallet.getBalance(account); + for (const account of accounts) { + const balance = await wallet.getBalance(account); let value = balance.unconfirmed; if (minconf > 0) @@ -852,8 +852,8 @@ RPC.prototype.listAddressGroupings = async function listAddressGroupings(args, h }; RPC.prototype.listLockUnspent = async function listLockUnspent(args, help) { - let wallet = this.wallet; - let out = []; + const wallet = this.wallet; + const out = []; let outpoints; if (help || args.length > 0) @@ -861,7 +861,7 @@ RPC.prototype.listLockUnspent = async function listLockUnspent(args, help) { outpoints = wallet.getLocked(); - for (let outpoint of outpoints) { + for (const outpoint of outpoints) { out.push({ txid: outpoint.txid(), vout: outpoint.index @@ -872,10 +872,10 @@ RPC.prototype.listLockUnspent = async function listLockUnspent(args, help) { }; RPC.prototype.listReceivedByAccount = async function listReceivedByAccount(args, help) { - let valid = new Validator([args]); - let minconf = valid.u32(0, 0); - let includeEmpty = valid.bool(1, false); - let watchOnly = valid.bool(2, false); + const valid = new Validator([args]); + const minconf = valid.u32(0, 0); + const includeEmpty = valid.bool(1, false); + const watchOnly = valid.bool(2, false); if (help || args.length > 3) { throw new RPCError(errs.MISC_ERROR, @@ -886,10 +886,10 @@ RPC.prototype.listReceivedByAccount = async function listReceivedByAccount(args, }; RPC.prototype.listReceivedByAddress = async function listReceivedByAddress(args, help) { - let valid = new Validator([args]); - let minconf = valid.u32(0, 0); - let includeEmpty = valid.bool(1, false); - let watchOnly = valid.bool(2, false); + const valid = new Validator([args]); + const minconf = valid.u32(0, 0); + const includeEmpty = valid.bool(1, false); + const watchOnly = valid.bool(2, false); if (help || args.length > 3) { throw new RPCError(errs.MISC_ERROR, @@ -900,16 +900,16 @@ RPC.prototype.listReceivedByAddress = async function listReceivedByAddress(args, }; RPC.prototype._listReceived = async function _listReceived(minconf, empty, watchOnly, account) { - let wallet = this.wallet; - let paths = await wallet.getPaths(); - let height = this.wdb.state.height; - let map = new Map(); + const wallet = this.wallet; + const paths = await wallet.getPaths(); + const height = this.wdb.state.height; + const map = new Map(); let out = []; - let result = []; + const result = []; let txs; - for (let path of paths) { - let addr = path.toAddress(); + for (const path of paths) { + const addr = path.toAddress(); map.set(path.hash, { involvesWatchonly: wallet.watchOnly, address: addr.toString(this.network), @@ -922,14 +922,14 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch txs = await wallet.getHistory(); - for (let wtx of txs) { - let conf = wtx.getDepth(height); + for (const wtx of txs) { + const conf = wtx.getDepth(height); if (conf < minconf) continue; - for (let output of wtx.tx.outputs) { - let addr = output.getAddress(); + for (const output of wtx.tx.outputs) { + const addr = output.getAddress(); let hash, entry; if (!addr) @@ -947,14 +947,14 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch } } - for (let entry of map.values()) + for (const entry of map.values()) out.push(entry); if (account) { - let map = new Map(); + const map = new Map(); - for (let entry of out) { - let item = map.get(entry.account); + for (const entry of out) { + const item = map.get(entry.account); if (!item) { map.set(entry.account, entry); entry.address = undefined; @@ -965,11 +965,11 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch out = []; - for (let entry of map.values()) + for (const entry of map.values()) out.push(entry); } - for (let entry of out) { + for (const entry of out) { if (!empty && entry.amount === 0) continue; @@ -984,14 +984,14 @@ RPC.prototype._listReceived = async function _listReceived(minconf, empty, watch }; RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { - let wallet = this.wallet; - let chainHeight = this.wdb.state.height; - let valid = new Validator([args]); - let block = valid.hash(0); - let minconf = valid.u32(1, 0); - let watchOnly = valid.bool(2, false); + const wallet = this.wallet; + const chainHeight = this.wdb.state.height; + const valid = new Validator([args]); + const block = valid.hash(0); + const minconf = valid.u32(1, 0); + const watchOnly = valid.bool(2, false); let height = -1; - let out = []; + const out = []; let txs, highest; if (help) { @@ -1003,7 +1003,7 @@ RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { return out; if (block) { - let entry = await this.client.getEntry(block); + const entry = await this.client.getEntry(block); if (entry) height = entry.height; } @@ -1013,7 +1013,7 @@ RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { txs = await wallet.getHistory(); - for (let wtx of txs) { + for (const wtx of txs) { let json; if (wtx.height < height) @@ -1039,8 +1039,8 @@ RPC.prototype.listSinceBlock = async function listSinceBlock(args, help) { }; RPC.prototype._toListTX = async function _toListTX(wtx) { - let wallet = this.wallet; - let details = await wallet.toDetails(wtx); + const wallet = this.wallet; + const details = await wallet.toDetails(wtx); let sent = 0; let received = 0; let receive = true; @@ -1050,7 +1050,7 @@ RPC.prototype._toListTX = async function _toListTX(wtx) { if (!details) throw new RPCError(errs.WALLET_ERROR, 'TX not found.'); - for (let member of details.inputs) { + for (const member of details.inputs) { if (member.path) { receive = false; break; @@ -1058,7 +1058,7 @@ RPC.prototype._toListTX = async function _toListTX(wtx) { } for (let i = 0; i < details.outputs.length; i++) { - let member = details.outputs[i]; + const member = details.outputs[i]; if (member.path) { if (member.path.branch === 1) @@ -1111,14 +1111,14 @@ RPC.prototype._toListTX = async function _toListTX(wtx) { }; RPC.prototype.listTransactions = async function listTransactions(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0); - let count = valid.u32(1, 10); - let from = valid.u32(2, 0); - let watchOnly = valid.bool(3, false); + const count = valid.u32(1, 10); + const from = valid.u32(2, 0); + const watchOnly = valid.bool(3, false); let end = from + count; - let out = []; + const out = []; let txs; if (help || args.length > 4) { @@ -1139,8 +1139,8 @@ RPC.prototype.listTransactions = async function listTransactions(args, help) { end = Math.min(end, txs.length); for (let i = from; i < end; i++) { - let wtx = txs[i]; - let json = await this._toListTX(wtx); + const wtx = txs[i]; + const json = await this._toListTX(wtx); out.push(json); } @@ -1148,14 +1148,14 @@ RPC.prototype.listTransactions = async function listTransactions(args, help) { }; RPC.prototype.listUnspent = async function listUnspent(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let minDepth = valid.u32(0, 1); - let maxDepth = valid.u32(1, 9999999); - let addrs = valid.array(2); - let height = this.wdb.state.height; - let map = new Set(); - let out = []; + const wallet = this.wallet; + const valid = new Validator([args]); + const minDepth = valid.u32(0, 1); + const maxDepth = valid.u32(1, 9999999); + const addrs = valid.array(2); + const height = this.wdb.state.height; + const map = new Set(); + const out = []; let coins; if (help || args.length > 3) { @@ -1164,10 +1164,10 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { } if (addrs) { - let valid = new Validator([addrs]); + const valid = new Validator([addrs]); for (let i = 0; i < addrs.length; i++) { - let addr = valid.str(i, ''); - let hash = parseHash(addr, this.network); + const addr = valid.str(i, ''); + const hash = parseHash(addr, this.network); if (map.has(hash)) throw new RPCError(errs.INVALID_PARAMETER, 'Duplicate address.'); @@ -1180,8 +1180,8 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { common.sortCoins(coins); - for (let coin of coins) { - let depth = coin.getDepth(height); + for (const coin of coins) { + const depth = coin.getDepth(height); let addr, hash, ring; if (!(depth >= minDepth && depth <= maxDepth)) @@ -1221,10 +1221,10 @@ RPC.prototype.listUnspent = async function listUnspent(args, help) { }; RPC.prototype.lockUnspent = async function lockUnspent(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let unlock = valid.bool(0, false); - let outputs = valid.array(1); + const wallet = this.wallet; + const valid = new Validator([args]); + const unlock = valid.bool(0, false); + const outputs = valid.array(1); if (help || args.length < 1 || args.length > 2) { throw new RPCError(errs.MISC_ERROR, @@ -1240,10 +1240,10 @@ RPC.prototype.lockUnspent = async function lockUnspent(args, help) { if (!outputs) throw new RPCError(errs.TYPE_ERROR, 'Invalid parameter.'); - for (let output of outputs) { - let valid = new Validator([output]); - let hash = valid.hash('txid'); - let index = valid.u32('vout'); + for (const output of outputs) { + const valid = new Validator([output]); + const hash = valid.hash('txid'); + const index = valid.u32('vout'); let outpoint; if (hash == null || index == null) @@ -1270,12 +1270,12 @@ RPC.prototype.move = async function move(args, help) { }; RPC.prototype.sendFrom = async function sendFrom(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let name = valid.str(0); let addr = valid.str(1); - let value = valid.btc(2); - let minconf = valid.u32(3, 0); + const value = valid.btc(2); + const minconf = valid.u32(3, 0); let options, tx; if (help || args.length < 3 || args.length > 6) { @@ -1309,14 +1309,14 @@ RPC.prototype.sendFrom = async function sendFrom(args, help) { }; RPC.prototype.sendMany = async function sendMany(args, help) { - let wallet = this.wallet; + const wallet = this.wallet; let valid = new Validator([args]); let name = valid.str(0); - let sendTo = valid.obj(1); - let minconf = valid.u32(2, 1); - let subtractFee = valid.bool(4, false); - let uniq = new Set(); - let outputs = []; + const sendTo = valid.obj(1); + const minconf = valid.u32(2, 1); + const subtractFee = valid.bool(4, false); + const uniq = new Set(); + const outputs = []; let options, tx; if (help || args.length < 2 || args.length > 5) { @@ -1333,10 +1333,10 @@ RPC.prototype.sendMany = async function sendMany(args, help) { valid = new Validator([sendTo]); - for (let key of Object.keys(sendTo)) { - let value = valid.btc(key); - let addr = parseAddress(key, this.network); - let hash = addr.getHash('hex'); + for (const key of Object.keys(sendTo)) { + const value = valid.btc(key); + const addr = parseAddress(key, this.network); + const hash = addr.getHash('hex'); let output; if (value == null) @@ -1366,11 +1366,11 @@ RPC.prototype.sendMany = async function sendMany(args, help) { }; RPC.prototype.sendToAddress = async function sendToAddress(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let addr = valid.str(0); - let value = valid.btc(1); - let subtractFee = valid.bool(4, false); + const value = valid.btc(1); + const subtractFee = valid.bool(4, false); let options, tx; if (help || args.length < 2 || args.length > 5) { @@ -1409,8 +1409,8 @@ RPC.prototype.setAccount = async function setAccount(args, help) { }; RPC.prototype.setTXFee = async function setTXFee(args, help) { - let valid = new Validator([args]); - let rate = valid.btc(0); + const valid = new Validator([args]); + const rate = valid.btc(0); if (help || args.length < 1 || args.length > 1) throw new RPCError(errs.MISC_ERROR, 'settxfee amount'); @@ -1424,8 +1424,8 @@ RPC.prototype.setTXFee = async function setTXFee(args, help) { }; RPC.prototype.signMessage = async function signMessage(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); + const wallet = this.wallet; + const valid = new Validator([args]); let addr = valid.str(0, ''); let msg = valid.str(1, ''); let sig, ring; @@ -1454,7 +1454,7 @@ RPC.prototype.signMessage = async function signMessage(args, help) { }; RPC.prototype.walletLock = async function walletLock(args, help) { - let wallet = this.wallet; + const wallet = this.wallet; if (help || (wallet.master.encrypted && args.length !== 0)) throw new RPCError(errs.MISC_ERROR, 'walletlock'); @@ -1468,10 +1468,10 @@ RPC.prototype.walletLock = async function walletLock(args, help) { }; RPC.prototype.walletPassphraseChange = async function walletPassphraseChange(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let old = valid.str(0, ''); - let new_ = valid.str(1, ''); + const wallet = this.wallet; + const valid = new Validator([args]); + const old = valid.str(0, ''); + const new_ = valid.str(1, ''); if (help || (wallet.master.encrypted && args.length !== 2)) { throw new RPCError(errs.MISC_ERROR, 'walletpassphrasechange' @@ -1490,10 +1490,10 @@ RPC.prototype.walletPassphraseChange = async function walletPassphraseChange(arg }; RPC.prototype.walletPassphrase = async function walletPassphrase(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let passphrase = valid.str(0, ''); - let timeout = valid.u32(1); + const wallet = this.wallet; + const valid = new Validator([args]); + const passphrase = valid.str(0, ''); + const timeout = valid.u32(1); if (help || (wallet.master.encrypted && args.length !== 2)) { throw new RPCError(errs.MISC_ERROR, @@ -1515,7 +1515,7 @@ RPC.prototype.walletPassphrase = async function walletPassphrase(args, help) { }; RPC.prototype.importPrunedFunds = async function importPrunedFunds(args, help) { - let valid = new Validator([args]); + const valid = new Validator([args]); let tx = valid.buf(0); let block = valid.buf(1); let hash, height; @@ -1556,9 +1556,9 @@ RPC.prototype.importPrunedFunds = async function importPrunedFunds(args, help) { }; RPC.prototype.removePrunedFunds = async function removePrunedFunds(args, help) { - let wallet = this.wallet; - let valid = new Validator([args]); - let hash = valid.hash(0); + const wallet = this.wallet; + const valid = new Validator([args]); + const hash = valid.hash(0); if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'removeprunedfunds "txid"'); @@ -1573,8 +1573,8 @@ RPC.prototype.removePrunedFunds = async function removePrunedFunds(args, help) { }; RPC.prototype.selectWallet = async function selectWallet(args, help) { - let valid = new Validator([args]); - let id = valid.str(0); + const valid = new Validator([args]); + const id = valid.str(0); let wallet; if (help || args.length !== 1) @@ -1598,8 +1598,8 @@ RPC.prototype.getMemoryInfo = async function getMemoryInfo(args, help) { }; RPC.prototype.setLogLevel = async function setLogLevel(args, help) { - let valid = new Validator([args]); - let level = valid.str(0, ''); + const valid = new Validator([args]); + const level = valid.str(0, ''); if (help || args.length !== 1) throw new RPCError(errs.MISC_ERROR, 'setloglevel "level"'); @@ -1614,7 +1614,7 @@ RPC.prototype.setLogLevel = async function setLogLevel(args, help) { */ function parseHash(raw, network) { - let addr = parseAddress(raw, network); + const addr = parseAddress(raw, network); return addr.getHash('hex'); } diff --git a/lib/wallet/server.js b/lib/wallet/server.js index b9cac845d..3d331dbbb 100644 --- a/lib/wallet/server.js +++ b/lib/wallet/server.js @@ -25,7 +25,7 @@ const server = exports; */ server.create = function create(options) { - let config = new Config('bcoin'); + const config = new Config('bcoin'); let logger = new Logger('debug'); let client, wdb, workers; diff --git a/lib/wallet/txdb.js b/lib/wallet/txdb.js index 26828c03c..7acc1fcaf 100644 --- a/lib/wallet/txdb.js +++ b/lib/wallet/txdb.js @@ -63,7 +63,7 @@ TXDB.layout = layout; */ TXDB.prototype.open = async function open() { - let state = await this.getState(); + const state = await this.getState(); if (state) { this.state = state; @@ -139,7 +139,7 @@ TXDB.prototype.commit = async function commit() { // Emit buffered events now that // we know everything is written. - for (let [event, data, details] of this.events) { + for (const [event, data, details] of this.events) { this.walletdb.emit(event, this.wallet.id, data, details); this.wallet.emit(event, data, details); } @@ -261,7 +261,7 @@ TXDB.prototype.values = function values(options) { */ TXDB.prototype.getPath = function getPath(output) { - let addr = output.getAddress(); + const addr = output.getAddress(); if (!addr) return Promise.resolve(); @@ -276,7 +276,7 @@ TXDB.prototype.getPath = function getPath(output) { */ TXDB.prototype.hasPath = function hasPath(output) { - let addr = output.getAddress(); + const addr = output.getAddress(); if (!addr) return Promise.resolve(false); @@ -291,9 +291,9 @@ TXDB.prototype.hasPath = function hasPath(output) { */ TXDB.prototype.saveCredit = async function saveCredit(credit, path) { - let coin = credit.coin; - let key = coin.toKey(); - let raw = credit.toRaw(); + const coin = credit.coin; + const key = coin.toKey(); + const raw = credit.toRaw(); await this.addOutpointMap(coin.hash, coin.index); @@ -310,8 +310,8 @@ TXDB.prototype.saveCredit = async function saveCredit(credit, path) { */ TXDB.prototype.removeCredit = async function removeCredit(credit, path) { - let coin = credit.coin; - let key = coin.toKey(); + const coin = credit.coin; + const key = coin.toKey(); await this.removeOutpointMap(coin.hash, coin.index); @@ -329,8 +329,8 @@ TXDB.prototype.removeCredit = async function removeCredit(credit, path) { */ TXDB.prototype.spendCredit = function spendCredit(credit, tx, index) { - let prevout = tx.inputs[index].prevout; - let spender = Outpoint.fromTX(tx, index); + const prevout = tx.inputs[index].prevout; + const spender = Outpoint.fromTX(tx, index); this.put(layout.s(prevout.hash, prevout.index), spender.toRaw()); this.put(layout.d(spender.hash, spender.index), credit.coin.toRaw()); }; @@ -342,8 +342,8 @@ TXDB.prototype.spendCredit = function spendCredit(credit, tx, index) { */ TXDB.prototype.unspendCredit = function unspendCredit(tx, index) { - let prevout = tx.inputs[index].prevout; - let spender = Outpoint.fromTX(tx, index); + const prevout = tx.inputs[index].prevout; + const spender = Outpoint.fromTX(tx, index); this.del(layout.s(prevout.hash, prevout.index)); this.del(layout.d(spender.hash, spender.index)); }; @@ -355,8 +355,8 @@ TXDB.prototype.unspendCredit = function unspendCredit(tx, index) { */ TXDB.prototype.writeInput = function writeInput(tx, index) { - let prevout = tx.inputs[index].prevout; - let spender = Outpoint.fromTX(tx, index); + const prevout = tx.inputs[index].prevout; + const spender = Outpoint.fromTX(tx, index); this.put(layout.s(prevout.hash, prevout.index), spender.toRaw()); }; @@ -367,7 +367,7 @@ TXDB.prototype.writeInput = function writeInput(tx, index) { */ TXDB.prototype.removeInput = function removeInput(tx, index) { - let prevout = tx.inputs[index].prevout; + const prevout = tx.inputs[index].prevout; this.del(layout.s(prevout.hash, prevout.index)); }; @@ -381,8 +381,8 @@ TXDB.prototype.removeInput = function removeInput(tx, index) { */ TXDB.prototype.resolveInput = async function resolveInput(tx, index, height, path, own) { - let hash = tx.hash('hex'); - let spent = await this.getSpent(hash, index); + const hash = tx.hash('hex'); + const spent = await this.getSpent(hash, index); let stx, credit; if (!spent) @@ -428,9 +428,9 @@ TXDB.prototype.resolveInput = async function resolveInput(tx, index, height, pat */ TXDB.prototype.isDoubleSpend = async function isDoubleSpend(tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; - let spent = await this.isSpent(prevout.hash, prevout.index); + for (const input of tx.inputs) { + const prevout = input.prevout; + const spent = await this.isSpent(prevout.hash, prevout.index); if (spent) return true; } @@ -449,8 +449,8 @@ TXDB.prototype.isRBF = async function isRBF(tx) { if (tx.isRBF()) return true; - for (let input of tx.inputs) { - let prevout = input.prevout; + for (const input of tx.inputs) { + const prevout = input.prevout; if (await this.has(layout.r(prevout.hash))) return true; } @@ -466,7 +466,7 @@ TXDB.prototype.isRBF = async function isRBF(tx) { */ TXDB.prototype.getSpent = async function getSpent(hash, index) { - let data = await this.get(layout.s(hash, index)); + const data = await this.get(layout.s(hash, index)); if (!data) return; @@ -512,7 +512,7 @@ TXDB.prototype.addOutpointMap = async function addOutpointMap(hash, i) { */ TXDB.prototype.removeOutpointMap = async function removeOutpointMap(hash, i) { - let map = await this.walletdb.getOutpointMap(hash, i); + const map = await this.walletdb.getOutpointMap(hash, i); if (!map) return; @@ -555,7 +555,7 @@ TXDB.prototype.addBlockMap = async function addBlockMap(hash, height) { */ TXDB.prototype.removeBlockMap = async function removeBlockMap(hash, height) { - let block = await this.walletdb.getBlockMap(height); + const block = await this.walletdb.getBlockMap(height); if (!block) return; @@ -591,7 +591,7 @@ TXDB.prototype.getBlocks = function getBlocks() { */ TXDB.prototype.getBlock = async function getBlock(height) { - let data = await this.get(layout.b(height)); + const data = await this.get(layout.b(height)); if (!data) return; @@ -607,7 +607,7 @@ TXDB.prototype.getBlock = async function getBlock(height) { */ TXDB.prototype.addBlock = async function addBlock(hash, meta) { - let key = layout.b(meta.height); + const key = layout.b(meta.height); let data = await this.get(key); let block, size; @@ -634,8 +634,8 @@ TXDB.prototype.addBlock = async function addBlock(hash, meta) { */ TXDB.prototype.removeBlock = async function removeBlock(hash, height) { - let key = layout.b(height); - let data = await this.get(key); + const key = layout.b(height); + const data = await this.get(key); let block, size; if (!data) @@ -684,7 +684,7 @@ TXDB.prototype.addBlockSlow = async function addBlockSlow(hash, meta) { */ TXDB.prototype.removeBlockSlow = async function removeBlockSlow(hash, height) { - let block = await this.getBlock(height); + const block = await this.getBlock(height); if (!block) return; @@ -733,8 +733,8 @@ TXDB.prototype.add = async function add(tx, block) { */ TXDB.prototype._add = async function add(tx, block) { - let hash = tx.hash('hex'); - let existing = await this.getTX(hash); + const hash = tx.hash('hex'); + const existing = await this.getTX(hash); let wtx; assert(!tx.mutable, 'Cannot add mutable TX to wallet.'); @@ -791,20 +791,20 @@ TXDB.prototype._add = async function add(tx, block) { */ TXDB.prototype.insert = async function insert(wtx, block) { - let tx = wtx.tx; - let hash = wtx.hash; - let height = block ? block.height : -1; - let details = new Details(this, wtx, block); - let accounts = new Set(); + const tx = wtx.tx; + const hash = wtx.hash; + const height = block ? block.height : -1; + const details = new Details(this, wtx, block); + const accounts = new Set(); let own = false; let updated = false; if (!tx.isCoinbase()) { // We need to potentially spend some coins here. for (let i = 0; i < tx.inputs.length; i++) { - let input = tx.inputs[i]; - let prevout = input.prevout; - let credit = await this.getCredit(prevout.hash, prevout.index); + const input = tx.inputs[i]; + const prevout = input.prevout; + const credit = await this.getCredit(prevout.hash, prevout.index); let coin, path; if (!credit) { @@ -880,8 +880,8 @@ TXDB.prototype.insert = async function insert(wtx, block) { // Potentially add coins to the utxo set. for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let path = await this.getPath(output); + const output = tx.outputs[i]; + const path = await this.getPath(output); let credit; if (!path) @@ -931,7 +931,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 (let account of accounts) { + for (const account of accounts) { this.put(layout.T(account, hash), null); this.put(layout.M(account, wtx.mtime, hash), null); @@ -978,7 +978,7 @@ TXDB.prototype.insert = async function insert(wtx, block) { */ TXDB.prototype.confirm = async function confirm(hash, block) { - let wtx = await this.getTX(hash); + const wtx = await this.getTX(hash); let details; if (!wtx) @@ -1012,23 +1012,23 @@ TXDB.prototype.confirm = async function confirm(hash, block) { */ TXDB.prototype._confirm = async function confirm(wtx, block) { - let tx = wtx.tx; - let hash = wtx.hash; - let height = block.height; - let details = new Details(this, wtx, block); - let accounts = new Set(); + const tx = wtx.tx; + const hash = wtx.hash; + const height = block.height; + const details = new Details(this, wtx, block); + const accounts = new Set(); wtx.setBlock(block); if (!tx.isCoinbase()) { - let credits = await this.getSpentCredits(tx); + const credits = await this.getSpentCredits(tx); // Potentially spend coins. Now that the tx // is mined, we can actually _remove_ coins // from the utxo state. for (let i = 0; i < tx.inputs.length; i++) { - let input = tx.inputs[i]; - let prevout = input.prevout; + const input = tx.inputs[i]; + const prevout = input.prevout; let credit = credits[i]; let coin, path; @@ -1072,8 +1072,8 @@ TXDB.prototype._confirm = async function confirm(wtx, block) { // Update credit heights, including undo coins. for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let path = await this.getPath(output); + const output = tx.outputs[i]; + const path = await this.getPath(output); let credit, coin; if (!path) @@ -1113,7 +1113,7 @@ TXDB.prototype._confirm = async function confirm(wtx, block) { this.put(layout.h(height, hash), null); // Secondary indexing also needs to change. - for (let account of accounts) { + for (const account of accounts) { this.del(layout.P(account, hash)); this.put(layout.H(account, height, hash), null); } @@ -1142,7 +1142,7 @@ TXDB.prototype._confirm = async function confirm(wtx, block) { */ TXDB.prototype.remove = async function remove(hash) { - let wtx = await this.getTX(hash); + const wtx = await this.getTX(hash); if (!wtx) return; @@ -1159,20 +1159,20 @@ TXDB.prototype.remove = async function remove(hash) { */ TXDB.prototype.erase = async function erase(wtx, block) { - let tx = wtx.tx; - let hash = wtx.hash; - let height = block ? block.height : -1; - let details = new Details(this, wtx, block); - let accounts = new Set(); + const tx = wtx.tx; + const hash = wtx.hash; + const height = block ? block.height : -1; + const details = new Details(this, wtx, block); + const accounts = new Set(); if (!tx.isCoinbase()) { // We need to undo every part of the // state this transaction ever touched. // Start by getting the undo coins. - let credits = await this.getSpentCredits(tx); + const credits = await this.getSpentCredits(tx); for (let i = 0; i < tx.inputs.length; i++) { - let credit = credits[i]; + const credit = credits[i]; let coin, path; if (!credit) { @@ -1207,8 +1207,8 @@ TXDB.prototype.erase = async function erase(wtx, block) { // We need to remove all credits // this transaction created. for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let path = await this.getPath(output); + const output = tx.outputs[i]; + const path = await this.getPath(output); let credit; if (!path) @@ -1242,7 +1242,7 @@ TXDB.prototype.erase = async function erase(wtx, block) { this.del(layout.h(height, hash)); // Remove all secondary indexing. - for (let account of accounts) { + for (const account of accounts) { this.del(layout.T(account, hash)); this.del(layout.M(account, wtx.mtime, hash)); @@ -1279,12 +1279,12 @@ TXDB.prototype.erase = async function erase(wtx, block) { */ TXDB.prototype.removeRecursive = async function removeRecursive(wtx) { - let tx = wtx.tx; - let hash = wtx.hash; + const tx = wtx.tx; + const hash = wtx.hash; let details; for (let i = 0; i < tx.outputs.length; i++) { - let spent = await this.getSpent(hash, i); + const spent = await this.getSpent(hash, i); let stx; if (!spent) @@ -1341,7 +1341,7 @@ TXDB.prototype.unconfirm = async function unconfirm(hash) { */ TXDB.prototype._unconfirm = async function unconfirm(hash) { - let wtx = await this.getTX(hash); + const wtx = await this.getTX(hash); if (!wtx) return; @@ -1359,11 +1359,11 @@ TXDB.prototype._unconfirm = async function unconfirm(hash) { */ TXDB.prototype.disconnect = async function disconnect(wtx, block) { - let tx = wtx.tx; - let hash = wtx.hash; - let height = block.height; - let details = new Details(this, wtx, block); - let accounts = new Set(); + const tx = wtx.tx; + const hash = wtx.hash; + const height = block.height; + const details = new Details(this, wtx, block); + const accounts = new Set(); assert(block); @@ -1373,10 +1373,10 @@ TXDB.prototype.disconnect = async function disconnect(wtx, block) { // We need to reconnect the coins. Start // by getting all of the undo coins we know // about. - let credits = await this.getSpentCredits(tx); + const credits = await this.getSpentCredits(tx); for (let i = 0; i < tx.inputs.length; i++) { - let credit = credits[i]; + const credit = credits[i]; let path, coin; if (!credit) @@ -1404,8 +1404,8 @@ TXDB.prototype.disconnect = async function disconnect(wtx, block) { // We need to remove heights on // the credits and undo coins. for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let path = await this.getPath(output); + const output = tx.outputs[i]; + const path = await this.getPath(output); let credit, coin; if (!path) @@ -1446,7 +1446,7 @@ TXDB.prototype.disconnect = async function disconnect(wtx, block) { this.del(layout.h(height, hash)); // Secondary indexing also needs to change. - for (let account of accounts) { + for (const account of accounts) { this.put(layout.P(account, hash), null); this.del(layout.H(account, height, hash)); } @@ -1474,7 +1474,7 @@ TXDB.prototype.disconnect = async function disconnect(wtx, block) { */ TXDB.prototype.removeConflict = async function removeConflict(wtx) { - let tx = wtx.tx; + const tx = wtx.tx; let details; this.logger.warning('Handling conflicting tx: %s.', tx.txid()); @@ -1502,16 +1502,16 @@ TXDB.prototype.removeConflict = async function removeConflict(wtx) { */ TXDB.prototype.removeConflicts = async function removeConflicts(tx, conf) { - let hash = tx.hash('hex'); - let spends = []; + const hash = tx.hash('hex'); + const spends = []; if (tx.isCoinbase()) return true; // Gather all spent records first. for (let i = 0; i < tx.inputs.length; i++) { - let input = tx.inputs[i]; - let prevout = input.prevout; + const input = tx.inputs[i]; + const prevout = input.prevout; let spent, spender, block; // Is it already spent? @@ -1537,7 +1537,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 (let spender of spends) { + for (const spender of spends) { if (!spender) continue; @@ -1558,7 +1558,7 @@ TXDB.prototype.removeConflicts = async function removeConflicts(tx, conf) { */ TXDB.prototype.verifyInput = async function verifyInput(tx, index, coin) { - let flags = Script.flags.MANDATORY_VERIFY_FLAGS; + const flags = Script.flags.MANDATORY_VERIFY_FLAGS; if (!this.options.verify) return true; return await tx.verifyInputAsync(index, coin, flags); @@ -1573,7 +1573,7 @@ TXDB.prototype.lockTX = function lockTX(tx) { if (tx.isCoinbase()) return; - for (let input of tx.inputs) + for (const input of tx.inputs) this.lockCoin(input.prevout); }; @@ -1586,7 +1586,7 @@ TXDB.prototype.unlockTX = function unlockTX(tx) { if (tx.isCoinbase()) return; - for (let input of tx.inputs) + for (const input of tx.inputs) this.unlockCoin(input.prevout); }; @@ -1596,7 +1596,7 @@ TXDB.prototype.unlockTX = function unlockTX(tx) { */ TXDB.prototype.lockCoin = function lockCoin(coin) { - let key = coin.toKey(); + const key = coin.toKey(); this.locked.add(key); }; @@ -1606,7 +1606,7 @@ TXDB.prototype.lockCoin = function lockCoin(coin) { */ TXDB.prototype.unlockCoin = function unlockCoin(coin) { - let key = coin.toKey(); + const key = coin.toKey(); return this.locked.delete(key); }; @@ -1616,7 +1616,7 @@ TXDB.prototype.unlockCoin = function unlockCoin(coin) { */ TXDB.prototype.isLocked = function isLocked(coin) { - let key = coin.toKey(); + const key = coin.toKey(); return this.locked.has(key); }; @@ -1628,9 +1628,9 @@ TXDB.prototype.isLocked = function isLocked(coin) { */ TXDB.prototype.filterLocked = function filterLocked(coins) { - let out = []; + const out = []; - for (let coin of coins) { + for (const coin of coins) { if (!this.isLocked(coin)) out.push(coin); } @@ -1644,9 +1644,9 @@ TXDB.prototype.filterLocked = function filterLocked(coins) { */ TXDB.prototype.getLocked = function getLocked() { - let outpoints = []; + const outpoints = []; - for (let key of this.locked.keys()) + for (const key of this.locked.keys()) outpoints.push(Outpoint.fromKey(key)); return outpoints; @@ -1663,7 +1663,7 @@ TXDB.prototype.getAccountHistoryHashes = function getHistoryHashes(account) { gte: layout.T(account, encoding.NULL_HASH), lte: layout.T(account, encoding.HIGH_HASH), parse: (key) => { - let [, hash] = layout.Tt(key); + const [, hash] = layout.Tt(key); return hash; } }); @@ -1697,7 +1697,7 @@ TXDB.prototype.getAccountPendingHashes = function getAccountPendingHashes(accoun gte: layout.P(account, encoding.NULL_HASH), lte: layout.P(account, encoding.HIGH_HASH), parse: (key) => { - let [, hash] = layout.Pp(key); + const [, hash] = layout.Pp(key); return hash; } }); @@ -1731,7 +1731,7 @@ TXDB.prototype.getAccountOutpoints = function getAccountOutpoints(account) { gte: layout.C(account, encoding.NULL_HASH, 0), lte: layout.C(account, encoding.HIGH_HASH, 0xffffffff), parse: (key) => { - let [, hash, index] = layout.Cc(key); + const [, hash, index] = layout.Cc(key); return new Outpoint(hash, index); } }); @@ -1751,7 +1751,7 @@ TXDB.prototype.getOutpoints = function getOutpoints(account) { gte: layout.c(encoding.NULL_HASH, 0), lte: layout.c(encoding.HIGH_HASH, 0xffffffff), parse: (key) => { - let [hash, index] = layout.cc(key); + const [hash, index] = layout.cc(key); return new Outpoint(hash, index); } }); @@ -1769,8 +1769,8 @@ TXDB.prototype.getOutpoints = function getOutpoints(account) { */ TXDB.prototype.getAccountHeightRangeHashes = function getAccountHeightRangeHashes(account, options) { - let start = options.start || 0; - let end = options.end || 0xffffffff; + const start = options.start || 0; + const end = options.end || 0xffffffff; return this.keys({ gte: layout.H(account, start, encoding.NULL_HASH), @@ -1778,7 +1778,7 @@ TXDB.prototype.getAccountHeightRangeHashes = function getAccountHeightRangeHashe limit: options.limit, reverse: options.reverse, parse: (key) => { - let [,, hash] = layout.Hh(key); + const [,, hash] = layout.Hh(key); return hash; } }); @@ -1815,7 +1815,7 @@ TXDB.prototype.getHeightRangeHashes = function getHeightRangeHashes(account, opt limit: options.limit, reverse: options.reverse, parse: (key) => { - let [, hash] = layout.hh(key); + const [, hash] = layout.hh(key); return hash; } }); @@ -1843,8 +1843,8 @@ TXDB.prototype.getHeightHashes = function getHeightHashes(height) { */ TXDB.prototype.getAccountRangeHashes = function getAccountRangeHashes(account, options) { - let start = options.start || 0; - let end = options.end || 0xffffffff; + const start = options.start || 0; + const end = options.end || 0xffffffff; return this.keys({ gte: layout.M(account, start, encoding.NULL_HASH), @@ -1852,7 +1852,7 @@ TXDB.prototype.getAccountRangeHashes = function getAccountRangeHashes(account, o limit: options.limit, reverse: options.reverse, parse: (key) => { - let [,, hash] = layout.Mm(key); + const [,, hash] = layout.Mm(key); return hash; } }); @@ -1889,7 +1889,7 @@ TXDB.prototype.getRangeHashes = function getRangeHashes(account, options) { limit: options.limit, reverse: options.reverse, parse: (key) => { - let [, hash] = layout.mm(key); + const [, hash] = layout.mm(key); return hash; } }); @@ -1907,7 +1907,7 @@ TXDB.prototype.getRangeHashes = function getRangeHashes(account, options) { */ TXDB.prototype.getRange = async function getRange(account, options) { - let txs = []; + const txs = []; let hashes; if (account && typeof account === 'object') { @@ -1917,8 +1917,8 @@ TXDB.prototype.getRange = async function getRange(account, options) { hashes = await this.getRangeHashes(account, options); - for (let hash of hashes) { - let tx = await this.getTX(hash); + for (const hash of hashes) { + const tx = await this.getTX(hash); assert(tx); txs.push(tx); } @@ -1968,11 +1968,11 @@ TXDB.prototype.getHistory = function getHistory(account) { */ TXDB.prototype.getAccountHistory = async function getAccountHistory(account) { - let hashes = await this.getHistoryHashes(account); - let txs = []; + const hashes = await this.getHistoryHashes(account); + const txs = []; - for (let hash of hashes) { - let tx = await this.getTX(hash); + for (const hash of hashes) { + const tx = await this.getTX(hash); assert(tx); txs.push(tx); } @@ -1987,11 +1987,11 @@ TXDB.prototype.getAccountHistory = async function getAccountHistory(account) { */ TXDB.prototype.getPending = async function getPending(account) { - let hashes = await this.getPendingHashes(account); - let txs = []; + const hashes = await this.getPendingHashes(account); + const txs = []; - for (let hash of hashes) { - let tx = await this.getTX(hash); + for (const hash of hashes) { + const tx = await this.getTX(hash); assert(tx); txs.push(tx); } @@ -2015,9 +2015,9 @@ TXDB.prototype.getCredits = function getCredits(account) { gte: layout.c(encoding.NULL_HASH, 0x00000000), lte: layout.c(encoding.HIGH_HASH, 0xffffffff), parse: (key, value) => { - let [hash, index] = layout.cc(key); - let credit = Credit.fromRaw(value); - let ckey = Outpoint.toKey(hash, index); + const [hash, index] = layout.cc(key); + const credit = Credit.fromRaw(value); + const ckey = Outpoint.toKey(hash, index); credit.coin.hash = hash; credit.coin.index = index; this.coinCache.set(ckey, value); @@ -2033,11 +2033,11 @@ TXDB.prototype.getCredits = function getCredits(account) { */ TXDB.prototype.getAccountCredits = async function getAccountCredits(account) { - let outpoints = await this.getOutpoints(account); - let credits = []; + const outpoints = await this.getOutpoints(account); + const credits = []; - for (let prevout of outpoints) { - let credit = await this.getCredit(prevout.hash, prevout.index); + for (const prevout of outpoints) { + const credit = await this.getCredit(prevout.hash, prevout.index); assert(credit); credits.push(credit); } @@ -2052,7 +2052,7 @@ TXDB.prototype.getAccountCredits = async function getAccountCredits(account) { */ TXDB.prototype.getSpentCredits = async function getSpentCredits(tx) { - let credits = []; + const credits = []; let hash; for (let i = 0; i < tx.inputs.length; i++) @@ -2067,9 +2067,9 @@ TXDB.prototype.getSpentCredits = async function getSpentCredits(tx) { gte: layout.d(hash, 0x00000000), lte: layout.d(hash, 0xffffffff), parse: (key, value) => { - let [, index] = layout.dd(key); - let coin = Coin.fromRaw(value); - let input = tx.inputs[index]; + const [, index] = layout.dd(key); + const coin = Coin.fromRaw(value); + const input = tx.inputs[index]; assert(input); coin.hash = input.prevout.hash; coin.index = input.prevout.index; @@ -2087,10 +2087,10 @@ TXDB.prototype.getSpentCredits = async function getSpentCredits(tx) { */ TXDB.prototype.getCoins = async function getCoins(account) { - let credits = await this.getCredits(account); - let coins = []; + const credits = await this.getCredits(account); + const coins = []; - for (let credit of credits) { + for (const credit of credits) { if (credit.spent) continue; @@ -2107,10 +2107,10 @@ TXDB.prototype.getCoins = async function getCoins(account) { */ TXDB.prototype.getAccountCoins = async function getAccountCoins(account) { - let credits = await this.getAccountCredits(account); - let coins = []; + const credits = await this.getAccountCredits(account); + const coins = []; - for (let credit of credits) { + for (const credit of credits) { if (credit.spent) continue; @@ -2127,7 +2127,7 @@ TXDB.prototype.getAccountCoins = async function getAccountCoins(account) { */ TXDB.prototype.getSpentCoins = async function getSpentCoins(tx) { - let coins = []; + const coins = []; let credits; if (tx.isCoinbase()) @@ -2135,7 +2135,7 @@ TXDB.prototype.getSpentCoins = async function getSpentCoins(tx) { credits = await this.getSpentCredits(tx); - for (let credit of credits) { + for (const credit of credits) { if (!credit) { coins.push(null); continue; @@ -2154,14 +2154,14 @@ TXDB.prototype.getSpentCoins = async function getSpentCoins(tx) { */ TXDB.prototype.getCoinView = async function getCoinView(tx) { - let view = new CoinView(); + const view = new CoinView(); if (tx.isCoinbase()) return view; - for (let input of tx.inputs) { - let prevout = input.prevout; - let coin = await this.getCoin(prevout.hash, prevout.index); + for (const input of tx.inputs) { + const prevout = input.prevout; + const coin = await this.getCoin(prevout.hash, prevout.index); if (!coin) continue; @@ -2179,7 +2179,7 @@ TXDB.prototype.getCoinView = async function getCoinView(tx) { */ TXDB.prototype.getSpentView = async function getSpentView(tx) { - let view = new CoinView(); + const view = new CoinView(); let coins; if (tx.isCoinbase()) @@ -2187,7 +2187,7 @@ TXDB.prototype.getSpentView = async function getSpentView(tx) { coins = await this.getSpentCoins(tx); - for (let coin of coins) { + for (const coin of coins) { if (!coin) continue; @@ -2203,7 +2203,7 @@ TXDB.prototype.getSpentView = async function getSpentView(tx) { */ TXDB.prototype.getState = async function getState() { - let data = await this.get(layout.R); + const data = await this.get(layout.R); if (!data) return; @@ -2218,7 +2218,7 @@ TXDB.prototype.getState = async function getState() { */ TXDB.prototype.getTX = async function getTX(hash) { - let raw = await this.get(layout.t(hash)); + const raw = await this.get(layout.t(hash)); if (!raw) return; @@ -2233,7 +2233,7 @@ TXDB.prototype.getTX = async function getTX(hash) { */ TXDB.prototype.getDetails = async function getDetails(hash) { - let wtx = await this.getTX(hash); + const wtx = await this.getTX(hash); if (!wtx) return; @@ -2248,13 +2248,13 @@ TXDB.prototype.getDetails = async function getDetails(hash) { */ TXDB.prototype.toDetails = async function toDetails(wtxs) { - let out = []; + const out = []; if (!Array.isArray(wtxs)) return await this._toDetails(wtxs); - for (let wtx of wtxs) { - let details = await this._toDetails(wtx); + for (const wtx of wtxs) { + const details = await this._toDetails(wtx); if (!details) continue; @@ -2273,13 +2273,13 @@ TXDB.prototype.toDetails = async function toDetails(wtxs) { */ TXDB.prototype._toDetails = async function _toDetails(wtx) { - let tx = wtx.tx; - let block = wtx.getBlock(); - let details = new Details(this, wtx, block); - let coins = await this.getSpentCoins(tx); + const tx = wtx.tx; + const block = wtx.getBlock(); + const details = new Details(this, wtx, block); + const coins = await this.getSpentCoins(tx); for (let i = 0; i < tx.inputs.length; i++) { - let coin = coins[i]; + const coin = coins[i]; let path = null; if (coin) @@ -2289,8 +2289,8 @@ TXDB.prototype._toDetails = async function _toDetails(wtx) { } for (let i = 0; i < tx.outputs.length; i++) { - let output = tx.outputs[i]; - let path = await this.getPath(output); + const output = tx.outputs[i]; + const path = await this.getPath(output); details.setOutput(i, path); } @@ -2315,7 +2315,7 @@ TXDB.prototype.hasTX = function hasTX(hash) { */ TXDB.prototype.getCoin = async function getCoin(hash, index) { - let credit = await this.getCredit(hash, index); + const credit = await this.getCredit(hash, index); if (!credit) return; @@ -2331,8 +2331,8 @@ TXDB.prototype.getCoin = async function getCoin(hash, index) { */ TXDB.prototype.getCredit = async function getCredit(hash, index) { - let state = this.state; - let key = Outpoint.toKey(hash, index); + const state = this.state; + const key = Outpoint.toKey(hash, index); let data = this.coinCache.get(key); let credit; @@ -2366,7 +2366,7 @@ TXDB.prototype.getCredit = async function getCredit(hash, index) { */ TXDB.prototype.getSpentCoin = async function getSpentCoin(spent, prevout) { - let data = await this.get(layout.d(spent.hash, spent.index)); + const data = await this.get(layout.d(spent.hash, spent.index)); let coin; if (!data) @@ -2398,8 +2398,8 @@ TXDB.prototype.hasSpentCoin = function hasSpentCoin(spent) { */ TXDB.prototype.updateSpentCoin = async function updateSpentCoin(tx, index, height) { - let prevout = Outpoint.fromTX(tx, index); - let spent = await this.getSpent(prevout.hash, prevout.index); + const prevout = Outpoint.fromTX(tx, index); + const spent = await this.getSpent(prevout.hash, prevout.index); let coin; if (!spent) @@ -2422,7 +2422,7 @@ TXDB.prototype.updateSpentCoin = async function updateSpentCoin(tx, index, heigh */ TXDB.prototype.hasCoin = function hasCoin(hash, index) { - let key = Outpoint.toKey(hash, index); + const key = Outpoint.toKey(hash, index); if (this.coinCache.has(key)) return Promise.resolve(true); @@ -2452,11 +2452,11 @@ TXDB.prototype.getBalance = async function getBalance(account) { */ TXDB.prototype.getWalletBalance = async function getWalletBalance() { - let credits = await this.getCredits(); - let balance = new Balance(this.wallet.wid, this.wallet.id, -1); + const credits = await this.getCredits(); + const balance = new Balance(this.wallet.wid, this.wallet.id, -1); - for (let credit of credits) { - let coin = credit.coin; + for (const credit of credits) { + const coin = credit.coin; if (coin.height !== -1) balance.confirmed += coin.value; @@ -2475,11 +2475,11 @@ TXDB.prototype.getWalletBalance = async function getWalletBalance() { */ TXDB.prototype.getAccountBalance = async function getAccountBalance(account) { - let credits = await this.getAccountCredits(account); - let balance = new Balance(this.wallet.wid, this.wallet.id, account); + const credits = await this.getAccountCredits(account); + const balance = new Balance(this.wallet.wid, this.wallet.id, account); - for (let credit of credits) { - let coin = credit.coin; + for (const credit of credits) { + const coin = credit.coin; if (coin.height !== -1) balance.confirmed += coin.value; @@ -2499,8 +2499,8 @@ TXDB.prototype.getAccountBalance = async function getAccountBalance(account) { */ TXDB.prototype.zap = async function zap(account, age) { - let hashes = []; - let now = util.now(); + const hashes = []; + const now = util.now(); let txs; assert(util.isUInt32(age)); @@ -2510,7 +2510,7 @@ TXDB.prototype.zap = async function zap(account, age) { end: now - age }); - for (let wtx of txs) { + for (const wtx of txs) { if (wtx.height !== -1) continue; @@ -2534,7 +2534,7 @@ TXDB.prototype.zap = async function zap(account, age) { */ TXDB.prototype.abandon = async function abandon(hash) { - let result = await this.has(layout.p(hash)); + const result = await this.has(layout.p(hash)); if (!result) throw new Error('TX not eligible.'); @@ -2635,7 +2635,7 @@ function TXDBState(wid, id) { */ TXDBState.prototype.clone = function clone() { - let state = new TXDBState(this.wid, this.id); + const state = new TXDBState(this.wid, this.id); state.tx = this.tx; state.coin = this.coin; state.unconfirmed = this.unconfirmed; @@ -2659,7 +2659,7 @@ TXDBState.prototype.commit = function commit() { */ TXDBState.prototype.toBalance = function toBalance() { - let balance = new Balance(this.wid, this.id, -1); + const balance = new Balance(this.wid, this.id, -1); balance.unconfirmed = this.unconfirmed; balance.confirmed = this.confirmed; return balance; @@ -2671,7 +2671,7 @@ TXDBState.prototype.toBalance = function toBalance() { */ TXDBState.prototype.toRaw = function toRaw() { - let bw = new StaticWriter(32); + const bw = new StaticWriter(32); bw.writeU64(this.tx); bw.writeU64(this.coin); @@ -2689,7 +2689,7 @@ TXDBState.prototype.toRaw = function toRaw() { */ TXDBState.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.tx = br.readU53(); this.coin = br.readU53(); this.unconfirmed = br.readU53(); @@ -2759,7 +2759,7 @@ function Credit(coin, spent) { */ Credit.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); this.coin.fromReader(br); this.spent = br.readU8() === 1; this.own = true; @@ -2796,8 +2796,8 @@ Credit.prototype.getSize = function getSize() { */ Credit.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); this.coin.toWriter(bw); bw.writeU8(this.spent ? 1 : 0); bw.writeU8(this.own ? 1 : 0); @@ -2877,14 +2877,14 @@ function Details(txdb, wtx, block) { */ Details.prototype.init = function init() { - for (let input of this.tx.inputs) { - let member = new DetailsMember(); + for (const input of this.tx.inputs) { + const member = new DetailsMember(); member.address = input.getAddress(); this.inputs.push(member); } - for (let output of this.tx.outputs) { - let member = new DetailsMember(); + for (const output of this.tx.outputs) { + const member = new DetailsMember(); member.value = output.value; member.address = output.getAddress(); this.outputs.push(member); @@ -2899,7 +2899,7 @@ Details.prototype.init = function init() { */ Details.prototype.setInput = function setInput(i, path, coin) { - let member = this.inputs[i]; + const member = this.inputs[i]; if (coin) { member.value = coin.value; @@ -2917,7 +2917,7 @@ Details.prototype.setInput = function setInput(i, path, coin) { */ Details.prototype.setOutput = function setOutput(i, path) { - let member = this.outputs[i]; + const member = this.outputs[i]; if (path) member.path = path; @@ -2952,14 +2952,14 @@ Details.prototype.getFee = function getFee() { let inputValue = 0; let outputValue = 0; - for (let input of this.inputs) { + for (const input of this.inputs) { if (!input.path) return 0; inputValue += input.value; } - for (let output of this.outputs) + for (const output of this.outputs) outputValue += output.value; return inputValue - outputValue; @@ -2982,7 +2982,7 @@ Details.prototype.getRate = function getRate(fee) { */ Details.prototype.toJSON = function toJSON() { - let fee = this.getFee(); + const fee = this.getFee(); let rate = this.getRate(fee); // Rate can exceed 53 bits in testing. @@ -3130,7 +3130,7 @@ BlockRecord.prototype.remove = function remove(hash) { */ BlockRecord.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); + const br = new BufferReader(data); let count; this.hash = br.readHash('hex'); @@ -3140,7 +3140,7 @@ BlockRecord.prototype.fromRaw = function fromRaw(data) { count = br.readU32(); for (let i = 0; i < count; i++) { - let hash = br.readHash('hex'); + const hash = br.readHash('hex'); this.index.add(hash); this.hashes.push(hash); } @@ -3173,8 +3173,8 @@ BlockRecord.prototype.getSize = function getSize() { */ BlockRecord.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeHash(this.hash); bw.writeU32(this.height); @@ -3182,7 +3182,7 @@ BlockRecord.prototype.toRaw = function toRaw() { bw.writeU32(this.hashes.length); - for (let hash of this.hashes) + for (const hash of this.hashes) bw.writeHash(hash); return bw.render(); diff --git a/lib/wallet/wallet.js b/lib/wallet/wallet.js index ee4962f93..43af27462 100644 --- a/lib/wallet/wallet.js +++ b/lib/wallet/wallet.js @@ -191,7 +191,7 @@ Wallet.fromOptions = function fromOptions(db, options) { */ Wallet.prototype.init = async function init(options) { - let passphrase = options.passphrase; + const passphrase = options.passphrase; let account; assert(!this.initialized); @@ -238,8 +238,8 @@ Wallet.prototype.open = async function open() { */ Wallet.prototype.destroy = async function destroy() { - let unlock1 = await this.writeLock.lock(); - let unlock2 = await this.fundLock.lock(); + const unlock1 = await this.writeLock.lock(); + const unlock2 = await this.fundLock.lock(); try { this.db.unregister(this); await this.master.destroy(); @@ -261,7 +261,7 @@ Wallet.prototype.destroy = async function destroy() { */ Wallet.prototype.addSharedKey = async function addSharedKey(acct, key) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._addSharedKey(acct, key); } finally { @@ -315,7 +315,7 @@ Wallet.prototype._addSharedKey = async function addSharedKey(acct, key) { */ Wallet.prototype.removeSharedKey = async function removeSharedKey(acct, key) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._removeSharedKey(acct, key); } finally { @@ -388,7 +388,7 @@ Wallet.prototype.setPassphrase = async function setPassphrase(old, new_) { */ Wallet.prototype.encrypt = async function encrypt(passphrase) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._encrypt(passphrase); } finally { @@ -404,7 +404,7 @@ Wallet.prototype.encrypt = async function encrypt(passphrase) { */ Wallet.prototype._encrypt = async function encrypt(passphrase) { - let key = await this.master.encrypt(passphrase, true); + const key = await this.master.encrypt(passphrase, true); this.start(); @@ -430,7 +430,7 @@ Wallet.prototype._encrypt = async function encrypt(passphrase) { */ Wallet.prototype.decrypt = async function decrypt(passphrase) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._decrypt(passphrase); } finally { @@ -446,7 +446,7 @@ Wallet.prototype.decrypt = async function decrypt(passphrase) { */ Wallet.prototype._decrypt = async function decrypt(passphrase) { - let key = await this.master.decrypt(passphrase, true); + const key = await this.master.decrypt(passphrase, true); this.start(); @@ -472,7 +472,7 @@ Wallet.prototype._decrypt = async function decrypt(passphrase) { */ Wallet.prototype.retoken = async function retoken(passphrase) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._retoken(passphrase); } finally { @@ -508,7 +508,7 @@ Wallet.prototype._retoken = async function retoken(passphrase) { */ Wallet.prototype.rename = async function rename(id) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this.db.rename(this, id); } finally { @@ -524,7 +524,7 @@ Wallet.prototype.rename = async function rename(id) { */ Wallet.prototype.renameAccount = async function renameAccount(acct, name) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._renameAccount(acct, name); } finally { @@ -569,7 +569,7 @@ Wallet.prototype._renameAccount = async function _renameAccount(acct, name) { paths = this.pathCache.values(); - for (let path of paths) { + for (const path of paths) { if (path.account !== account.accountIndex) continue; @@ -582,8 +582,8 @@ Wallet.prototype._renameAccount = async function _renameAccount(acct, name) { */ Wallet.prototype.lock = async function lock() { - let unlock1 = await this.writeLock.lock(); - let unlock2 = await this.fundLock.lock(); + const unlock1 = await this.writeLock.lock(); + const unlock2 = await this.fundLock.lock(); try { await this.master.lock(); } finally { @@ -664,7 +664,7 @@ Wallet.prototype.getToken = function getToken(nonce) { */ Wallet.prototype.createAccount = async function createAccount(options, passphrase) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._createAccount(options, passphrase); } finally { @@ -754,8 +754,8 @@ Wallet.prototype._createAccount = async function createAccount(options, passphra */ Wallet.prototype.ensureAccount = async function ensureAccount(options, passphrase) { - let name = options.name; - let account = await this.getAccount(name); + const name = options.name; + const account = await this.getAccount(name); if (account) return account; @@ -791,7 +791,7 @@ Wallet.prototype.getAddressHashes = function getAddressHashes(acct) { */ Wallet.prototype.getAccountHashes = async function getAccountHashes(acct) { - let index = await this.ensureIndex(acct, true); + const index = await this.ensureIndex(acct, true); return await this.db.getAccountHashes(this.wid, index); }; @@ -911,7 +911,7 @@ Wallet.prototype.getAccountName = async function getAccountName(index) { */ Wallet.prototype.hasAccount = async function hasAccount(acct) { - let index = await this.getAccountIndex(acct); + const index = await this.getAccountIndex(acct); if (index === -1) return false; @@ -960,7 +960,7 @@ Wallet.prototype.createNested = function createNested(acct) { */ Wallet.prototype.createKey = async function createKey(acct, branch) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._createKey(acct, branch); } finally { @@ -1059,8 +1059,8 @@ Wallet.prototype.commit = function commit() { */ Wallet.prototype.hasAddress = async function hasAddress(address) { - let hash = Address.getHash(address, 'hex'); - let path = await this.getPath(hash); + const hash = Address.getHash(address, 'hex'); + const path = await this.getPath(hash); return path != null; }; @@ -1071,7 +1071,7 @@ Wallet.prototype.hasAddress = async function hasAddress(address) { */ Wallet.prototype.getPath = async function getPath(address) { - let path = await this.readPath(address); + const path = await this.readPath(address); if (!path) return; @@ -1093,7 +1093,7 @@ Wallet.prototype.getPath = async function getPath(address) { */ Wallet.prototype.readPath = async function readPath(address) { - let hash = Address.getHash(address, 'hex'); + const hash = Address.getHash(address, 'hex'); let path = this.pathCache.get(hash); if (path) @@ -1116,7 +1116,7 @@ Wallet.prototype.readPath = async function readPath(address) { */ Wallet.prototype.hasPath = async function hasPath(address) { - let hash = Address.getHash(address, 'hex'); + const hash = Address.getHash(address, 'hex'); if (this.pathCache.has(hash)) return true; @@ -1139,7 +1139,7 @@ Wallet.prototype.getPaths = async function getPaths(acct) { paths = await this.db.getWalletPaths(this.wid); result = []; - for (let path of paths) { + for (const path of paths) { path.id = this.id; path.name = await this.getAccountName(path.account); @@ -1160,15 +1160,15 @@ Wallet.prototype.getPaths = async function getPaths(acct) { */ Wallet.prototype.getAccountPaths = async function getAccountPaths(acct) { - let index = await this.ensureIndex(acct, true); - let hashes = await this.getAccountHashes(index); - let name = await this.getAccountName(acct); - let result = []; + const index = await this.ensureIndex(acct, true); + const hashes = await this.getAccountHashes(index); + const name = await this.getAccountName(acct); + const result = []; assert(name); - for (let hash of hashes) { - let path = await this.readPath(hash); + for (const hash of hashes) { + const path = await this.readPath(hash); assert(path); assert(path.account === index); @@ -1193,7 +1193,7 @@ Wallet.prototype.getAccountPaths = async function getAccountPaths(acct) { */ Wallet.prototype.importKey = async function importKey(acct, ring, passphrase) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._importKey(acct, ring, passphrase); } finally { @@ -1279,7 +1279,7 @@ Wallet.prototype._importKey = async function importKey(acct, ring, passphrase) { */ Wallet.prototype.importAddress = async function importAddress(acct, address) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._importAddress(acct, address); } finally { @@ -1365,7 +1365,7 @@ Wallet.prototype._importAddress = async function importAddress(acct, address) { */ Wallet.prototype.fund = async function fund(mtx, options, force) { - let unlock = await this.fundLock.lock(force); + const unlock = await this.fundLock.lock(force); try { return await this._fund(mtx, options); } finally { @@ -1438,8 +1438,8 @@ Wallet.prototype._fund = async function fund(mtx, options) { */ Wallet.prototype.getAccountByAddress = async function getAccountByAddress(address) { - let hash = Address.getHash(address, 'hex'); - let path = await this.getPath(hash); + const hash = Address.getHash(address, 'hex'); + const path = await this.getPath(hash); if (!path) return; @@ -1454,8 +1454,8 @@ Wallet.prototype.getAccountByAddress = async function getAccountByAddress(addres */ Wallet.prototype.estimateSize = async function estimateSize(prev) { - let scale = consensus.WITNESS_SCALE_FACTOR; - let address = prev.getAddress(); + const scale = consensus.WITNESS_SCALE_FACTOR; + const address = prev.getAddress(); let size = 0; let account; @@ -1535,8 +1535,8 @@ Wallet.prototype.estimateSize = async function estimateSize(prev) { */ Wallet.prototype.createTX = async function createTX(options, force) { - let outputs = options.outputs; - let mtx = new MTX(); + const outputs = options.outputs; + const mtx = new MTX(); let addr, total; assert(Array.isArray(outputs), 'Outputs must be an array.'); @@ -1595,7 +1595,7 @@ Wallet.prototype.createTX = async function createTX(options, force) { */ Wallet.prototype.send = async function send(options, passphrase) { - let unlock = await this.fundLock.lock(); + const unlock = await this.fundLock.lock(); try { return await this._send(options, passphrase); } finally { @@ -1612,7 +1612,7 @@ Wallet.prototype.send = async function send(options, passphrase) { */ Wallet.prototype._send = async function send(options, passphrase) { - let mtx = await this.createTX(options, true); + const mtx = await this.createTX(options, true); let tx; await this.sign(mtx, passphrase); @@ -1648,7 +1648,7 @@ Wallet.prototype._send = async function send(options, passphrase) { */ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase) { - let wtx = await this.getTX(hash); + const wtx = await this.getTX(hash); let tx, mtx, view, oldFee, fee, change; assert(util.isUInt32(rate), 'Rate must be a number.'); @@ -1681,7 +1681,7 @@ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase mtx = MTX.fromTX(tx); mtx.view = view; - for (let input of mtx.inputs) { + for (const input of mtx.inputs) { input.script.length = 0; input.script.compile(); input.witness.length = 0; @@ -1689,8 +1689,8 @@ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase } for (let i = 0; i < mtx.outputs.length; i++) { - let output = mtx.outputs[i]; - let addr = output.getAddress(); + const output = mtx.outputs[i]; + const addr = output.getAddress(); let path; if (!addr) @@ -1749,18 +1749,18 @@ Wallet.prototype.increaseFee = async function increaseFee(hash, rate, passphrase */ Wallet.prototype.resend = async function resend() { - let wtxs = await this.getPending(); + const wtxs = await this.getPending(); let txs = []; if (wtxs.length > 0) this.logger.info('Rebroadcasting %d transactions.', wtxs.length); - for (let wtx of wtxs) + for (const wtx of wtxs) txs.push(wtx.tx); txs = common.sortDeps(txs); - for (let tx of txs) + for (const tx of txs) await this.db.send(tx); return txs; @@ -1774,15 +1774,15 @@ Wallet.prototype.resend = async function resend() { */ Wallet.prototype.deriveInputs = async function deriveInputs(mtx) { - let rings = []; + const rings = []; let paths; assert(mtx.mutable); paths = await this.getInputPaths(mtx); - for (let path of paths) { - let account = await this.getAccount(path.account); + for (const path of paths) { + const account = await this.getAccount(path.account); let ring; if (!account) @@ -1804,8 +1804,8 @@ Wallet.prototype.deriveInputs = async function deriveInputs(mtx) { */ Wallet.prototype.getKey = async function getKey(address) { - let hash = Address.getHash(address, 'hex'); - let path = await this.getPath(hash); + const hash = Address.getHash(address, 'hex'); + const path = await this.getPath(hash); let account; if (!path) @@ -1828,8 +1828,8 @@ Wallet.prototype.getKey = async function getKey(address) { */ Wallet.prototype.getPrivateKey = async function getPrivateKey(address, passphrase) { - let hash = Address.getHash(address, 'hex'); - let path = await this.getPath(hash); + const hash = Address.getHash(address, 'hex'); + const path = await this.getPath(hash); let account, key; if (!path) @@ -1857,7 +1857,7 @@ Wallet.prototype.getPrivateKey = async function getPrivateKey(address, passphras */ Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { - let paths = []; + const paths = []; let hashes; assert(mtx.mutable); @@ -1867,8 +1867,8 @@ Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { hashes = mtx.getInputHashes('hex'); - for (let hash of hashes) { - let path = await this.getPath(hash); + for (const hash of hashes) { + const path = await this.getPath(hash); if (path) paths.push(path); } @@ -1883,11 +1883,11 @@ Wallet.prototype.getInputPaths = async function getInputPaths(mtx) { */ Wallet.prototype.getOutputPaths = async function getOutputPaths(tx) { - let paths = []; - let hashes = tx.getOutputHashes('hex'); + const paths = []; + const hashes = tx.getOutputHashes('hex'); - for (let hash of hashes) { - let path = await this.getPath(hash); + for (const hash of hashes) { + const path = await this.getPath(hash); if (path) paths.push(path); } @@ -1903,7 +1903,7 @@ Wallet.prototype.getOutputPaths = async function getOutputPaths(tx) { */ Wallet.prototype.setLookahead = async function setLookahead(acct, lookahead) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return this._setLookahead(acct, lookahead); } finally { @@ -1956,14 +1956,14 @@ Wallet.prototype._setLookahead = async function setLookahead(acct, lookahead) { */ Wallet.prototype.syncOutputDepth = async function syncOutputDepth(details) { - let map = new Map(); - let derived = []; + const map = new Map(); + const derived = []; if (!details) return derived; - for (let output of details.outputs) { - let path = output.path; + for (const output of details.outputs) { + const path = output.path; if (!path) continue; @@ -1977,13 +1977,13 @@ Wallet.prototype.syncOutputDepth = async function syncOutputDepth(details) { map.get(path.account).push(path); } - for (let [acct, paths] of map) { + for (const [acct, paths] of map) { let receive = -1; let change = -1; let nested = -1; let account, ring; - for (let path of paths) { + for (const path of paths) { switch (path.branch) { case 0: if (path.index > receive) @@ -2046,7 +2046,7 @@ Wallet.prototype.getRedeem = async function getRedeem(hash) { */ Wallet.prototype.template = async function template(mtx) { - let rings = await this.deriveInputs(mtx); + const rings = await this.deriveInputs(mtx); return mtx.template(rings); }; @@ -2159,7 +2159,7 @@ Wallet.prototype.getBlock = function getBlock(height) { */ Wallet.prototype.add = async function add(tx, block) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._add(tx, block); } finally { @@ -2205,7 +2205,7 @@ Wallet.prototype._add = async function add(tx, block) { */ Wallet.prototype.unconfirm = async function unconfirm(hash) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this.txdb.unconfirm(hash); } finally { @@ -2220,7 +2220,7 @@ Wallet.prototype.unconfirm = async function unconfirm(hash) { */ Wallet.prototype.remove = async function remove(hash) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this.txdb.remove(hash); } finally { @@ -2236,7 +2236,7 @@ Wallet.prototype.remove = async function remove(hash) { */ Wallet.prototype.zap = async function zap(acct, age) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._zap(acct, age); } finally { @@ -2253,7 +2253,7 @@ Wallet.prototype.zap = async function zap(acct, age) { */ Wallet.prototype._zap = async function zap(acct, age) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.zap(account, age); }; @@ -2264,7 +2264,7 @@ Wallet.prototype._zap = async function zap(acct, age) { */ Wallet.prototype.abandon = async function abandon(hash) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._abandon(hash); } finally { @@ -2326,7 +2326,7 @@ Wallet.prototype.getLocked = function getLocked() { */ Wallet.prototype.getHistory = async function getHistory(acct) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return this.txdb.getHistory(account); }; @@ -2337,7 +2337,7 @@ Wallet.prototype.getHistory = async function getHistory(acct) { */ Wallet.prototype.getCoins = async function getCoins(acct) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.getCoins(account); }; @@ -2348,7 +2348,7 @@ Wallet.prototype.getCoins = async function getCoins(acct) { */ Wallet.prototype.getCredits = async function getCredits(acct) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.getCredits(account); }; @@ -2359,11 +2359,11 @@ Wallet.prototype.getCredits = async function getCredits(acct) { */ Wallet.prototype.getSmartCoins = async function getSmartCoins(acct) { - let credits = await this.getCredits(acct); - let coins = []; + const credits = await this.getCredits(acct); + const coins = []; - for (let credit of credits) { - let coin = credit.coin; + for (const credit of credits) { + const coin = credit.coin; if (credit.spent) continue; @@ -2398,7 +2398,7 @@ Wallet.prototype.getSmartCoins = async function getSmartCoins(acct) { */ Wallet.prototype.getPending = async function getPending(acct) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.getPending(account); }; @@ -2409,7 +2409,7 @@ Wallet.prototype.getPending = async function getPending(acct) { */ Wallet.prototype.getBalance = async function getBalance(acct) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.getBalance(account); }; @@ -2440,7 +2440,7 @@ Wallet.prototype.getRange = async function getRange(acct, options) { */ Wallet.prototype.getLast = async function getLast(acct, limit) { - let account = await this.ensureIndex(acct); + const account = await this.ensureIndex(acct); return await this.txdb.getLast(account, limit); }; @@ -2572,8 +2572,8 @@ Wallet.prototype.getSize = function getSize() { */ Wallet.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU32(this.network.magic); bw.writeU32(this.wid); @@ -2595,8 +2595,8 @@ Wallet.prototype.toRaw = function toRaw() { */ Wallet.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let network = Network.fromMagic(br.readU32()); + const br = new BufferReader(data); + const network = Network.fromMagic(br.readU32()); this.wid = br.readU32(); this.id = br.readVarString('ascii'); diff --git a/lib/wallet/walletdb.js b/lib/wallet/walletdb.js index aee1e5dde..456b3a4c5 100644 --- a/lib/wallet/walletdb.js +++ b/lib/wallet/walletdb.js @@ -187,7 +187,7 @@ WalletDB.prototype._close = async function close() { if (this.http && this.options.listen) await this.http.close(); - for (let wallet of this.wallets.values()) + for (const wallet of this.wallets.values()) await wallet.destroy(); await this.db.close(); @@ -202,7 +202,7 @@ WalletDB.prototype._close = async function close() { */ WalletDB.prototype.load = async function load() { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { await this.connect(); await this.init(); @@ -306,8 +306,8 @@ WalletDB.prototype.disconnect = async function disconnect() { */ WalletDB.prototype.init = async function init() { - let state = await this.getState(); - let startHeight = this.options.startHeight; + const state = await this.getState(); + const startHeight = this.options.startHeight; let tip; if (state) { @@ -352,13 +352,13 @@ WalletDB.prototype.watch = async function watch() { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; try { - let data = layout.pp(item.key); + const data = layout.pp(item.key); this.filter.add(data, 'hex'); } catch (e) { await iter.end(); @@ -374,15 +374,15 @@ WalletDB.prototype.watch = async function watch() { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; try { - let [hash, index] = layout.oo(item.key); - let outpoint = new Outpoint(hash, index); - let data = outpoint.toRaw(); + const [hash, index] = layout.oo(item.key); + const outpoint = new Outpoint(hash, index); + const data = outpoint.toRaw(); this.filter.add(data); } catch (e) { await iter.end(); @@ -412,7 +412,7 @@ WalletDB.prototype.sync = async function sync() { return; while (height >= 0) { - let tip = await this.getBlock(height); + const tip = await this.getBlock(height); if (!tip) break; @@ -477,7 +477,7 @@ WalletDB.prototype.scan = async function scan(height) { */ WalletDB.prototype.rescan = async function rescan(height) { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { return await this._rescan(height); } finally { @@ -596,7 +596,7 @@ WalletDB.prototype.backup = function backup(path) { */ WalletDB.prototype.wipe = async function wipe() { - let batch = this.db.batch(); + const batch = this.db.batch(); let total = 0; let iter; @@ -609,7 +609,7 @@ WalletDB.prototype.wipe = async function wipe() { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; @@ -696,7 +696,7 @@ WalletDB.prototype.start = function start(wallet) { */ WalletDB.prototype.drop = function drop(wallet) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); wallet.current = null; wallet.accountCache.drop(); wallet.pathCache.drop(); @@ -710,7 +710,7 @@ WalletDB.prototype.drop = function drop(wallet) { */ WalletDB.prototype.clear = function clear(wallet) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); wallet.accountCache.clear(); wallet.pathCache.clear(); batch.clear(); @@ -736,7 +736,7 @@ WalletDB.prototype.batch = function batch(wallet) { */ WalletDB.prototype.commit = async function commit(wallet) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); try { await batch.write(); @@ -782,7 +782,7 @@ WalletDB.prototype.addHash = function addHash(hash) { */ WalletDB.prototype.addOutpoint = function addOutpoint(hash, index) { - let outpoint = new Outpoint(hash, index); + const outpoint = new Outpoint(hash, index); this.filter.add(outpoint.toRaw()); }; @@ -855,7 +855,7 @@ WalletDB.prototype.getWalletID = async function getWalletID(id) { */ WalletDB.prototype.get = async function get(id) { - let wid = await this.getWalletID(id); + const wid = await this.getWalletID(id); let unlock; if (!wid) @@ -904,9 +904,9 @@ WalletDB.prototype._get = async function get(wid) { */ WalletDB.prototype.save = function save(wallet) { - let wid = wallet.wid; - let id = wallet.id; - let batch = this.batch(wallet); + const wid = wallet.wid; + const id = wallet.id; + const batch = this.batch(wallet); this.widCache.set(id, wid); @@ -922,7 +922,7 @@ WalletDB.prototype.save = function save(wallet) { */ WalletDB.prototype.rename = async function rename(wallet, id) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); try { return await this._rename(wallet, id); } finally { @@ -939,7 +939,7 @@ WalletDB.prototype.rename = async function rename(wallet, id) { */ WalletDB.prototype._rename = async function _rename(wallet, id) { - let old = wallet.id; + const old = wallet.id; let paths, batch; if (!common.isName(id)) @@ -961,7 +961,7 @@ WalletDB.prototype._rename = async function _rename(wallet, id) { paths = wallet.pathCache.values(); - for (let path of paths) + for (const path of paths) path.id = id; }; @@ -972,8 +972,8 @@ WalletDB.prototype._rename = async function _rename(wallet, id) { */ WalletDB.prototype.renameAccount = function renameAccount(account, name) { - let wallet = account.wallet; - let batch = this.batch(wallet); + const wallet = account.wallet; + const batch = this.batch(wallet); // Remove old wid/name->account index. batch.del(layout.i(account.wid, account.name)); @@ -991,7 +991,7 @@ WalletDB.prototype.renameAccount = function renameAccount(account, name) { */ WalletDB.prototype.auth = async function auth(wid, token) { - let wallet = await this.get(wid); + const wallet = await this.get(wid); if (!wallet) return; @@ -1016,7 +1016,7 @@ WalletDB.prototype.auth = async function auth(wid, token) { */ WalletDB.prototype.create = async function create(options) { - let unlock = await this.writeLock.lock(); + const unlock = await this.writeLock.lock(); if (!options) options = {}; @@ -1036,7 +1036,7 @@ WalletDB.prototype.create = async function create(options) { */ WalletDB.prototype._create = async function create(options) { - let exists = await this.has(options.id); + const exists = await this.has(options.id); let wallet; if (exists) @@ -1061,7 +1061,7 @@ WalletDB.prototype._create = async function create(options) { */ WalletDB.prototype.has = async function has(id) { - let wid = await this.getWalletID(id); + const wid = await this.getWalletID(id); return wid != null; }; @@ -1072,7 +1072,7 @@ WalletDB.prototype.has = async function has(id) { */ WalletDB.prototype.ensure = async function ensure(options) { - let wallet = await this.get(options.id); + const wallet = await this.get(options.id); if (wallet) return wallet; return await this.create(options); @@ -1087,7 +1087,7 @@ WalletDB.prototype.ensure = async function ensure(options) { */ WalletDB.prototype.getAccount = async function getAccount(wid, index) { - let data = await this.db.get(layout.a(wid, index)); + const data = await this.db.get(layout.a(wid, index)); if (!data) return; @@ -1117,7 +1117,7 @@ WalletDB.prototype.getAccounts = function getAccounts(wid) { */ WalletDB.prototype.getAccountIndex = async function getAccountIndex(wid, name) { - let index = await this.db.get(layout.i(wid, name)); + const index = await this.db.get(layout.i(wid, name)); if (!index) return -1; @@ -1133,7 +1133,7 @@ WalletDB.prototype.getAccountIndex = async function getAccountIndex(wid, name) { */ WalletDB.prototype.getAccountName = async function getAccountName(wid, index) { - let name = await this.db.get(layout.n(wid, index)); + const name = await this.db.get(layout.n(wid, index)); if (!name) return; @@ -1148,11 +1148,11 @@ WalletDB.prototype.getAccountName = async function getAccountName(wid, index) { */ WalletDB.prototype.saveAccount = function saveAccount(account) { - let wid = account.wid; - let wallet = account.wallet; - let index = account.accountIndex; - let name = account.name; - let batch = this.batch(wallet); + const wid = account.wid; + const wallet = account.wallet; + const index = account.accountIndex; + const name = account.name; + const batch = this.batch(wallet); // Account data batch.put(layout.a(wid, index), account.toRaw()); @@ -1228,9 +1228,9 @@ WalletDB.prototype.saveKey = function saveKey(wallet, ring) { */ WalletDB.prototype.savePath = async function savePath(wallet, path) { - let wid = wallet.wid; - let hash = path.hash; - let batch = this.batch(wallet); + const wid = wallet.wid; + const hash = path.hash; + const batch = this.batch(wallet); let map; await this.addHash(hash); @@ -1264,7 +1264,7 @@ WalletDB.prototype.savePath = async function savePath(wallet, path) { */ WalletDB.prototype.getPath = async function getPath(wid, hash) { - let data = await this.db.get(layout.P(wid, hash)); + const data = await this.db.get(layout.P(wid, hash)); let path; if (!data) @@ -1311,7 +1311,7 @@ WalletDB.prototype.getOutpoints = function getOutpoints() { gte: layout.o(encoding.NULL_HASH, 0), lte: layout.o(encoding.HIGH_HASH, 0xffffffff), parse: (key) => { - let [hash, index] = layout.oo(key); + const [hash, index] = layout.oo(key); return new Outpoint(hash, index); } }); @@ -1353,16 +1353,16 @@ WalletDB.prototype.getAccountHashes = function getAccountHashes(wid, account) { */ WalletDB.prototype.getWalletPaths = async function getWalletPaths(wid) { - let paths = []; + const paths = []; - let items = await this.db.range({ + const items = await this.db.range({ gte: layout.P(wid, encoding.NULL_HASH), lte: layout.P(wid, encoding.HIGH_HASH) }); - for (let item of items) { - let hash = layout.Pp(item.key); - let path = Path.fromRaw(item.value); + for (const item of items) { + const hash = layout.Pp(item.key); + const path = Path.fromRaw(item.value); path.hash = hash; path.wid = wid; @@ -1394,9 +1394,9 @@ WalletDB.prototype.getWallets = function getWallets() { */ WalletDB.prototype.encryptKeys = async function encryptKeys(wallet, key) { - let wid = wallet.wid; - let paths = await wallet.getPaths(); - let batch = this.batch(wallet); + const wid = wallet.wid; + const paths = await wallet.getPaths(); + const batch = this.batch(wallet); for (let path of paths) { let iv; @@ -1427,9 +1427,9 @@ WalletDB.prototype.encryptKeys = async function encryptKeys(wallet, key) { */ WalletDB.prototype.decryptKeys = async function decryptKeys(wallet, key) { - let wid = wallet.wid; - let paths = await wallet.getPaths(); - let batch = this.batch(wallet); + const wid = wallet.wid; + const paths = await wallet.getPaths(); + const batch = this.batch(wallet); for (let path of paths) { let iv; @@ -1458,13 +1458,13 @@ WalletDB.prototype.decryptKeys = async function decryptKeys(wallet, key) { */ WalletDB.prototype.resend = async function resend() { - let keys = await this.db.keys({ + const keys = await this.db.keys({ gte: layout.w(0x00000000), lte: layout.w(0xffffffff) }); - for (let key of keys) { - let wid = layout.ww(key); + for (const key of keys) { + const wid = layout.ww(key); await this.resendPending(wid); } }; @@ -1477,7 +1477,7 @@ WalletDB.prototype.resend = async function resend() { */ WalletDB.prototype.resendPending = async function resendPending(wid) { - let layout = layouts.txdb; + const layout = layouts.txdb; let txs = []; let keys; @@ -1494,10 +1494,10 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { keys.length, wid); - for (let key of keys) { - let hash = layout.pp(key); - let tkey = layout.prefix(wid, layout.t(hash)); - let data = await this.db.get(tkey); + for (const key of keys) { + const hash = layout.pp(key); + const tkey = layout.prefix(wid, layout.t(hash)); + const data = await this.db.get(tkey); let wtx; if (!data) @@ -1513,7 +1513,7 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { txs = common.sortDeps(txs); - for (let tx of txs) + for (const tx of txs) await this.send(tx); }; @@ -1524,12 +1524,12 @@ WalletDB.prototype.resendPending = async function resendPending(wid) { */ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { - let hashes = tx.getOutputHashes('hex'); - let result = new Set(); + const hashes = tx.getOutputHashes('hex'); + const result = new Set(); if (!tx.isCoinbase()) { - for (let input of tx.inputs) { - let prevout = input.prevout; + for (const input of tx.inputs) { + const prevout = input.prevout; let map; if (!this.testFilter(prevout.toRaw())) @@ -1540,12 +1540,12 @@ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { if (!map) continue; - for (let wid of map.wids) + for (const wid of map.wids) result.add(wid); } } - for (let hash of hashes) { + for (const hash of hashes) { let map; if (!this.testFilter(hash)) @@ -1556,7 +1556,7 @@ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { if (!map) continue; - for (let wid of map.wids) + for (const wid of map.wids) result.add(wid); } @@ -1572,7 +1572,7 @@ WalletDB.prototype.getWalletsByTX = async function getWalletsByTX(tx) { */ WalletDB.prototype.getState = async function getState() { - let data = await this.db.get(layout.R); + const data = await this.db.get(layout.R); if (!data) return; @@ -1587,8 +1587,8 @@ WalletDB.prototype.getState = async function getState() { */ WalletDB.prototype.resetState = async function resetState(tip, marked) { - let batch = this.db.batch(); - let state = this.state.clone(); + const batch = this.db.batch(); + const state = this.state.clone(); let iter; iter = this.db.iterator({ @@ -1598,7 +1598,7 @@ WalletDB.prototype.resetState = async function resetState(tip, marked) { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; @@ -1631,8 +1631,8 @@ WalletDB.prototype.resetState = async function resetState(tip, marked) { */ WalletDB.prototype.syncState = async function syncState(tip) { - let batch = this.db.batch(); - let state = this.state.clone(); + const batch = this.db.batch(); + const state = this.state.clone(); if (tip.height < state.height) { // Hashes ahead of our new tip @@ -1649,7 +1649,7 @@ WalletDB.prototype.syncState = async function syncState(tip) { } } else if (tip.height > state.height) { // Prune old hashes. - let height = tip.height - this.options.keepBlocks; + const height = tip.height - this.options.keepBlocks; assert(tip.height === state.height + 1, 'Bad chain sync.'); @@ -1691,7 +1691,7 @@ WalletDB.prototype.maybeMark = async function maybeMark(tip) { */ WalletDB.prototype.getBlockMap = async function getBlockMap(height) { - let data = await this.db.get(layout.b(height)); + const data = await this.db.get(layout.b(height)); if (!data) return; @@ -1707,7 +1707,7 @@ WalletDB.prototype.getBlockMap = async function getBlockMap(height) { */ WalletDB.prototype.writeBlockMap = function writeBlockMap(wallet, height, block) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); batch.put(layout.b(height), block.toRaw()); }; @@ -1718,7 +1718,7 @@ WalletDB.prototype.writeBlockMap = function writeBlockMap(wallet, height, block) */ WalletDB.prototype.unwriteBlockMap = function unwriteBlockMap(wallet, height) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); batch.del(layout.b(height)); }; @@ -1730,7 +1730,7 @@ WalletDB.prototype.unwriteBlockMap = function unwriteBlockMap(wallet, height) { */ WalletDB.prototype.getOutpointMap = async function getOutpointMap(hash, index) { - let data = await this.db.get(layout.o(hash, index)); + const data = await this.db.get(layout.o(hash, index)); if (!data) return; @@ -1747,7 +1747,7 @@ WalletDB.prototype.getOutpointMap = async function getOutpointMap(hash, index) { */ WalletDB.prototype.writeOutpointMap = function writeOutpointMap(wallet, hash, index, map) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); this.addOutpoint(hash, index); @@ -1762,7 +1762,7 @@ WalletDB.prototype.writeOutpointMap = function writeOutpointMap(wallet, hash, in */ WalletDB.prototype.unwriteOutpointMap = function unwriteOutpointMap(wallet, hash, index) { - let batch = this.batch(wallet); + const batch = this.batch(wallet); batch.del(layout.o(hash, index)); }; @@ -1773,7 +1773,7 @@ WalletDB.prototype.unwriteOutpointMap = function unwriteOutpointMap(wallet, hash */ WalletDB.prototype.getBlock = async function getBlock(height) { - let data = await this.db.get(layout.h(height)); + const data = await this.db.get(layout.h(height)); let block; if (!data) @@ -1793,7 +1793,7 @@ WalletDB.prototype.getBlock = async function getBlock(height) { */ WalletDB.prototype.getTip = async function getTip() { - let tip = await this.getBlock(this.state.height); + const tip = await this.getBlock(this.state.height); if (!tip) throw new Error('WDB: Tip not found!'); @@ -1872,20 +1872,20 @@ WalletDB.prototype.revert = async function revert(target) { }); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; try { - let height = layout.bb(item.key); - let block = BlockMapRecord.fromRaw(height, item.value); - let txs = block.toArray(); + const height = layout.bb(item.key); + const block = BlockMapRecord.fromRaw(height, item.value); + const txs = block.toArray(); total += txs.length; for (let i = txs.length - 1; i >= 0; i--) { - let tx = txs[i]; + const tx = txs[i]; await this._unconfirm(tx); } } catch (e) { @@ -1904,7 +1904,7 @@ WalletDB.prototype.revert = async function revert(target) { */ WalletDB.prototype.addBlock = async function addBlock(entry, txs) { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { return await this._addBlock(entry, txs); } finally { @@ -1921,7 +1921,7 @@ WalletDB.prototype.addBlock = async function addBlock(entry, txs) { */ WalletDB.prototype._addBlock = async function addBlock(entry, txs) { - let tip = BlockMeta.fromEntry(entry); + const tip = BlockMeta.fromEntry(entry); let total = 0; if (tip.height < this.state.height) { @@ -1951,7 +1951,7 @@ WalletDB.prototype._addBlock = async function addBlock(entry, txs) { return total; } - for (let tx of txs) { + for (const tx of txs) { if (await this._insert(tx, tip)) total++; } @@ -1972,7 +1972,7 @@ WalletDB.prototype._addBlock = async function addBlock(entry, txs) { */ WalletDB.prototype.removeBlock = async function removeBlock(entry) { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { return await this._removeBlock(entry); } finally { @@ -1988,7 +1988,7 @@ WalletDB.prototype.removeBlock = async function removeBlock(entry) { */ WalletDB.prototype._removeBlock = async function removeBlock(entry) { - let tip = BlockMeta.fromEntry(entry); + const tip = BlockMeta.fromEntry(entry); let prev, block, txs; if (tip.height > this.state.height) { @@ -2017,7 +2017,7 @@ WalletDB.prototype._removeBlock = async function removeBlock(entry) { txs = block.toArray(); for (let i = txs.length - 1; i >= 0; i--) { - let tx = txs[i]; + const tx = txs[i]; await this._unconfirm(tx); } @@ -2061,7 +2061,7 @@ WalletDB.prototype.rescanBlock = async function rescanBlock(entry, txs) { */ WalletDB.prototype.addTX = async function addTX(tx) { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { return await this._insert(tx); @@ -2079,7 +2079,7 @@ WalletDB.prototype.addTX = async function addTX(tx) { */ WalletDB.prototype._insert = async function insert(tx, block) { - let wids = await this.getWalletsByTX(tx); + const wids = await this.getWalletsByTX(tx); let result = false; assert(!tx.mutable, 'WDB: Cannot add mutable TX.'); @@ -2098,8 +2098,8 @@ WalletDB.prototype._insert = async function insert(tx, block) { // Insert the transaction // into every matching wallet. - for (let wid of wids) { - let wallet = await this.get(wid); + for (const wid of wids) { + const wallet = await this.get(wid); assert(wallet); @@ -2126,8 +2126,8 @@ WalletDB.prototype._insert = async function insert(tx, block) { */ WalletDB.prototype._unconfirm = async function unconfirm(tx) { - for (let wid of tx.wids) { - let wallet = await this.get(wid); + for (const wid of tx.wids) { + const wallet = await this.get(wid); assert(wallet); await wallet.unconfirm(tx.hash); } @@ -2140,7 +2140,7 @@ WalletDB.prototype._unconfirm = async function unconfirm(tx) { */ WalletDB.prototype.resetChain = async function resetChain(entry) { - let unlock = await this.txLock.lock(); + const unlock = await this.txLock.lock(); try { return await this._resetChain(entry); } finally { diff --git a/lib/wallet/walletkey.js b/lib/wallet/walletkey.js index 215692c64..008561be6 100644 --- a/lib/wallet/walletkey.js +++ b/lib/wallet/walletkey.js @@ -262,7 +262,7 @@ WalletKey.fromRing = function fromRing(account, ring) { */ WalletKey.prototype.toPath = function toPath() { - let path = new Path(); + const path = new Path(); path.id = this.id; path.wid = this.wid; diff --git a/lib/workers/child.js b/lib/workers/child.js index 67dcf9ba8..8cc995438 100644 --- a/lib/workers/child.js +++ b/lib/workers/child.js @@ -51,9 +51,9 @@ Child.hasSupport = function hasSupport() { */ Child.prototype.init = function init(file) { - let bin = process.argv[0]; - let filename = path.resolve(__dirname, file); - let options = { stdio: 'pipe', env: process.env }; + const bin = process.argv[0]; + const filename = path.resolve(__dirname, file); + const options = { stdio: 'pipe', env: process.env }; this.child = cp.spawn(bin, [filename], options); @@ -123,7 +123,7 @@ function bindExit() { exitBound = true; listenExit(() => { - for (let child of children) + for (const child of children) child.destroy(); }); } @@ -135,19 +135,19 @@ function bindExit() { */ function listenExit(handler) { - let onSighup = () => { + const onSighup = () => { process.exit(1 | 0x80); }; - let onSigint = () => { + const onSigint = () => { process.exit(2 | 0x80); }; - let onSigterm = () => { + const onSigterm = () => { process.exit(15 | 0x80); }; - let onError = (err) => { + const onError = (err) => { if (err && err.stack) console.error(err.stack + ''); else diff --git a/lib/workers/framer.js b/lib/workers/framer.js index d4b7303e5..6b3d01d03 100644 --- a/lib/workers/framer.js +++ b/lib/workers/framer.js @@ -21,8 +21,8 @@ function Framer() { } Framer.prototype.packet = function _packet(packet) { - let size = 10 + packet.getSize(); - let bw = new StaticWriter(size); + const size = 10 + packet.getSize(); + const bw = new StaticWriter(size); let data; bw.writeU32(packet.id); diff --git a/lib/workers/jobs.js b/lib/workers/jobs.js index ff39037ce..21cbf700b 100644 --- a/lib/workers/jobs.js +++ b/lib/workers/jobs.js @@ -114,7 +114,7 @@ jobs.checkInput = function checkInput(tx, index, coin, flags) { */ jobs.sign = function sign(tx, ring, type) { - let total = tx.sign(ring, type); + const total = tx.sign(ring, type); return packets.SignResultPacket.fromTX(tx, total); }; @@ -129,7 +129,7 @@ jobs.sign = function sign(tx, ring, type) { */ jobs.signInput = function signInput(tx, index, coin, ring, type) { - let result = tx.signInput(tx, index, coin, ring, type); + const result = tx.signInput(tx, index, coin, ring, type); return packets.SignInputResultPacket.fromTX(tx, index, result); }; @@ -142,7 +142,7 @@ jobs.signInput = function signInput(tx, index, coin, ring, type) { */ jobs.ecVerify = function ecVerify(msg, sig, key) { - let result = secp256k1.verify(msg, sig, key); + const result = secp256k1.verify(msg, sig, key); return new packets.ECVerifyResultPacket(result); }; @@ -156,7 +156,7 @@ jobs.ecVerify = function ecVerify(msg, sig, key) { */ jobs.ecSign = function ecSign(msg, key) { - let sig = secp256k1.sign(msg, key); + const sig = secp256k1.sign(msg, key); return new packets.ECSignResultPacket(sig); }; @@ -170,7 +170,7 @@ jobs.ecSign = function ecSign(msg, key) { */ jobs.mine = function _mine(data, target, min, max) { - let nonce = mine(data, target, min, max); + const nonce = mine(data, target, min, max); return new packets.MineResultPacket(nonce); }; @@ -187,6 +187,6 @@ jobs.mine = function _mine(data, target, min, max) { */ jobs.scrypt = function _scrypt(passwd, salt, N, r, p, len) { - let key = scrypt.derive(passwd, salt, N, r, p, len); + const key = scrypt.derive(passwd, salt, N, r, p, len); return new packets.ScryptResultPacket(key); }; diff --git a/lib/workers/master.js b/lib/workers/master.js index b48c5174a..7303d860f 100644 --- a/lib/workers/master.js +++ b/lib/workers/master.js @@ -133,7 +133,7 @@ Master.prototype.destroy = function destroy() { */ Master.prototype.log = function log(...items) { - let text = util.format(items, this.color); + const text = util.format(items, this.color); this.send(new packets.LogPacket(text)); }; diff --git a/lib/workers/packets.js b/lib/workers/packets.js index 6721667c8..cf22ab63a 100644 --- a/lib/workers/packets.js +++ b/lib/workers/packets.js @@ -92,8 +92,8 @@ EnvPacket.prototype.toWriter = function toWriter(bw) { }; EnvPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new EnvPacket(); + const br = new BufferReader(data, true); + const packet = new EnvPacket(); packet.json = br.readVarString('utf8'); packet.env = JSON.parse(packet.json); return packet; @@ -123,8 +123,8 @@ EventPacket.prototype.toWriter = function toWriter(bw) { }; EventPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new EventPacket(); + const br = new BufferReader(data, true); + const packet = new EventPacket(); packet.json = br.readVarString('utf8'); packet.items = JSON.parse(packet.json); return packet; @@ -153,8 +153,8 @@ LogPacket.prototype.toWriter = function toWriter(bw) { }; LogPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new LogPacket(); + const br = new BufferReader(data, true); + const packet = new LogPacket(); packet.text = br.readVarString('utf8'); return packet; }; @@ -218,8 +218,8 @@ ErrorPacket.prototype.toWriter = function toWriter(bw) { }; ErrorPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ErrorPacket(); + const br = new BufferReader(data, true); + const packet = new ErrorPacket(); packet.error.message = br.readVarString('utf8'); packet.error.stack = br.readVarString('utf8'); @@ -280,8 +280,8 @@ CheckPacket.prototype.toWriter = function toWriter(bw) { }; CheckPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new CheckPacket(); + const br = new BufferReader(data, true); + const packet = new CheckPacket(); packet.tx = TX.fromReader(br); packet.view = CoinView.fromReader(br, packet.tx); @@ -308,7 +308,7 @@ util.inherits(CheckResultPacket, Packet); CheckResultPacket.prototype.cmd = packetTypes.CHECKRESULT; CheckResultPacket.prototype.getSize = function getSize() { - let err = this.error; + const err = this.error; let size = 0; if (!err) { @@ -327,7 +327,7 @@ CheckResultPacket.prototype.getSize = function getSize() { }; CheckResultPacket.prototype.toWriter = function toWriter(bw) { - let err = this.error; + const err = this.error; if (!err) { bw.writeU8(0); @@ -343,8 +343,8 @@ CheckResultPacket.prototype.toWriter = function toWriter(bw) { }; CheckResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new CheckResultPacket(); + const br = new BufferReader(data, true); + const packet = new CheckResultPacket(); let err; if (br.readU8() === 0) @@ -391,7 +391,7 @@ SignPacket.prototype.getSize = function getSize() { size += this.tx.view.getSize(this.tx); size += encoding.sizeVarint(this.rings.length); - for (let ring of this.rings) + for (const ring of this.rings) size += ring.getSize(); size += 1; @@ -405,15 +405,15 @@ SignPacket.prototype.toWriter = function toWriter(bw) { bw.writeVarint(this.rings.length); - for (let ring of this.rings) + for (const ring of this.rings) ring.toWriter(bw); bw.writeU8(this.type); }; SignPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new SignPacket(); + const br = new BufferReader(data, true); + const packet = new SignPacket(); let count; packet.tx = MTX.fromReader(br); @@ -422,7 +422,7 @@ SignPacket.fromRaw = function fromRaw(data) { count = br.readVarint(); for (let i = 0; i < count; i++) { - let ring = KeyRing.fromReader(br); + const ring = KeyRing.fromReader(br); packet.rings.push(ring); } @@ -448,9 +448,9 @@ util.inherits(SignResultPacket, Packet); SignResultPacket.prototype.cmd = packetTypes.SIGNRESULT; SignResultPacket.fromTX = function fromTX(tx, total) { - let packet = new SignResultPacket(total); + const packet = new SignResultPacket(total); - for (let input of tx.inputs) { + for (const input of tx.inputs) { packet.script.push(input.script); packet.witness.push(input.witness); } @@ -465,8 +465,8 @@ SignResultPacket.prototype.getSize = function getSize() { size += encoding.sizeVarint(this.script.length); for (let i = 0; i < this.script.length; i++) { - let script = this.script[i]; - let witness = this.witness[i]; + const script = this.script[i]; + const witness = this.witness[i]; size += script.getVarSize(); size += witness.getVarSize(); } @@ -491,15 +491,15 @@ SignResultPacket.prototype.inject = function inject(tx) { assert(this.witness.length === tx.inputs.length); for (let i = 0; i < tx.inputs.length; i++) { - let input = tx.inputs[i]; + const input = tx.inputs[i]; input.script = this.script[i]; input.witness = this.witness[i]; } }; SignResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new SignResultPacket(); + const br = new BufferReader(data, true); + const packet = new SignResultPacket(); let count; packet.total = br.readVarint(); @@ -550,8 +550,8 @@ CheckInputPacket.prototype.toWriter = function toWriter(bw) { }; CheckInputPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new CheckInputPacket(); + const br = new BufferReader(data, true); + const packet = new CheckInputPacket(); packet.tx = TX.fromReader(br); packet.index = br.readVarint(); @@ -582,8 +582,8 @@ util.inherits(CheckInputResultPacket, CheckResultPacket); CheckInputResultPacket.prototype.cmd = packetTypes.CHECKINPUTRESULT; CheckInputResultPacket.fromRaw = function fromRaw(data) { - let p = CheckResultPacket.fromRaw(data); - let packet = new CheckInputResultPacket(); + const p = CheckResultPacket.fromRaw(data); + const packet = new CheckInputResultPacket(); packet.error = p.error; return packet; }; @@ -627,8 +627,8 @@ SignInputPacket.prototype.toWriter = function toWriter(bw) { }; SignInputPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new SignInputPacket(); + const br = new BufferReader(data, true); + const packet = new SignInputPacket(); packet.tx = MTX.fromReader(br); packet.index = br.readVarint(); @@ -660,8 +660,8 @@ util.inherits(SignInputResultPacket, Packet); SignInputResultPacket.prototype.cmd = packetTypes.SIGNINPUTRESULT; SignInputResultPacket.fromTX = function fromTX(tx, i, value) { - let packet = new SignInputResultPacket(value); - let input = tx.inputs[i]; + const packet = new SignInputResultPacket(value); + const input = tx.inputs[i]; assert(input); @@ -682,15 +682,15 @@ SignInputResultPacket.prototype.toWriter = function toWriter(bw) { }; SignInputResultPacket.prototype.inject = function inject(tx, i) { - let input = tx.inputs[i]; + const input = tx.inputs[i]; assert(input); input.script = this.script; input.witness = this.witness; }; SignInputResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new SignInputResultPacket(); + const br = new BufferReader(data, true); + const packet = new SignInputResultPacket(); packet.value = br.readU8() === 1; packet.script = Script.fromReader(br); packet.witness = Witness.fromReader(br); @@ -729,8 +729,8 @@ ECVerifyPacket.prototype.toWriter = function toWriter(bw) { }; ECVerifyPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ECVerifyPacket(); + const br = new BufferReader(data, true); + const packet = new ECVerifyPacket(); packet.msg = br.readVarBytes(); packet.sig = br.readVarBytes(); packet.key = br.readVarBytes(); @@ -760,8 +760,8 @@ ECVerifyResultPacket.prototype.toWriter = function toWriter(bw) { }; ECVerifyResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ECVerifyResultPacket(); + const br = new BufferReader(data, true); + const packet = new ECVerifyResultPacket(); packet.value = br.readU8() === 1; return packet; }; @@ -794,8 +794,8 @@ ECSignPacket.prototype.toWriter = function toWriter(bw) { }; ECSignPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ECSignPacket(); + const br = new BufferReader(data, true); + const packet = new ECSignPacket(); packet.msg = br.readVarBytes(); packet.key = br.readVarBytes(); return packet; @@ -824,8 +824,8 @@ ECSignResultPacket.prototype.toWriter = function toWriter(bw) { }; ECSignResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ECSignResultPacket(); + const br = new BufferReader(data, true); + const packet = new ECSignResultPacket(); packet.sig = br.readVarBytes(); return packet; }; @@ -859,8 +859,8 @@ MinePacket.prototype.toWriter = function toWriter(bw) { }; MinePacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new MinePacket(); + const br = new BufferReader(data, true); + const packet = new MinePacket(); packet.data = br.readBytes(80); packet.target = br.readBytes(32); packet.min = br.readU32(); @@ -891,8 +891,8 @@ MineResultPacket.prototype.toWriter = function toWriter(bw) { }; MineResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new MineResultPacket(); + const br = new BufferReader(data, true); + const packet = new MineResultPacket(); packet.nonce = br.readU32(); if ((packet.nonce >> 0) === -1) packet.nonce = -1; @@ -936,8 +936,8 @@ ScryptPacket.prototype.toWriter = function toWriter(bw) { }; ScryptPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ScryptPacket(); + const br = new BufferReader(data, true); + const packet = new ScryptPacket(); packet.passwd = br.readVarBytes(); packet.salt = br.readVarBytes(); packet.N = br.readU32(); @@ -970,8 +970,8 @@ ScryptResultPacket.prototype.toWriter = function toWriter(bw) { }; ScryptResultPacket.fromRaw = function fromRaw(data) { - let br = new BufferReader(data, true); - let packet = new ScryptResultPacket(); + const br = new BufferReader(data, true); + const packet = new ScryptResultPacket(); packet.key = br.readVarBytes(); return packet; }; diff --git a/lib/workers/parser.js b/lib/workers/parser.js index 13cbb0129..f98fd76f1 100644 --- a/lib/workers/parser.js +++ b/lib/workers/parser.js @@ -37,7 +37,7 @@ Parser.prototype.feed = function feed(data) { this.pending.push(data); while (this.total >= this.waiting) { - let chunk = this.read(this.waiting); + const chunk = this.read(this.waiting); this.parse(chunk); } }; @@ -125,9 +125,9 @@ Parser.prototype.parse = function parse(data) { }; Parser.prototype.parseHeader = function parseHeader(data) { - let id = data.readUInt32LE(0, true); - let cmd = data.readUInt8(4, true); - let size = data.readUInt32LE(5, true); + const id = data.readUInt32LE(0, true); + const cmd = data.readUInt8(4, true); + const size = data.readUInt32LE(5, true); return new Header(id, cmd, size); }; diff --git a/lib/workers/workerpool.js b/lib/workers/workerpool.js index b289aa797..9bdddb7de 100644 --- a/lib/workers/workerpool.js +++ b/lib/workers/workerpool.js @@ -108,7 +108,7 @@ WorkerPool.prototype.close = async function close() { */ WorkerPool.prototype.spawn = function spawn(id) { - let child = new Worker(this.file); + const child = new Worker(this.file); child.id = id; @@ -144,7 +144,7 @@ WorkerPool.prototype.spawn = function spawn(id) { */ WorkerPool.prototype.alloc = function alloc() { - let id = this.uid++ % this.size; + const id = this.uid++ % this.size; if (!this.children.has(id)) this.children.set(id, this.spawn(id)); @@ -162,7 +162,7 @@ WorkerPool.prototype.alloc = function alloc() { WorkerPool.prototype.sendEvent = function sendEvent() { let result = true; - for (let child of this.children.values()) { + for (const child of this.children.values()) { if (!child.sendEvent.apply(child, arguments)) result = false; } @@ -175,7 +175,7 @@ WorkerPool.prototype.sendEvent = function sendEvent() { */ WorkerPool.prototype.destroy = function destroy() { - for (let child of this.children.values()) + for (const child of this.children.values()) child.destroy(); }; @@ -222,8 +222,8 @@ WorkerPool.prototype.execute = function execute(packet, timeout) { */ WorkerPool.prototype.check = async function check(tx, view, flags) { - let packet = new packets.CheckPacket(tx, view, flags); - let result = await this.execute(packet, -1); + const packet = new packets.CheckPacket(tx, view, flags); + const result = await this.execute(packet, -1); if (result.error) throw result.error; @@ -266,8 +266,8 @@ WorkerPool.prototype.sign = async function sign(tx, ring, type) { */ WorkerPool.prototype.checkInput = async function checkInput(tx, index, coin, flags) { - let packet = new packets.CheckInputPacket(tx, index, coin, flags); - let result = await this.execute(packet, -1); + const packet = new packets.CheckInputPacket(tx, index, coin, flags); + const result = await this.execute(packet, -1); if (result.error) throw result.error; @@ -287,8 +287,8 @@ WorkerPool.prototype.checkInput = async function checkInput(tx, index, coin, fla */ WorkerPool.prototype.signInput = async function signInput(tx, index, coin, ring, type) { - let packet = new packets.SignInputPacket(tx, index, coin, ring, type); - let result = await this.execute(packet, -1); + const packet = new packets.SignInputPacket(tx, index, coin, ring, type); + const result = await this.execute(packet, -1); result.inject(tx); return result.value; }; @@ -303,8 +303,8 @@ WorkerPool.prototype.signInput = async function signInput(tx, index, coin, ring, */ WorkerPool.prototype.ecVerify = async function ecVerify(msg, sig, key) { - let packet = new packets.ECVerifyPacket(msg, sig, key); - let result = await this.execute(packet, -1); + const packet = new packets.ECVerifyPacket(msg, sig, key); + const result = await this.execute(packet, -1); return result.value; }; @@ -317,8 +317,8 @@ WorkerPool.prototype.ecVerify = async function ecVerify(msg, sig, key) { */ WorkerPool.prototype.ecSign = async function ecSign(msg, key) { - let packet = new packets.ECSignPacket(msg, key); - let result = await this.execute(packet, -1); + const packet = new packets.ECSignPacket(msg, key); + const result = await this.execute(packet, -1); return result.sig; }; @@ -333,8 +333,8 @@ WorkerPool.prototype.ecSign = async function ecSign(msg, key) { */ WorkerPool.prototype.mine = async function mine(data, target, min, max) { - let packet = new packets.MinePacket(data, target, min, max); - let result = await this.execute(packet, -1); + const packet = new packets.MinePacket(data, target, min, max); + const result = await this.execute(packet, -1); return result.nonce; }; @@ -351,8 +351,8 @@ WorkerPool.prototype.mine = async function mine(data, target, min, max) { */ WorkerPool.prototype.scrypt = async function scrypt(passwd, salt, N, r, p, len) { - let packet = new packets.ScryptPacket(passwd, salt, N, r, p, len); - let result = await this.execute(packet, -1); + const packet = new packets.ScryptPacket(passwd, salt, N, r, p, len); + const result = await this.execute(packet, -1); return result.key; }; @@ -540,7 +540,7 @@ Worker.prototype.execute = function execute(packet, timeout) { */ Worker.prototype._execute = function _execute(packet, timeout, resolve, reject) { - let job = new PendingJob(this, packet.id, resolve, reject); + const job = new PendingJob(this, packet.id, resolve, reject); assert(!this.pending.has(packet.id), 'ID overflow.'); @@ -558,7 +558,7 @@ Worker.prototype._execute = function _execute(packet, timeout, resolve, reject) */ Worker.prototype.resolveJob = function resolveJob(id, result) { - let job = this.pending.get(id); + const job = this.pending.get(id); if (!job) throw new Error(`Job ${id} is not in progress.`); @@ -573,7 +573,7 @@ Worker.prototype.resolveJob = function resolveJob(id, result) { */ Worker.prototype.rejectJob = function rejectJob(id, err) { - let job = this.pending.get(id); + const job = this.pending.get(id); if (!job) throw new Error(`Job ${id} is not in progress.`); @@ -586,7 +586,7 @@ Worker.prototype.rejectJob = function rejectJob(id, err) { */ Worker.prototype.killJobs = function killJobs() { - for (let job of this.pending.values()) + for (const job of this.pending.values()) job.destroy(); }; @@ -635,7 +635,7 @@ PendingJob.prototype.destroy = function destroy() { */ PendingJob.prototype.cleanup = function cleanup() { - let job = this.job; + const job = this.job; assert(job, 'Already finished.'); @@ -658,7 +658,7 @@ PendingJob.prototype.cleanup = function cleanup() { */ PendingJob.prototype.resolve = function resolve(result) { - let job = this.cleanup(); + const job = this.cleanup(); job.resolve(result); }; @@ -668,7 +668,7 @@ PendingJob.prototype.resolve = function resolve(result) { */ PendingJob.prototype.reject = function reject(err) { - let job = this.cleanup(); + const job = this.cleanup(); job.reject(err); }; diff --git a/migrate/chaindb0to1.js b/migrate/chaindb0to1.js index 86db9e011..4d610013e 100644 --- a/migrate/chaindb0to1.js +++ b/migrate/chaindb0to1.js @@ -19,8 +19,8 @@ const db = bcoin.ldb({ }); function makeKey(data) { - let height = data.readUInt32LE(1, true); - let key = Buffer.allocUnsafe(5); + const height = data.readUInt32LE(1, true); + const key = Buffer.allocUnsafe(5); key[0] = 0x48; key.writeUInt32BE(height, 1, true); return key; @@ -75,7 +75,7 @@ async function updateState() { } async function updateEndian() { - let batch = db.batch(); + const batch = db.batch(); let total = 0; let iter, item; diff --git a/migrate/chaindb1to2.js b/migrate/chaindb1to2.js index 3792837e2..4cb1d48e5 100644 --- a/migrate/chaindb1to2.js +++ b/migrate/chaindb1to2.js @@ -64,7 +64,7 @@ async function updateVersion() { } async function checkTipIndex() { - let keys = await db.keys({ + const keys = await db.keys({ gte: pair('p', encoding.ZERO_HASH), lte: pair('p', encoding.MAX_HASH) }); @@ -206,7 +206,7 @@ function write(data, str, off) { } function pair(prefix, hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); if (typeof prefix === 'string') prefix = prefix.charCodeAt(0); key[0] = prefix; @@ -215,7 +215,7 @@ function pair(prefix, hash) { } function injectCoin(undo, coin) { - let output = new Output(); + const output = new Output(); output.value = coin.value; output.script = coin.script; @@ -227,7 +227,7 @@ function injectCoin(undo, coin) { } function defaultOptions() { - let bw = new BufferWriter(); + const bw = new BufferWriter(); let flags = 0; if (options.spv) @@ -252,7 +252,7 @@ function defaultOptions() { } function defaultDeployments() { - let bw = new BufferWriter(); + const bw = new BufferWriter(); let i, deployment; bw.writeU8(options.network.deploys.length); diff --git a/migrate/chaindb2to3.js b/migrate/chaindb2to3.js index 6458fa3cc..dac3e5083 100644 --- a/migrate/chaindb2to3.js +++ b/migrate/chaindb2to3.js @@ -56,7 +56,7 @@ const STATE_DONE = 5; const metaCache = new Map(); function writeJournal(batch, state, hash) { - let data = Buffer.allocUnsafe(34); + const data = Buffer.allocUnsafe(34); if (!hash) hash = encoding.NULL_HASH; @@ -69,7 +69,7 @@ function writeJournal(batch, state, hash) { } async function readJournal() { - let data = await db.get(JOURNAL_KEY); + const data = await db.get(JOURNAL_KEY); let state, hash; if (!data) @@ -91,7 +91,7 @@ async function readJournal() { } async function updateVersion() { - let batch = db.batch(); + const batch = db.batch(); let data, version; console.log('Checking version.'); @@ -126,7 +126,7 @@ async function updateVersion() { async function reserializeUndo(hash) { let batch = db.batch(); let tip = await getTip(); - let height = tip.height; + const height = tip.height; let pruning = false; let total = 0; @@ -176,11 +176,11 @@ async function reserializeUndo(hash) { undo = new UndoCoins(); for (let i = block.txs.length - 1; i >= 1; i--) { - let tx = block.txs[i]; + const tx = block.txs[i]; for (let j = tx.inputs.length - 1; j >= 0; j--) { - let {prevout} = tx.inputs[j]; - let coin = old.items.pop(); - let output = coin.toOutput(); + const {prevout} = tx.inputs[j]; + const coin = old.items.pop(); + const output = coin.toOutput(); let version, height, write, item; assert(coin); @@ -198,7 +198,7 @@ async function reserializeUndo(hash) { // Store an index of heights and versions for later. if (write) { - let data = Buffer.allocUnsafe(8); + const data = Buffer.allocUnsafe(8); data.writeUInt32LE(version, 0, true); data.writeUInt32LE(height, 4, true); batch.put(pair(0x01, prevout.hash), data); @@ -239,7 +239,7 @@ async function cleanupIndex() { let batch = db.batch(); let total = 0; - let iter = db.iterator({ + const iter = db.iterator({ gte: pair(0x01, encoding.ZERO_HASH), lte: pair(0x01, encoding.MAX_HASH), keys: true @@ -248,7 +248,7 @@ async function cleanupIndex() { console.log('Removing txid->height undo index.'); for (;;) { - let item = await iter.next(); + const item = await iter.next(); if (!item) break; @@ -276,7 +276,7 @@ async function reserializeCoins(hash) { let start = true; let total = 0; - let iter = db.iterator({ + const iter = db.iterator({ gte: pair('c', hash), lte: pair('c', encoding.MAX_HASH), keys: true, @@ -284,7 +284,7 @@ async function reserializeCoins(hash) { }); if (hash !== encoding.NULL_HASH) { - let item = await iter.next(); + const item = await iter.next(); if (!item) start = false; } @@ -292,7 +292,7 @@ async function reserializeCoins(hash) { console.log('Reserializing coins from %s.', util.revHex(hash)); while (start) { - let item = await iter.next(); + const item = await iter.next(); let update = false; let hash, old; @@ -306,7 +306,7 @@ async function reserializeCoins(hash) { old = OldCoins.fromRaw(item.value, hash); for (let i = 0; i < old.outputs.length; i++) { - let coin = old.getCoin(i); + const coin = old.getCoin(i); let item; if (!coin) @@ -346,19 +346,19 @@ async function reserializeCoins(hash) { } async function reserializeEntries(hash) { - let tip = await getTipHash(); + const tip = await getTipHash(); let batch = db.batch(); let start = true; let total = 0; - let iter = db.iterator({ + const iter = db.iterator({ gte: pair('e', hash), lte: pair('e', encoding.MAX_HASH), values: true }); if (hash !== encoding.NULL_HASH) { - let item = await iter.next(); + const item = await iter.next(); if (!item) start = false; else @@ -368,7 +368,7 @@ async function reserializeEntries(hash) { console.log('Reserializing entries from %s.', util.revHex(hash)); while (start) { - let item = await iter.next(); + const item = await iter.next(); let entry, main; if (!item) @@ -396,8 +396,8 @@ async function reserializeEntries(hash) { } async function finalize() { - let batch = db.batch(); - let data = Buffer.allocUnsafe(4); + const batch = db.batch(); + const data = Buffer.allocUnsafe(4); data.writeUInt32LE(3, 0, true); @@ -408,7 +408,7 @@ async function finalize() { batch.del(pair('n', encoding.ZERO_HASH)); if (shouldPrune) { - let data = await db.get('O'); + const data = await db.get('O'); let flags; assert(data); @@ -447,7 +447,7 @@ async function getMeta(coin, prevout) { item = metaCache.get(prevout.hash); if (item) { - let [version, height] = item; + const [version, height] = item; return [version, height, false]; } @@ -457,8 +457,8 @@ async function getMeta(coin, prevout) { data = await db.get(pair(0x01, prevout.hash)); if (data) { - let version = data.readUInt32LE(0, true); - let height = data.readUInt32LE(4, true); + const version = data.readUInt32LE(0, true); + const height = data.readUInt32LE(4, true); return [version, height, false]; } @@ -475,30 +475,30 @@ async function getMeta(coin, prevout) { } async function getTip() { - let tip = await getTipHash(); + const tip = await getTipHash(); return await getEntry(tip); } async function getTipHash() { - let state = await db.get('R'); + const state = await db.get('R'); assert(state); return state.toString('hex', 0, 32); } async function getEntry(hash) { - let data = await db.get(pair('e', hash)); + const data = await db.get(pair('e', hash)); assert(data); return entryFromRaw(data); } async function isPruned() { - let data = await db.get('O'); + const data = await db.get('O'); assert(data); return (data.readUInt32LE(4) & 4) !== 0; } async function isSPV() { - let data = await db.get('O'); + const data = await db.get('O'); assert(data); return (data.readUInt32LE(4) & 1) !== 0; } @@ -514,9 +514,9 @@ async function isMainChain(entry, tip) { } function entryFromRaw(data) { - let p = new BufferReader(data, true); - let hash = digest.hash256(p.readBytes(80)); - let entry = {}; + const p = new BufferReader(data, true); + const hash = digest.hash256(p.readBytes(80)); + const entry = {}; p.seek(-80); @@ -534,7 +534,7 @@ function entryFromRaw(data) { } function entryToRaw(entry, main) { - let bw = new StaticWriter(116 + 1); + const bw = new StaticWriter(116 + 1); bw.writeU32(entry.version); bw.writeHash(entry.prevBlock); @@ -556,7 +556,7 @@ function write(data, str, off) { } function pair(prefix, hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); if (typeof prefix === 'string') prefix = prefix.charCodeAt(0); key[0] = prefix; @@ -565,7 +565,7 @@ function pair(prefix, hash) { } function bpair(prefix, hash, index) { - let key = Buffer.allocUnsafe(37); + const key = Buffer.allocUnsafe(37); if (typeof prefix === 'string') prefix = prefix.charCodeAt(0); key[0] = prefix; diff --git a/migrate/coins-old.js b/migrate/coins-old.js index 45582b48b..d58e47d61 100644 --- a/migrate/coins-old.js +++ b/migrate/coins-old.js @@ -151,7 +151,7 @@ Coins.prototype.get = function get(index) { */ Coins.prototype.spend = function spend(index) { - let coin = this.get(index); + const coin = this.get(index); if (!coin) return; @@ -221,9 +221,9 @@ Coins.prototype.isEmpty = function isEmpty() { */ Coins.prototype.toRaw = function toRaw() { - let bw = new BufferWriter(); - let length = this.size(); - let len = Math.ceil(length / 8); + const bw = new BufferWriter(); + const length = this.size(); + const len = Math.ceil(length / 8); let i, output, bits, start, bit, oct, data; // Return nothing if we're fully spent. @@ -302,7 +302,7 @@ Coins.prototype.toRaw = function toRaw() { */ Coins.prototype.fromRaw = function fromRaw(data, hash, index) { - let br = new BufferReader(data); + const br = new BufferReader(data); let pos = 0; let bits, len, start, bit, oct, spent, coin; @@ -356,8 +356,8 @@ Coins.prototype.fromRaw = function fromRaw(data, hash, index) { */ Coins.parseCoin = function parseCoin(data, hash, index) { - let br = new BufferReader(data); - let coin = new Coin(); + const br = new BufferReader(data); + const coin = new Coin(); let pos = 0; let bits, len, start, bit, oct, spent; @@ -490,7 +490,7 @@ function CoinEntry() { */ CoinEntry.prototype.toCoin = function toCoin(coins, index) { - let coin = new Coin(); + const coin = new Coin(); let br; // Load in all necessary properties @@ -551,7 +551,7 @@ CoinEntry.prototype.toWriter = function toWriter(bw) { */ CoinEntry.fromReader = function fromReader(br) { - let entry = new CoinEntry(); + const entry = new CoinEntry(); entry.offset = br.offset; entry.size = skipCoin(br); entry.raw = br.data; @@ -566,7 +566,7 @@ CoinEntry.fromReader = function fromReader(br) { */ CoinEntry.fromTX = function fromTX(tx, index) { - let entry = new CoinEntry(); + const entry = new CoinEntry(); entry.output = tx.outputs[index]; return entry; }; @@ -578,7 +578,7 @@ CoinEntry.fromTX = function fromTX(tx, index) { */ CoinEntry.fromCoin = function fromCoin(coin) { - let entry = new CoinEntry(); + const entry = new CoinEntry(); entry.output = new Output(); entry.output.script = coin.script; entry.output.value = coin.value; @@ -590,7 +590,7 @@ CoinEntry.fromCoin = function fromCoin(coin) { */ function skipCoin(br) { - let start = br.offset; + const start = br.offset; // Skip past the compressed scripts. switch (br.readU8()) { diff --git a/migrate/coins/coins.js b/migrate/coins/coins.js index 3d727c209..aef8edd05 100644 --- a/migrate/coins/coins.js +++ b/migrate/coins/coins.js @@ -182,7 +182,7 @@ Coins.prototype.get = function get(index) { */ Coins.prototype.getOutput = function getOutput(index) { - let entry = this.get(index); + const entry = this.get(index); if (!entry) return; @@ -197,7 +197,7 @@ Coins.prototype.getOutput = function getOutput(index) { */ Coins.prototype.getCoin = function getCoin(index) { - let entry = this.get(index); + const entry = this.get(index); if (!entry) return; @@ -212,7 +212,7 @@ Coins.prototype.getCoin = function getCoin(index) { */ Coins.prototype.spend = function spend(index) { - let entry = this.get(index); + const entry = this.get(index); if (!entry || entry.spent) return; @@ -229,7 +229,7 @@ Coins.prototype.spend = function spend(index) { */ Coins.prototype.remove = function remove(index) { - let entry = this.get(index); + const entry = this.get(index); if (!entry) return false; @@ -314,8 +314,8 @@ Coins.prototype.isEmpty = function isEmpty() { */ Coins.prototype.header = function header(len, size) { - let first = this.isUnspent(0); - let second = this.isUnspent(1); + const first = this.isUnspent(0); + const second = this.isUnspent(1); let offset = 0; let code; @@ -350,11 +350,11 @@ Coins.prototype.header = function header(len, size) { */ Coins.prototype.toRaw = function toRaw() { - let len = this.length(); - let size = Math.floor((len + 5) / 8); - let code = this.header(len, size); - let total = this.getSize(len, size, code); - let bw = new StaticWriter(total); + const len = this.length(); + const size = Math.floor((len + 5) / 8); + const code = this.header(len, size); + const total = this.getSize(len, size, code); + const bw = new StaticWriter(total); // Write headers. bw.writeVarint(this.version); @@ -373,7 +373,7 @@ Coins.prototype.toRaw = function toRaw() { // Write the compressed outputs. for (let i = 0; i < len; i++) { - let output = this.outputs[i]; + const output = this.outputs[i]; if (!output || output.spent) continue; @@ -402,7 +402,7 @@ Coins.prototype.getSize = function getSize(len, size, code) { // Write the compressed outputs. for (let i = 0; i < len; i++) { - let output = this.outputs[i]; + const output = this.outputs[i]; if (!output || output.spent) continue; @@ -422,7 +422,7 @@ Coins.prototype.getSize = function getSize(len, size, code) { */ Coins.prototype.fromRaw = function fromRaw(data, hash) { - let br = new BufferReader(data); + const br = new BufferReader(data); let first = null; let second = null; let code, size, offset; @@ -458,7 +458,7 @@ Coins.prototype.fromRaw = function fromRaw(data, hash) { // Read outputs. for (let i = 0; i < size; i++) { - let ch = br.data[offset++]; + const ch = br.data[offset++]; for (let j = 0; j < 8; j++) { if ((ch & (1 << j)) === 0) { this.outputs.push(null); @@ -482,8 +482,8 @@ Coins.prototype.fromRaw = function fromRaw(data, hash) { */ Coins.parseCoin = function parseCoin(data, hash, index) { - let br = new BufferReader(data); - let coin = new Coin(); + const br = new BufferReader(data); + const coin = new Coin(); let code, size, offset; // Inject outpoint (passed by caller). @@ -526,7 +526,7 @@ Coins.parseCoin = function parseCoin(data, hash, index) { // Read outputs. for (let i = 0; i < size; i++) { - let ch = br.data[offset++]; + const ch = br.data[offset++]; for (let j = 0; j < 8; j++) { if ((ch & (1 << j)) !== 0) { if (index === 0) { @@ -649,8 +649,8 @@ CoinEntry.prototype.reader = function reader() { */ CoinEntry.prototype.toCoin = function toCoin(coins, index) { - let coin = new Coin(); - let output = this.toOutput(); + const coin = new Coin(); + const output = this.toOutput(); // Load in all necessary properties // from the parent Coins object. @@ -718,7 +718,7 @@ CoinEntry.prototype.toWriter = function toWriter(bw) { */ CoinEntry.fromReader = function fromReader(br) { - let entry = new CoinEntry(); + const entry = new CoinEntry(); entry.offset = br.offset; entry.size = decompress.skip(br); entry.raw = br.data; @@ -732,7 +732,7 @@ CoinEntry.fromReader = function fromReader(br) { */ CoinEntry.fromOutput = function fromOutput(output) { - let entry = new CoinEntry(); + const entry = new CoinEntry(); entry.output = output; return entry; }; @@ -744,8 +744,8 @@ CoinEntry.fromOutput = function fromOutput(output) { */ CoinEntry.fromCoin = function fromCoin(coin) { - let entry = new CoinEntry(); - let output = new Output(); + const entry = new CoinEntry(); + const output = new Output(); output.value = coin.value; output.script = coin.script; entry.output = output; diff --git a/migrate/coins/coinview.js b/migrate/coins/coinview.js index 00e4864f7..f3dcb941d 100644 --- a/migrate/coins/coinview.js +++ b/migrate/coins/coinview.js @@ -80,7 +80,7 @@ CoinView.prototype.remove = function remove(hash) { */ CoinView.prototype.addTX = function addTX(tx, height) { - let coins = Coins.fromTX(tx, height); + const coins = Coins.fromTX(tx, height); return this.add(coins); }; @@ -91,7 +91,7 @@ CoinView.prototype.addTX = function addTX(tx, height) { */ CoinView.prototype.removeTX = function removeTX(tx, height) { - let coins = Coins.fromTX(tx, height); + const coins = Coins.fromTX(tx, height); coins.outputs.length = 0; return this.add(coins); }; @@ -152,7 +152,7 @@ CoinView.prototype.addOutput = function addOutput(hash, index, output) { */ CoinView.prototype.spendOutput = function spendOutput(hash, index) { - let coins = this.get(hash); + const coins = this.get(hash); if (!coins) return false; @@ -168,7 +168,7 @@ CoinView.prototype.spendOutput = function spendOutput(hash, index) { */ CoinView.prototype.removeOutput = function removeOutput(hash, index) { - let coins = this.get(hash); + const coins = this.get(hash); if (!coins) return false; @@ -184,7 +184,7 @@ CoinView.prototype.removeOutput = function removeOutput(hash, index) { */ CoinView.prototype.spendFrom = function spendFrom(coins, index) { - let entry = coins.spend(index); + const entry = coins.spend(index); let undo; if (!entry) @@ -210,7 +210,7 @@ CoinView.prototype.spendFrom = function spendFrom(coins, index) { */ CoinView.prototype.getCoin = function getCoin(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return; @@ -225,7 +225,7 @@ CoinView.prototype.getCoin = function getCoin(input) { */ CoinView.prototype.getOutput = function getOutput(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return; @@ -240,7 +240,7 @@ CoinView.prototype.getOutput = function getOutput(input) { */ CoinView.prototype.getEntry = function getEntry(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return; @@ -255,7 +255,7 @@ CoinView.prototype.getEntry = function getEntry(input) { */ CoinView.prototype.hasEntry = function hasEntry(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return false; @@ -270,7 +270,7 @@ CoinView.prototype.hasEntry = function hasEntry(input) { */ CoinView.prototype.getHeight = function getHeight(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return -1; @@ -285,7 +285,7 @@ CoinView.prototype.getHeight = function getHeight(input) { */ CoinView.prototype.isCoinbase = function isCoinbase(input) { - let coins = this.get(input.prevout.hash); + const coins = this.get(input.prevout.hash); if (!coins) return false; @@ -327,7 +327,7 @@ CoinView.prototype.readCoins = async function readCoins(db, hash) { CoinView.prototype.ensureInputs = async function ensureInputs(db, tx) { let found = true; - for (let input of tx.inputs) { + for (const input of tx.inputs) { if (!(await this.readCoins(db, input.prevout.hash))) found = false; } @@ -344,9 +344,9 @@ CoinView.prototype.ensureInputs = async function ensureInputs(db, tx) { */ CoinView.prototype.spendInputs = async function spendInputs(db, tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; - let coins = await this.readCoins(db, prevout.hash); + for (const input of tx.inputs) { + const prevout = input.prevout; + const coins = await this.readCoins(db, prevout.hash); if (!coins) return false; @@ -364,9 +364,9 @@ CoinView.prototype.spendInputs = async function spendInputs(db, tx) { */ CoinView.prototype.toArray = function toArray() { - let out = []; + const out = []; - for (let coins of this.map.values()) + for (const coins of this.map.values()) out.push(coins); return out; @@ -382,8 +382,8 @@ CoinView.prototype.getSize = function getSize(tx) { size += tx.inputs.length; - for (let input of tx.inputs) { - let entry = this.getEntry(input); + for (const input of tx.inputs) { + const entry = this.getEntry(input); if (!entry) continue; @@ -402,9 +402,9 @@ CoinView.prototype.getSize = function getSize(tx) { */ CoinView.prototype.toWriter = function toWriter(bw, tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; - let coins = this.get(prevout.hash); + for (const input of tx.inputs) { + const prevout = input.prevout; + const coins = this.get(prevout.hash); let entry; if (!coins) { @@ -435,8 +435,8 @@ CoinView.prototype.toWriter = function toWriter(bw, tx) { */ CoinView.prototype.fromReader = function fromReader(br, tx) { - for (let input of tx.inputs) { - let prevout = input.prevout; + for (const input of tx.inputs) { + const prevout = input.prevout; let coins, entry; if (br.readU8() === 0) diff --git a/migrate/coins/compress.js b/migrate/coins/compress.js index ebe057c17..e50be0e39 100644 --- a/migrate/coins/compress.js +++ b/migrate/coins/compress.js @@ -217,7 +217,7 @@ function decompressCoin(coin, br) { */ function skipOutput(br) { - let start = br.offset; + const start = br.offset; // Skip past the value. br.skipVarint(); @@ -367,7 +367,7 @@ function compressKey(key) { */ function decompressKey(key) { - let format = key[0]; + const format = key[0]; let out; assert(key.length === 33); diff --git a/migrate/coins/undocoins.js b/migrate/coins/undocoins.js index 4b6034fa9..b1e6e607b 100644 --- a/migrate/coins/undocoins.js +++ b/migrate/coins/undocoins.js @@ -40,7 +40,7 @@ function UndoCoins() { */ UndoCoins.prototype.push = function push(entry) { - let undo = new UndoCoin(); + const undo = new UndoCoin(); undo.entry = entry; this.items.push(undo); }; @@ -55,7 +55,7 @@ UndoCoins.prototype.getSize = function getSize() { size += 4; - for (let coin of this.items) + for (const coin of this.items) size += coin.getSize(); return size; @@ -67,12 +67,12 @@ UndoCoins.prototype.getSize = function getSize() { */ UndoCoins.prototype.toRaw = function toRaw() { - let size = this.getSize(); - let bw = new StaticWriter(size); + const size = this.getSize(); + const bw = new StaticWriter(size); bw.writeU32(this.items.length); - for (let coin of this.items) + for (const coin of this.items) coin.toWriter(bw); return bw.render(); @@ -86,8 +86,8 @@ UndoCoins.prototype.toRaw = function toRaw() { */ UndoCoins.prototype.fromRaw = function fromRaw(data) { - let br = new BufferReader(data); - let count = br.readU32(); + const br = new BufferReader(data); + const count = br.readU32(); for (let i = 0; i < count; i++) this.items.push(UndoCoin.fromReader(br)); @@ -120,7 +120,7 @@ UndoCoins.prototype.isEmpty = function isEmpty() { */ UndoCoins.prototype.commit = function commit() { - let raw = this.toRaw(); + const raw = this.toRaw(); this.items.length = 0; return raw; }; @@ -141,9 +141,9 @@ UndoCoins.prototype.top = function top() { */ UndoCoins.prototype.apply = function apply(view, outpoint) { - let undo = this.items.pop(); - let hash = outpoint.hash; - let index = outpoint.index; + const undo = this.items.pop(); + const hash = outpoint.hash; + const index = outpoint.index; let coins; assert(undo); @@ -263,7 +263,7 @@ UndoCoin.prototype.toWriter = function toWriter(bw) { */ UndoCoin.prototype.toRaw = function toRaw() { - let size = this.getSize(); + const size = this.getSize(); return this.toWriter(new StaticWriter(size)).render(); }; @@ -275,7 +275,7 @@ UndoCoin.prototype.toRaw = function toRaw() { */ UndoCoin.prototype.fromReader = function fromReader(br) { - let code = br.readVarint(); + const code = br.readVarint(); this.output = new Output(); diff --git a/migrate/coinview-old.js b/migrate/coinview-old.js index 87624a540..e9880d0ba 100644 --- a/migrate/coinview-old.js +++ b/migrate/coinview-old.js @@ -62,7 +62,7 @@ CoinView.prototype.addTX = function addTX(tx) { */ CoinView.prototype.get = function get(hash, index) { - let coins = this.coins[hash]; + const coins = this.coins[hash]; if (!coins) return; @@ -78,7 +78,7 @@ CoinView.prototype.get = function get(hash, index) { */ CoinView.prototype.has = function has(hash, index) { - let coins = this.coins[hash]; + const coins = this.coins[hash]; if (!coins) return false; @@ -94,7 +94,7 @@ CoinView.prototype.has = function has(hash, index) { */ CoinView.prototype.spend = function spend(hash, index) { - let coins = this.coins[hash]; + const coins = this.coins[hash]; if (!coins) return; @@ -128,8 +128,8 @@ CoinView.prototype.fillCoins = function fillCoins(tx) { */ CoinView.prototype.toArray = function toArray() { - let keys = Object.keys(this.coins); - let out = []; + const keys = Object.keys(this.coins); + const out = []; let i, hash; for (i = 0; i < keys.length; i++) { diff --git a/migrate/compress-old.js b/migrate/compress-old.js index d32023f4b..1ba95c150 100644 --- a/migrate/compress-old.js +++ b/migrate/compress-old.js @@ -209,7 +209,7 @@ function compressKey(key) { */ function decompressKey(key) { - let format = key[0] >>> 2; + const format = key[0] >>> 2; let out; assert(key.length === 33); diff --git a/migrate/ensure-tip-index.js b/migrate/ensure-tip-index.js index 31e6fdcaa..af7355d59 100644 --- a/migrate/ensure-tip-index.js +++ b/migrate/ensure-tip-index.js @@ -41,9 +41,9 @@ async function checkVersion() { } function entryFromRaw(data) { - let p = new BufferReader(data, true); - let hash = digest.hash256(p.readBytes(80)); - let entry = {}; + const p = new BufferReader(data, true); + const hash = digest.hash256(p.readBytes(80)); + const entry = {}; p.seek(-80); @@ -69,10 +69,10 @@ function getEntries() { } async function getTip(entry) { - let state = await db.get('R'); + const state = await db.get('R'); assert(state); - let tip = state.toString('hex', 0, 32); - let data = await db.get(pair('e', tip)); + const tip = state.toString('hex', 0, 32); + const data = await db.get(pair('e', tip)); assert(data); return entryFromRaw(data); } @@ -90,11 +90,11 @@ async function isMainChain(entry, tip) { // And this insane function is why we should // be indexing tips in the first place! async function indexTips() { - let entries = await getEntries(); + const entries = await getEntries(); let tip = await getTip(); - let tips = []; - let orphans = []; - let prevs = {}; + const tips = []; + const orphans = []; + const prevs = {}; let i, orphan, entry, main; for (i = 0; i < entries.length; i++) { @@ -128,7 +128,7 @@ function write(data, str, off) { } function pair(prefix, hash) { - let key = Buffer.allocUnsafe(33); + const key = Buffer.allocUnsafe(33); if (typeof prefix === 'string') prefix = prefix.charCodeAt(0); key[0] = prefix; diff --git a/migrate/walletdb2to3.js b/migrate/walletdb2to3.js index b7c22a63e..8b65c07dd 100644 --- a/migrate/walletdb2to3.js +++ b/migrate/walletdb2to3.js @@ -10,7 +10,7 @@ const Account = require('../lib/wallet/account'); const Wallet = require('../lib/wallet/wallet'); const BufferReader = require('../lib/utils/reader'); const BufferWriter = require('../lib/utils/writer'); -let layout = walletdb.layout; +const layout = walletdb.layout; let file = process.argv[2]; let db, batch; @@ -28,7 +28,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; + const bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -194,8 +194,8 @@ async function updateTXMap() { } function pathFromRaw(data) { - let path = {}; - let p = new BufferReader(data); + const path = {}; + const p = new BufferReader(data); path.wid = p.readU32(); path.name = p.readVarString('utf8'); @@ -228,8 +228,8 @@ function pathFromRaw(data) { } function parsePaths(data, hash) { - let p = new BufferReader(data); - let out = {}; + const p = new BufferReader(data); + const out = {}; let path; while (p.left()) { @@ -243,15 +243,15 @@ function parsePaths(data, hash) { } function parseWallets(data) { - let p = new BufferReader(data); - let wallets = []; + const p = new BufferReader(data); + const wallets = []; while (p.left()) wallets.push(p.readU32()); return wallets; } function serializeWallets(wallets) { - let p = new BufferWriter(); + const p = new BufferWriter(); let i, wid; for (i = 0; i < wallets.length; i++) { @@ -270,8 +270,8 @@ function readAccountKey(key) { } function accountFromRaw(data, dbkey) { - let account = {}; - let p = new BufferReader(data); + const account = {}; + const p = new BufferReader(data); let i, count, key, name; dbkey = readAccountKey(dbkey); @@ -311,8 +311,8 @@ function accountFromRaw(data, dbkey) { } function walletFromRaw(data) { - let wallet = {}; - let p = new BufferReader(data); + const wallet = {}; + const p = new BufferReader(data); let id; wallet.network = bcoin.network.fromMagic(p.readU32()); @@ -337,8 +337,8 @@ function walletFromRaw(data) { } function keyFromRaw(data, network) { - let ring = {}; - let p = new BufferReader(data); + const ring = {}; + const p = new BufferReader(data); let key, script; ring.network = bcoin.network.get(network); diff --git a/migrate/walletdb3to4.js b/migrate/walletdb3to4.js index ab4297063..135d08921 100644 --- a/migrate/walletdb3to4.js +++ b/migrate/walletdb3to4.js @@ -24,7 +24,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; + const bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -91,8 +91,8 @@ async function updateTXDB() { } function fromExtended(data, saveCoins) { - let tx = new TX(); - let p = BufferReader(data); + const tx = new TX(); + const p = BufferReader(data); let i, coinCount, coin; tx.fromRaw(p); @@ -129,9 +129,9 @@ function fromExtended(data, saveCoins) { } function getValues(map) { - let items = []; + const items = []; - for (let key of Object.keys(map)) + for (const key of Object.keys(map)) items.push(map[key]); return items; diff --git a/migrate/walletdb4to5.js b/migrate/walletdb4to5.js index 760ba34e7..242f3132f 100644 --- a/migrate/walletdb4to5.js +++ b/migrate/walletdb4to5.js @@ -19,7 +19,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; + const bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); diff --git a/migrate/walletdb5to6.js b/migrate/walletdb5to6.js index 371897ba9..b074b39a7 100644 --- a/migrate/walletdb5to6.js +++ b/migrate/walletdb5to6.js @@ -22,7 +22,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; + const bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -129,8 +129,8 @@ async function patchPathMaps() { } function parseWallets(data) { - let p = new BufferReader(data); - let wids = []; + const p = new BufferReader(data); + const wids = []; while (p.left()) wids.push(p.readU32()); @@ -139,7 +139,7 @@ function parseWallets(data) { } function serializeWallets(wids) { - let p = new BufferWriter(); + const p = new BufferWriter(); let i, wid; p.writeU32(wids.length); @@ -153,7 +153,7 @@ function serializeWallets(wids) { } function accountToRaw(account) { - let p = new BufferWriter(); + const p = new BufferWriter(); let i, key; p.writeVarString(account.name, 'ascii'); @@ -179,8 +179,8 @@ function accountToRaw(account) { }; function accountFromRaw(data) { - let account = {}; - let p = new BufferReader(data); + const account = {}; + const p = new BufferReader(data); let i, count, key; account.name = p.readVarString('ascii'); @@ -208,7 +208,7 @@ function accountFromRaw(data) { } function n(wid, index) { - let key = Buffer.allocUnsafe(9); + const key = Buffer.allocUnsafe(9); key[0] = 0x6e; key.writeUInt32BE(wid, 1, true); key.writeUInt32BE(index, 5, true); @@ -216,7 +216,7 @@ function n(wid, index) { } function r(wid, index, hash) { - let key = Buffer.allocUnsafe(1 + 4 + 4 + (hash.length / 2)); + const key = Buffer.allocUnsafe(1 + 4 + 4 + (hash.length / 2)); key[0] = 0x72; key.writeUInt32BE(wid, 1, true); key.writeUInt32BE(index, 5, true); @@ -225,7 +225,7 @@ function r(wid, index, hash) { } async function updateLookahead() { - let WalletDB = require('../lib/wallet/walletdb'); + const WalletDB = require('../lib/wallet/walletdb'); let i, j, db, wallet; db = new WalletDB({ diff --git a/scripts/dump.js b/scripts/dump.js index 1af07baf8..70acc5a64 100644 --- a/scripts/dump.js +++ b/scripts/dump.js @@ -7,16 +7,16 @@ const Coins = require('../lib/coins/coins'); const TX = require('../lib/primitives/tx'); const CoinView = require('../lib/coins/coinview'); -let SNAPSHOT = `${__dirname}/../dump.heapsnapshot`; -let tx = parseTX('../test/data/tx4.hex'); +const SNAPSHOT = `${__dirname}/../dump.heapsnapshot`; +const tx = parseTX('../test/data/tx4.hex'); let raw, coins, entry; function parseTX(file) { - let data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); - let parts = data.trim().split(/\n+/); + const data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); + const parts = data.trim().split(/\n+/); let raw = parts[0]; - let tx = TX.fromRaw(raw.trim(), 'hex'); - let view = new CoinView(); + const tx = TX.fromRaw(raw.trim(), 'hex'); + const view = new CoinView(); let i, prev; for (i = 1; i < parts.length; i++) { diff --git a/scripts/fuzz.js b/scripts/fuzz.js index 88fc35086..2a3b3288f 100644 --- a/scripts/fuzz.js +++ b/scripts/fuzz.js @@ -15,12 +15,12 @@ const MANDATORY = Script.flags.MANDATORY_VERIFY_FLAGS | Script.flags.VERIFY_WITN const STANDARD = Script.flags.STANDARD_VERIFY_FLAGS; function randomOutpoint() { - let hash = random.randomBytes(32).toString('hex'); + const hash = random.randomBytes(32).toString('hex'); return new Outpoint(hash, util.random(0, 0xffffffff)); } function randomInput() { - let input = Input.fromOutpoint(randomOutpoint()); + const input = Input.fromOutpoint(randomOutpoint()); if (util.random(0, 5) === 0) input.sequence = util.random(0, 0xffffffff); @@ -33,9 +33,9 @@ function randomOutput() { } function randomTX() { - let tx = new TX(); - let inputs = util.random(1, 5); - let outputs = util.random(0, 5); + const tx = new TX(); + const inputs = util.random(1, 5); + const outputs = util.random(0, 5); let i; tx.version = util.random(0, 0xffffffff); @@ -55,8 +55,8 @@ function randomTX() { } function randomWitness(redeem) { - let size = util.random(1, 100); - let witness = new Witness(); + const size = util.random(1, 100); + const witness = new Witness(); let i, len; for (i = 0; i < size; i++) { @@ -73,8 +73,8 @@ function randomWitness(redeem) { } function randomInputScript(redeem) { - let size = util.random(1, 100); - let script = new Script(); + const size = util.random(1, 100); + const script = new Script(); let i, len; for (i = 0; i < size; i++) { @@ -91,7 +91,7 @@ function randomInputScript(redeem) { } function randomOutputScript() { - let size = util.random(1, 10000); + const size = util.random(1, 10000); return Script.fromRaw(random.randomBytes(size)); } @@ -120,7 +120,7 @@ function isPushOnly(script) { } function randomPubkey() { - let len = util.random(0, 2) === 0 ? 33 : 65; + const len = util.random(0, 2) === 0 ? 33 : 65; return Script.fromPubkey(random.randomBytes(len)); } @@ -129,9 +129,9 @@ function randomPubkeyhash() { } function randomMultisig() { - let n = util.random(1, 16); - let m = util.random(1, n); - let keys = []; + const n = util.random(1, 16); + const m = util.random(1, n); + const keys = []; let i, len; for (i = 0; i < n; i++) { @@ -155,8 +155,8 @@ function randomWitnessScripthash() { } function randomProgram() { - let version = util.random(0, 16); - let size = util.random(2, 41); + const version = util.random(0, 16); + const size = util.random(2, 41); return Script.fromProgram(version, random.randomBytes(size)); } @@ -215,7 +215,7 @@ function randomPubkeyhashContext() { } function randomScripthashContext() { - let redeem = randomRedeem(); + const redeem = randomRedeem(); return { input: randomInputScript(redeem.toRaw()), witness: new Witness(), @@ -234,7 +234,7 @@ function randomWitnessPubkeyhashContext() { } function randomWitnessScripthashContext() { - let redeem = randomRedeem(); + const redeem = randomRedeem(); return { input: new Script(), witness: randomWitness(redeem.toRaw()), @@ -244,8 +244,8 @@ function randomWitnessScripthashContext() { } function randomWitnessNestedContext() { - let redeem = randomRedeem(); - let program = Script.fromProgram(0, redeem.sha256()); + const redeem = randomRedeem(); + const program = Script.fromProgram(0, redeem.sha256()); return { input: new Script([program.toRaw()]), witness: randomWitness(redeem.toRaw()), @@ -430,7 +430,7 @@ function fuzzLess(flags) { } function main() { - let flags = process.argv.indexOf('--standard') !== -1 ? STANDARD : MANDATORY; + const flags = process.argv.indexOf('--standard') !== -1 ? STANDARD : MANDATORY; switch (process.argv[2]) { case 'simple': diff --git a/test/aes-test.js b/test/aes-test.js index 5817d9c80..ebbfd4519 100644 --- a/test/aes-test.js +++ b/test/aes-test.js @@ -8,7 +8,7 @@ const nativeCrypto = require('crypto'); describe('AES', function() { function pbkdf2key(passphrase, iterations, dkLen, ivLen, alg) { - let key = pbkdf2.derive(passphrase, '', iterations, dkLen + ivLen, 'sha512'); + const key = pbkdf2.derive(passphrase, '', iterations, dkLen + ivLen, 'sha512'); return { key: key.slice(0, dkLen), iv: key.slice(dkLen, dkLen + ivLen) @@ -124,17 +124,17 @@ describe('AES', function() { } it('should encrypt and decrypt a hash with 2 blocks', () => { - let hash = digest.sha256(Buffer.alloc(0)); - let enchash = encrypt(hash, 'foo'); - let dechash = decrypt(enchash, 'foo'); + const hash = digest.sha256(Buffer.alloc(0)); + const enchash = encrypt(hash, 'foo'); + const dechash = decrypt(enchash, 'foo'); - let hash2 = digest.sha256(Buffer.alloc(0)); - let enchash2 = nencrypt(hash2, 'foo'); - let dechash2 = ndecrypt(enchash2, 'foo'); + const hash2 = digest.sha256(Buffer.alloc(0)); + const enchash2 = nencrypt(hash2, 'foo'); + const dechash2 = ndecrypt(enchash2, 'foo'); - let hash3 = digest.sha256(Buffer.alloc(0)); - let enchash3 = bencrypt(hash3, 'foo'); - let dechash3 = bdecrypt(enchash3, 'foo'); + const hash3 = digest.sha256(Buffer.alloc(0)); + const enchash3 = bencrypt(hash3, 'foo'); + const dechash3 = bdecrypt(enchash3, 'foo'); assert.deepEqual(hash, hash2); assert.deepEqual(enchash, enchash2); @@ -143,13 +143,13 @@ describe('AES', function() { }); it('should encrypt and decrypt a hash with uneven blocks', () => { - let hash = Buffer.concat([digest.sha256(Buffer.alloc(0)), Buffer.from([1,2,3])]); - let enchash = encrypt(hash, 'foo'); - let dechash = decrypt(enchash, 'foo'); + const hash = Buffer.concat([digest.sha256(Buffer.alloc(0)), Buffer.from([1,2,3])]); + const enchash = encrypt(hash, 'foo'); + const dechash = decrypt(enchash, 'foo'); - let hash2 = Buffer.concat([digest.sha256(Buffer.alloc(0)), Buffer.from([1,2,3])]); - let enchash2 = nencrypt(hash2, 'foo'); - let dechash2 = ndecrypt(enchash2, 'foo'); + const hash2 = Buffer.concat([digest.sha256(Buffer.alloc(0)), Buffer.from([1,2,3])]); + const enchash2 = nencrypt(hash2, 'foo'); + const dechash2 = ndecrypt(enchash2, 'foo'); assert.deepEqual(hash, hash2); assert.deepEqual(enchash, enchash2); diff --git a/test/bech32-test.js b/test/bech32-test.js index a50a28551..bceebabbe 100644 --- a/test/bech32-test.js +++ b/test/bech32-test.js @@ -99,7 +99,7 @@ describe('Bech32', function() { ]; function fromAddress(hrp, addr) { - let dec = bech32.decode(addr); + const dec = bech32.decode(addr); if (dec.hrp !== hrp) throw new Error('Invalid bech32 prefix or data length.'); @@ -114,7 +114,7 @@ describe('Bech32', function() { } function toAddress(hrp, version, program) { - let ret = bech32.encode(hrp, version, program); + const ret = bech32.encode(hrp, version, program); fromAddress(hrp, ret); @@ -122,20 +122,20 @@ describe('Bech32', function() { } function createProgram(version, program) { - let ver = Buffer.from([version ? version + 0x80 : 0, program.length]); + const ver = Buffer.from([version ? version + 0x80 : 0, program.length]); return Buffer.concat([ver, program]); } VALID_CHECKSUM.forEach((test) => { it(`should have valid checksum for ${test}`, () => { - let ret = bech32.deserialize(test); + const ret = bech32.deserialize(test); assert(ret); }); }); VALID_ADDRESS.forEach((test) => { - let address = test[0]; - let scriptpubkey = test[1]; + const address = test[0]; + const scriptpubkey = test[1]; it(`should have valid address for ${address}`, () => { let hrp = 'bc'; let ret, ok, output, recreate; @@ -193,8 +193,8 @@ describe('Bech32', function() { }); VALID_ADDRESS.forEach((test, i) => { - let address = test[0]; - let scriptpubkey = test[1]; + const address = test[0]; + const scriptpubkey = test[1]; // TODO: Fix. (wrong length for program) // Need to drop old segwit addrs. diff --git a/test/bip150-test.js b/test/bip150-test.js index d816f5677..ba5fc0a98 100644 --- a/test/bip150-test.js +++ b/test/bip150-test.js @@ -6,15 +6,15 @@ const BIP150 = require('../lib/net/bip150'); const BIP151 = require('../lib/net/bip151'); describe('BIP150', function() { - let db = new BIP150.AuthDB(); - let ck = secp256k1.generatePrivateKey(); - let sk = secp256k1.generatePrivateKey(); + const db = new BIP150.AuthDB(); + const ck = secp256k1.generatePrivateKey(); + const sk = secp256k1.generatePrivateKey(); db.addAuthorized(secp256k1.publicKeyCreate(ck, true)); db.addKnown('127.0.0.2', secp256k1.publicKeyCreate(sk, true)); - let client = new BIP151(); - let server = new BIP151(); + const client = new BIP151(); + const server = new BIP151(); client.bip150 = new BIP150(client, '127.0.0.2', true, db, ck); server.bip150 = new BIP150(server, '127.0.0.1', false, db, sk); @@ -64,7 +64,7 @@ describe('BIP150', function() { }); it('should encrypt payload from client to server', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -76,7 +76,7 @@ describe('BIP150', function() { }); it('should encrypt payload from server to client', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -88,7 +88,7 @@ describe('BIP150', function() { }); it('should encrypt payload from client to server (2)', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -100,7 +100,7 @@ describe('BIP150', function() { }); it('should encrypt payload from server to client (2)', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -113,11 +113,11 @@ describe('BIP150', function() { it('client should rekey', () => { let rekeyed = false; - let bytes = client.output.processed; + const bytes = client.output.processed; client.once('rekey', () => { rekeyed = true; - let packet = client.packet('encack', client.toRekey().toRaw()); + const packet = client.packet('encack', client.toRekey().toRaw()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -139,7 +139,7 @@ describe('BIP150', function() { }); it('should encrypt payload from client to server after rekey', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -151,7 +151,7 @@ describe('BIP150', function() { }); it('should encrypt payload from server to client after rekey', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -163,7 +163,7 @@ describe('BIP150', function() { }); it('should encrypt payload from client to server after rekey (2)', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -175,7 +175,7 @@ describe('BIP150', function() { }); it('should encrypt payload from server to client after rekey (2)', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -187,8 +187,8 @@ describe('BIP150', function() { }); it('should encrypt payloads both ways asynchronously', () => { - let spacket = server.packet('fake', payload()); - let cpacket = client.packet('fake', payload()); + const spacket = server.packet('fake', payload()); + const cpacket = client.packet('fake', payload()); let cemitted = false; let semitted = false; client.once('packet', (cmd, body) => { diff --git a/test/bip151-test.js b/test/bip151-test.js index 637717088..9c76d8683 100644 --- a/test/bip151-test.js +++ b/test/bip151-test.js @@ -4,8 +4,8 @@ const assert = require('assert'); const BIP151 = require('../lib/net/bip151'); describe('BIP151', function() { - let client = new BIP151(); - let server = new BIP151(); + const client = new BIP151(); + const server = new BIP151(); function payload() { return Buffer.from('deadbeef', 'hex'); @@ -37,7 +37,7 @@ describe('BIP151', function() { }); it('should encrypt payload from client to server', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -49,7 +49,7 @@ describe('BIP151', function() { }); it('should encrypt payload from server to client', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -61,7 +61,7 @@ describe('BIP151', function() { }); it('should encrypt payload from client to server (2)', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -73,7 +73,7 @@ describe('BIP151', function() { }); it('should encrypt payload from server to client (2)', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -86,11 +86,11 @@ describe('BIP151', function() { it('client should rekey', () => { let rekeyed = false; - let bytes = client.output.processed; + const bytes = client.output.processed; client.once('rekey', () => { rekeyed = true; - let packet = client.packet('encack', client.toRekey().toRaw()); + const packet = client.packet('encack', client.toRekey().toRaw()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -112,7 +112,7 @@ describe('BIP151', function() { }); it('should encrypt payload from client to server after rekey', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -124,7 +124,7 @@ describe('BIP151', function() { }); it('should encrypt payload from server to client after rekey', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -136,7 +136,7 @@ describe('BIP151', function() { }); it('should encrypt payload from client to server after rekey (2)', () => { - let packet = client.packet('fake', payload()); + const packet = client.packet('fake', payload()); let emitted = false; server.once('packet', (cmd, body) => { emitted = true; @@ -148,7 +148,7 @@ describe('BIP151', function() { }); it('should encrypt payload from server to client after rekey (2)', () => { - let packet = server.packet('fake', payload()); + const packet = server.packet('fake', payload()); let emitted = false; client.once('packet', (cmd, body) => { emitted = true; @@ -160,8 +160,8 @@ describe('BIP151', function() { }); it('should encrypt payloads both ways asynchronously', () => { - let spacket = server.packet('fake', payload()); - let cpacket = client.packet('fake', payload()); + const spacket = server.packet('fake', payload()); + const cpacket = client.packet('fake', payload()); let cemitted = false; let semitted = false; client.once('packet', (cmd, body) => { diff --git a/test/bip70-test.js b/test/bip70-test.js index 40a947a90..19d785b7a 100644 --- a/test/bip70-test.js +++ b/test/bip70-test.js @@ -23,7 +23,7 @@ x509.trusted.clear(); describe('BIP70', function() { function testRequest(data) { - let request = bip70.PaymentRequest.fromRaw(data); + const request = bip70.PaymentRequest.fromRaw(data); let ser; assert.equal(request.pkiType, 'x509+sha256'); @@ -126,12 +126,12 @@ describe('BIP70', function() { }); it('should still fail to verify cert signatures for invalid', () => { - let request = bip70.PaymentRequest.fromRaw(tests.invalid); + const request = bip70.PaymentRequest.fromRaw(tests.invalid); assert(!request.verifyChain()); }); it('should get chain and ca for request', () => { - let request = bip70.PaymentRequest.fromRaw(tests.valid); + const request = bip70.PaymentRequest.fromRaw(tests.valid); assert.equal(request.getChain().length, 4); assert.equal(request.getCA().name, 'Go Daddy Class 2 Certification Authority'); @@ -148,7 +148,7 @@ describe('BIP70', function() { }); it('should parse a payment ack', () => { - let ack = bip70.PaymentACK.fromRaw(tests.ack); + const ack = bip70.PaymentACK.fromRaw(tests.ack); assert.equal(ack.memo.length, 95); assert.equal(ack.memo, 'Transaction received by BitPay.' + ' Invoice will be marked as paid if the transaction is confirmed.'); @@ -156,7 +156,7 @@ describe('BIP70', function() { }); it('should create a payment request, sign, and verify', () => { - let request = new bip70.PaymentRequest({ + const request = new bip70.PaymentRequest({ version: 25, paymentDetails: { network: 'testnet', diff --git a/test/block-test.js b/test/block-test.js index d3c82d716..b0b841bc0 100644 --- a/test/block-test.js +++ b/test/block-test.js @@ -25,11 +25,11 @@ cmpct1 = cmpct1.trim().split('\n'); cmpct2 = cmpct2.trim(); function parseUndo(data) { - let br = new BufferReader(data); - let undo = []; + const br = new BufferReader(data); + const undo = []; while (br.left()) { - let output = Output.fromReader(br); + const output = Output.fromReader(br); undo.push(output); } @@ -37,14 +37,14 @@ function parseUndo(data) { } function applyUndo(block, undo) { - let view = new CoinView(); + const view = new CoinView(); let i = 0; - for (let tx of block.txs) { + for (const tx of block.txs) { if (tx.isCoinbase()) continue; - for (let {prevout} of tx.inputs) + for (const {prevout} of tx.inputs) view.addOutput(prevout, undo[i++]); } @@ -121,26 +121,26 @@ describe('Block', function() { }); it('should decode/encode with parser/framer', () => { - let b = MerkleBlock.fromRaw(raw, 'hex'); + const b = MerkleBlock.fromRaw(raw, 'hex'); assert.equal(b.toRaw().toString('hex'), raw); assert.equal(raw, raw2); }); it('should be verifiable', () => { - let b = MerkleBlock.fromRaw(raw, 'hex'); + const b = MerkleBlock.fromRaw(raw, 'hex'); assert(b.verify()); }); it('should be serialized and deserialized and still verify', () => { - let raw = mblock.toRaw(); - let b = MerkleBlock.fromRaw(raw); + const raw = mblock.toRaw(); + const b = MerkleBlock.fromRaw(raw); assert.deepEqual(b.toRaw(), raw); assert(b.verify()); }); it('should be jsonified and unjsonified and still verify', () => { - let raw = mblock.toJSON(); - let b = MerkleBlock.fromJSON(raw); + const raw = mblock.toJSON(); + const b = MerkleBlock.fromJSON(raw); assert.deepEqual(b.toJSON(), raw); assert(b.verify()); }); @@ -150,7 +150,7 @@ describe('Block', function() { let total = 0; for (;;) { - let reward = consensus.getReward(height, 210000); + const reward = consensus.getReward(height, 210000); assert(reward <= consensus.COIN * 50); total += reward; if (reward === 0) @@ -191,17 +191,17 @@ describe('Block', function() { }); it('should verify a historical block', () => { - let view = new CoinView(); - let height = block300025.height; + const view = new CoinView(); + const height = block300025.height; let sigops = 0; let reward = 0; let flags; for (let i = 1; i < block300025.txs.length; i++) { - let tx = block300025.txs[i]; + const tx = block300025.txs[i]; for (let j = 0; j < tx.inputs.length; j++) { - let input = tx.inputs[j]; - let coin = Coin.fromJSON(input.coin); + const input = tx.inputs[j]; + const coin = Coin.fromJSON(input.coin); view.addCoin(coin); } } @@ -215,7 +215,7 @@ describe('Block', function() { flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG; for (let i = 1; i < block.txs.length; i++) { - let tx = block.txs[i]; + const tx = block.txs[i]; assert(tx.isSane()); assert(tx.verifyInputs(view, height)); assert(tx.verify(view, flags)); @@ -233,7 +233,7 @@ describe('Block', function() { }); it('should fail with a bad merkle root', () => { - let block2 = new Block(block); + const block2 = new Block(block); let reason; block2.merkleRoot = encoding.NULL_HASH; block2.refresh(); @@ -247,7 +247,7 @@ describe('Block', function() { }); it('should fail on merkle block with a bad merkle root', () => { - let mblock2 = new MerkleBlock(mblock); + const mblock2 = new MerkleBlock(mblock); let reason; mblock2.merkleRoot = encoding.NULL_HASH; mblock2.refresh(); @@ -261,7 +261,7 @@ describe('Block', function() { }); it('should fail with a low target', () => { - let block2 = new Block(block); + const block2 = new Block(block); block2.bits = 403014710; block2.refresh(); assert(!block2.verifyPOW()); @@ -273,7 +273,7 @@ describe('Block', function() { }); it('should fail on duplicate txs', () => { - let block2 = new Block(block); + const block2 = new Block(block); let reason; block2.txs.push(block2.txs[block2.txs.length - 1]); block2.refresh(); @@ -282,17 +282,17 @@ describe('Block', function() { }); it('should verify with headers', () => { - let headers = new Headers(block); + const headers = new Headers(block); assert(headers.verifyPOW()); assert(headers.verifyBody()); assert(headers.verify()); }); it('should handle compact block', () => { - let block = Block.fromRaw(cmpct1[1], 'hex'); - let cblock1 = bip152.CompactBlock.fromRaw(cmpct1[0], 'hex'); - let cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); - let map = new Map(); + const block = Block.fromRaw(cmpct1[1], 'hex'); + const cblock1 = bip152.CompactBlock.fromRaw(cmpct1[0], 'hex'); + const cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); + const map = new Map(); let i, tx, mempool, result; assert(cblock1.init()); @@ -323,10 +323,10 @@ describe('Block', function() { }); it('should handle half-full compact block', () => { - let block = Block.fromRaw(cmpct1[1], 'hex'); - let cblock1 = bip152.CompactBlock.fromRaw(cmpct1[0], 'hex'); - let cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); - let map = new Map(); + const block = Block.fromRaw(cmpct1[1], 'hex'); + const cblock1 = bip152.CompactBlock.fromRaw(cmpct1[0], 'hex'); + const cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); + const map = new Map(); let i, tx, mempool, result, req, res; assert(cblock1.init()); @@ -371,10 +371,10 @@ describe('Block', function() { }); it('should handle compact block', () => { - let block = Block.fromRaw(cmpct2block); - let cblock1 = bip152.CompactBlock.fromRaw(cmpct2, 'hex'); - let cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); - let map = new Map(); + const block = Block.fromRaw(cmpct2block); + const cblock1 = bip152.CompactBlock.fromRaw(cmpct2, 'hex'); + const cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); + const map = new Map(); let i, tx, result, mempool; assert(cblock1.init()); @@ -403,10 +403,10 @@ describe('Block', function() { }); it('should handle half-full compact block', () => { - let block = Block.fromRaw(cmpct2block); - let cblock1 = bip152.CompactBlock.fromRaw(cmpct2, 'hex'); - let cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); - let map = new Map(); + const block = Block.fromRaw(cmpct2block); + const cblock1 = bip152.CompactBlock.fromRaw(cmpct2, 'hex'); + const cblock2 = bip152.CompactBlock.fromBlock(block, false, cblock1.keyNonce); + const map = new Map(); let i, tx, mempool, result, req, res; assert(cblock1.init()); @@ -447,13 +447,13 @@ describe('Block', function() { }); it('should count sigops for block 928828 (testnet)', async () => { - let blockRaw = await fs.readFile(`${__dirname}/data/block928828.raw`); - let undoRaw = await fs.readFile(`${__dirname}/data/undo928828.raw`); - let block = Block.fromRaw(blockRaw); - let undo = parseUndo(undoRaw); - let view = applyUndo(block, undo); + const blockRaw = await fs.readFile(`${__dirname}/data/block928828.raw`); + const undoRaw = await fs.readFile(`${__dirname}/data/undo928828.raw`); + const block = Block.fromRaw(blockRaw); + const undo = parseUndo(undoRaw); + const view = applyUndo(block, undo); let sigops = 0; - let flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; + const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; let i, tx; for (i = 0; i < block.txs.length; i++) { @@ -466,13 +466,13 @@ describe('Block', function() { }); it('should count sigops for block 928927 (testnet)', async () => { - let blockRaw = await fs.readFile(`${__dirname}/data/block928927.raw`); - let undoRaw = await fs.readFile(`${__dirname}/data/undo928927.raw`); - let block = Block.fromRaw(blockRaw); - let undo = parseUndo(undoRaw); - let view = applyUndo(block, undo); + const blockRaw = await fs.readFile(`${__dirname}/data/block928927.raw`); + const undoRaw = await fs.readFile(`${__dirname}/data/undo928927.raw`); + const block = Block.fromRaw(blockRaw); + const undo = parseUndo(undoRaw); + const view = applyUndo(block, undo); let sigops = 0; - let flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; + const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; let i, tx; for (i = 0; i < block.txs.length; i++) { @@ -485,13 +485,13 @@ describe('Block', function() { }); it('should count sigops for block 1087400 (testnet)', async () => { - let blockRaw = await fs.readFile(`${__dirname}/data/block1087400.raw`); - let undoRaw = await fs.readFile(`${__dirname}/data/undo1087400.raw`); - let block = Block.fromRaw(blockRaw); - let undo = parseUndo(undoRaw); - let view = applyUndo(block, undo); + const blockRaw = await fs.readFile(`${__dirname}/data/block1087400.raw`); + const undoRaw = await fs.readFile(`${__dirname}/data/undo1087400.raw`); + const block = Block.fromRaw(blockRaw); + const undo = parseUndo(undoRaw); + const view = applyUndo(block, undo); let sigops = 0; - let flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; + const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_WITNESS; let i, tx; for (i = 0; i < block.txs.length; i++) { diff --git a/test/bloom-test.js b/test/bloom-test.js index 08efc5dc2..141a77a9b 100644 --- a/test/bloom-test.js +++ b/test/bloom-test.js @@ -43,7 +43,7 @@ describe('Bloom', function() { }); it('should test and add stuff', () => { - let b = new Bloom(512, 10, 156); + const b = new Bloom(512, 10, 156); b.add('hello', 'ascii'); assert(b.test('hello', 'ascii')); @@ -59,9 +59,9 @@ describe('Bloom', function() { }); it('should serialize to the correct format', () => { - let filter = new Bloom(952, 6, 3624314491, Bloom.flags.NONE); - let item1 = '8e7445bbb8abd4b3174d80fa4c409fea6b94d96b'; - let item2 = '047b00000078da0dca3b0ec2300c00d0ab4466ed10' + const filter = new Bloom(952, 6, 3624314491, Bloom.flags.NONE); + const item1 = '8e7445bbb8abd4b3174d80fa4c409fea6b94d96b'; + const item2 = '047b00000078da0dca3b0ec2300c00d0ab4466ed10' + 'e763272c6c9ca052972c69e3884a9022084215e2eef' + '0e6f781656b5d5a87231cd4349e534b6dea55ad4ff55e'; filter.add(item1, 'hex'); @@ -70,7 +70,7 @@ describe('Bloom', function() { }); it('should handle 1m ops with regular filter', () => { - let filter = Bloom.fromRate(210000, 0.00001, -1); + const filter = Bloom.fromRate(210000, 0.00001, -1); let i, j, str; filter.tweak = 0xdeadbeef; @@ -89,7 +89,7 @@ describe('Bloom', function() { }); it('should handle 1m ops with rolling filter', () => { - let filter = new RollingFilter(210000, 0.00001); + const filter = new RollingFilter(210000, 0.00001); let i, j, str; filter.tweak = 0xdeadbeef; @@ -108,7 +108,7 @@ describe('Bloom', function() { }); it('should handle rolling generations', () => { - let filter = new RollingFilter(50, 0.00001); + const filter = new RollingFilter(50, 0.00001); let i, j, str; filter.tweak = 0xdeadbeee; diff --git a/test/chachapoly-test.js b/test/chachapoly-test.js index 5399e3474..2072056a5 100644 --- a/test/chachapoly-test.js +++ b/test/chachapoly-test.js @@ -11,7 +11,7 @@ describe('ChaCha20 / Poly1305 / AEAD', function() { let nonce = options.nonce; let plain = options.plain; let ciphertext = options.ciphertext; - let counter = options.counter; + const counter = options.counter; let chacha, plainenc; key = Buffer.from(key, 'hex'); @@ -159,9 +159,9 @@ describe('ChaCha20 / Poly1305 / AEAD', function() { }); it('should perform poly1305', () => { - let expected = Buffer.from('ddb9da7ddd5e52792730ed5cda5f90a4', 'hex'); - let key = Buffer.allocUnsafe(32); - let msg = Buffer.allocUnsafe(73); + const expected = Buffer.from('ddb9da7ddd5e52792730ed5cda5f90a4', 'hex'); + const key = Buffer.allocUnsafe(32); + const msg = Buffer.allocUnsafe(73); let mac; let i; diff --git a/test/chain-test.js b/test/chain-test.js index 549734a8f..27a41f092 100644 --- a/test/chain-test.js +++ b/test/chain-test.js @@ -43,12 +43,12 @@ describe('Chain', function() { } async function mineBlock(job, flags) { - let block = await job.mineAsync(); + const block = await job.mineAsync(); return await addBlock(block, flags); } async function mineCSV(tx) { - let job = await cpu.createJob(); + const job = await cpu.createJob(); let rtx; rtx = new MTX(); @@ -189,12 +189,12 @@ describe('Chain', function() { }); it('should check main chain', async () => { - let result = await tip1.isMainChain(); + const result = await tip1.isMainChain(); assert(!result); }); it('should mine a block after a reorg', async () => { - let block = await cpu.mineBlock(); + const block = await cpu.mineBlock(); let hash, entry, result; assert(await chain.add(block)); @@ -239,9 +239,9 @@ describe('Chain', function() { }); it('should fail to connect coins on an alternate chain', async () => { - let block = await chain.db.getBlock(tip1.hash); - let cb = block.txs[0]; - let mtx = new MTX(); + const block = await chain.db.getBlock(tip1.hash); + const cb = block.txs[0]; + const mtx = new MTX(); let job; mtx.addTX(cb, 0); @@ -330,7 +330,7 @@ describe('Chain', function() { }); it('should activate csv', async () => { - let deployments = network.deployments; + const deployments = network.deployments; let i, block, prev, state, cache; miner.options.version = -1; @@ -374,14 +374,14 @@ describe('Chain', function() { }); it('should have activated segwit', async () => { - let deployments = network.deployments; - let prev = await chain.tip.getPrevious(); - let state = await chain.getState(prev, deployments.segwit); + const deployments = network.deployments; + const prev = await chain.tip.getPrevious(); + const state = await chain.getState(prev, deployments.segwit); assert.equal(state, 3); }); it('should test csv', async () => { - let tx = (await chain.db.getBlock(chain.height - 100)).txs[0]; + const tx = (await chain.db.getBlock(chain.height - 100)).txs[0]; let block = await mineCSV(tx); let csv, job, rtx; @@ -413,8 +413,8 @@ describe('Chain', function() { }); it('should fail csv with bad sequence', async () => { - let csv = (await chain.db.getBlock(chain.height - 100)).txs[0]; - let rtx = new MTX(); + const csv = (await chain.db.getBlock(chain.height - 100)).txs[0]; + const rtx = new MTX(); let job; rtx.addOutput({ @@ -436,14 +436,14 @@ describe('Chain', function() { }); it('should mine a block', async () => { - let block = await cpu.mineBlock(); + const block = await cpu.mineBlock(); assert(block); assert(await chain.add(block)); }); it('should fail csv lock checks', async () => { - let tx = (await chain.db.getBlock(chain.height - 100)).txs[0]; - let block = await mineCSV(tx); + const tx = (await chain.db.getBlock(chain.height - 100)).txs[0]; + const block = await mineCSV(tx); let csv, job, rtx; assert(await chain.add(block)); @@ -475,36 +475,36 @@ describe('Chain', function() { }); it('should fail to connect bad bits', async () => { - let job = await cpu.createJob(); + const job = await cpu.createJob(); job.attempt.bits = 553713663; assert.equal(await mineBlock(job), 'bad-diffbits'); }); it('should fail to connect bad MTP', async () => { - let mtp = await chain.tip.getMedianTime(); - let job = await cpu.createJob(); + const mtp = await chain.tip.getMedianTime(); + const job = await cpu.createJob(); job.attempt.time = mtp - 1; assert.equal(await mineBlock(job), 'time-too-old'); }); it('should fail to connect bad time', async () => { - let job = await cpu.createJob(); - let now = network.now() + 3 * 60 * 60; + const job = await cpu.createJob(); + const now = network.now() + 3 * 60 * 60; job.attempt.time = now; assert.equal(await mineBlock(job), 'time-too-new'); }); it('should fail to connect bad locktime', async () => { - let job = await cpu.createJob(); - let tx = await wallet.send({ locktime: 100000 }); + const job = await cpu.createJob(); + const tx = await wallet.send({ locktime: 100000 }); job.pushTX(tx.toTX()); job.refresh(); assert.equal(await mineBlock(job), 'bad-txns-nonfinal'); }); it('should fail to connect bad cb height', async () => { - let bip34height = network.block.bip34height; - let job = await cpu.createJob(); + const bip34height = network.block.bip34height; + const job = await cpu.createJob(); job.attempt.height = 10; job.attempt.refresh(); @@ -518,9 +518,9 @@ describe('Chain', function() { }); it('should fail to connect bad witness nonce size', async () => { - let block = await cpu.mineBlock(); - let tx = block.txs[0]; - let input = tx.inputs[0]; + const block = await cpu.mineBlock(); + const tx = block.txs[0]; + const input = tx.inputs[0]; input.witness.set(0, Buffer.allocUnsafe(33)); input.witness.compile(); block.refresh(true); @@ -528,9 +528,9 @@ describe('Chain', function() { }); it('should fail to connect bad witness nonce', async () => { - let block = await cpu.mineBlock(); - let tx = block.txs[0]; - let input = tx.inputs[0]; + const block = await cpu.mineBlock(); + const tx = block.txs[0]; + const input = tx.inputs[0]; input.witness.set(0, encoding.ONE_HASH); input.witness.compile(); block.refresh(true); @@ -538,10 +538,10 @@ describe('Chain', function() { }); it('should fail to connect bad witness commitment', async () => { - let flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; - let block = await cpu.mineBlock(); - let tx = block.txs[0]; - let output = tx.outputs[1]; + const flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; + const block = await cpu.mineBlock(); + const tx = block.txs[0]; + const output = tx.outputs[1]; let commit; assert(output.script.isCommitment()); @@ -558,10 +558,10 @@ describe('Chain', function() { }); it('should fail to connect unexpected witness', async () => { - let flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; - let block = await cpu.mineBlock(); - let tx = block.txs[0]; - let output = tx.outputs[1]; + const flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; + const block = await cpu.mineBlock(); + const tx = block.txs[0]; + const output = tx.outputs[1]; assert(output.script.isCommitment()); @@ -593,8 +593,8 @@ describe('Chain', function() { it('should mine a witness tx', async () => { let block = await chain.db.getBlock(chain.height - 2000); - let cb = block.txs[0]; - let mtx = new MTX(); + const cb = block.txs[0]; + const mtx = new MTX(); let job; mtx.addTX(cb, 0); @@ -612,9 +612,9 @@ describe('Chain', function() { }); it('should mine fail to connect too much weight', async () => { - let start = chain.height - 2000; - let end = chain.height - 200; - let job = await cpu.createJob(); + const start = chain.height - 2000; + const end = chain.height - 200; + const job = await cpu.createJob(); let mtx = new MTX(); let i, j, block, cb; @@ -639,9 +639,9 @@ describe('Chain', function() { }); it('should mine fail to connect too much size', async () => { - let start = chain.height - 2000; - let end = chain.height - 200; - let job = await cpu.createJob(); + const start = chain.height - 2000; + const end = chain.height - 200; + const job = await cpu.createJob(); let mtx = new MTX(); let i, j, block, cb; @@ -666,9 +666,9 @@ describe('Chain', function() { }); it('should mine a big block', async () => { - let start = chain.height - 2000; - let end = chain.height - 200; - let job = await cpu.createJob(); + const start = chain.height - 2000; + const end = chain.height - 200; + const job = await cpu.createJob(); let mtx = new MTX(); let i, j, block, cb; @@ -703,7 +703,7 @@ describe('Chain', function() { }); it('should fail to connect bad amount', async () => { - let job = await cpu.createJob(); + const job = await cpu.createJob(); job.attempt.fees += 1; job.refresh(); @@ -711,10 +711,10 @@ describe('Chain', function() { }); it('should fail to connect premature cb spend', async () => { - let job = await cpu.createJob(); - let block = await chain.db.getBlock(chain.height - 98); - let cb = block.txs[0]; - let mtx = new MTX(); + const job = await cpu.createJob(); + const block = await chain.db.getBlock(chain.height - 98); + const cb = block.txs[0]; + const mtx = new MTX(); mtx.addTX(cb, 0); mtx.addOutput(wwallet.getAddress(), 1); @@ -729,10 +729,10 @@ describe('Chain', function() { }); it('should fail to connect vout belowout', async () => { - let job = await cpu.createJob(); - let block = await chain.db.getBlock(chain.height - 99); - let cb = block.txs[0]; - let mtx = new MTX(); + const job = await cpu.createJob(); + const block = await chain.db.getBlock(chain.height - 99); + const cb = block.txs[0]; + const mtx = new MTX(); mtx.addTX(cb, 0); mtx.addOutput(wwallet.getAddress(), 1e8); @@ -747,10 +747,10 @@ describe('Chain', function() { }); it('should fail to connect outtotal toolarge', async () => { - let job = await cpu.createJob(); - let block = await chain.db.getBlock(chain.height - 99); - let cb = block.txs[0]; - let mtx = new MTX(); + const job = await cpu.createJob(); + const block = await chain.db.getBlock(chain.height - 99); + const cb = block.txs[0]; + const mtx = new MTX(); mtx.addTX(cb, 0); mtx.addOutput(wwallet.getAddress(), Math.floor(consensus.MAX_MONEY / 2)); @@ -767,7 +767,7 @@ describe('Chain', function() { }); it('should mine 111 multisig blocks', async () => { - let flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; + const flags = common.flags.DEFAULT_FLAGS & ~common.flags.VERIFY_POW; let i, j, script, cb, output, val, block; script = new Script(); @@ -807,9 +807,9 @@ describe('Chain', function() { }); it('should fail to connect too many sigops', async () => { - let start = chain.height - 110; - let end = chain.height - 100; - let job = await cpu.createJob(); + const start = chain.height - 110; + const end = chain.height - 100; + const job = await cpu.createJob(); let i, j, mtx, script, block, cb; script = new Script(); diff --git a/test/coins-test.js b/test/coins-test.js index 8b4302d1e..0d74fca04 100644 --- a/test/coins-test.js +++ b/test/coins-test.js @@ -14,8 +14,8 @@ const data = parseTX('data/tx1.hex'); const tx1 = data.tx; function reserialize(coin) { - let raw = coin.toRaw(); - let entry = CoinEntry.fromRaw(raw); + const raw = coin.toRaw(); + const entry = CoinEntry.fromRaw(raw); entry.raw = null; return CoinEntry.fromRaw(entry.toRaw()); } @@ -29,10 +29,10 @@ function deepCoinsEqual(a, b) { describe('Coins', function() { it('should instantiate coinview from tx', () => { - let hash = tx1.hash('hex'); - let view = new CoinView(); - let prevout = new Outpoint(hash, 0); - let input = Input.fromOutpoint(prevout); + const hash = tx1.hash('hex'); + const view = new CoinView(); + const prevout = new Outpoint(hash, 0); + const input = Input.fromOutpoint(prevout); let coins, entry, output; view.addTX(tx1, 1); @@ -58,8 +58,8 @@ describe('Coins', function() { }); it('should spend an output', () => { - let hash = tx1.hash('hex'); - let view = new CoinView(); + const hash = tx1.hash('hex'); + const view = new CoinView(); let coins, entry, length; view.addTX(tx1, 1); @@ -84,7 +84,7 @@ describe('Coins', function() { }); it('should handle coin view', () => { - let view = new CoinView(); + const view = new CoinView(); let i, tx, size, bw, br; let raw, res, prev, coins; diff --git a/test/gcs-test.js b/test/gcs-test.js index 179d79e4e..ee408f74c 100644 --- a/test/gcs-test.js +++ b/test/gcs-test.js @@ -8,12 +8,12 @@ const Block = require('../lib/primitives/block'); const Outpoint = require('../lib/primitives/outpoint'); const Address = require('../lib/primitives/address'); -let raw = fs.readFileSync(`${__dirname}/data/block928927.raw`); -let block = Block.fromRaw(raw); +const raw = fs.readFileSync(`${__dirname}/data/block928927.raw`); +const block = Block.fromRaw(raw); describe('GCS', function() { - let key = random.randomBytes(16); - let P = 20; + const key = random.randomBytes(16); + const P = 20; let filter1, filter2, filter3, filter4, filter5; let contents1, contents2; let op1, op2, op3, op4; @@ -149,8 +149,8 @@ describe('GCS', function() { }); it('should test GCS filter fromBlock', () => { - let key = block.hash().slice(0, 16); - let filter = GCSFilter.fromBlock(block); + const key = block.hash().slice(0, 16); + const filter = GCSFilter.fromBlock(block); assert(filter.match(key, op1.toRaw())); assert(filter.match(key, op2.toRaw())); assert(!filter.match(key, op3.toRaw())); @@ -163,8 +163,8 @@ describe('GCS', function() { }); it('should test GCS filter fromExtended', () => { - let key = block.hash().slice(0, 16); - let filter = GCSFilter.fromExtended(block); + const key = block.hash().slice(0, 16); + const filter = GCSFilter.fromExtended(block); assert(!filter.match(key, op1.toRaw())); assert(filter.match(key, block.txs[0].hash())); assert(filter.match(key, block.txs[1].hash())); diff --git a/test/hd-test.js b/test/hd-test.js index fb2a5db06..22ee3a0db 100644 --- a/test/hd-test.js +++ b/test/hd-test.js @@ -21,7 +21,7 @@ describe('HD', function() { let master, child1, child2, child3, child4, child5, child6; it('should create a pbkdf2 seed', () => { - let seed = pbkdf2.derive(vectors.phrase, 'mnemonicfoo', 2048, 64, 'sha512'); + const seed = pbkdf2.derive(vectors.phrase, 'mnemonicfoo', 2048, 64, 'sha512'); assert.equal(seed.toString('hex'), vectors.seed); }); @@ -67,7 +67,7 @@ describe('HD', function() { }); it('should derive correctly when private key has leading zeros', () => { - let key = HD.PrivateKey.fromBase58(vectors.zero_priv); + const key = HD.PrivateKey.fromBase58(vectors.zero_priv); let child; assert.equal(key.privateKey.toString('hex'), @@ -87,7 +87,7 @@ describe('HD', function() { }); it('should deserialize and reserialize', () => { - let key = HD.generate(); + const key = HD.generate(); assert.equal(HD.fromJSON(key.toJSON()).toBase58(), key.toBase58()); }); @@ -101,13 +101,13 @@ describe('HD', function() { }); Object.keys(vector).forEach((path) => { - let kp = vector[path]; + const kp = vector[path]; if (path === 'seed' || path === 'm') return; it(`should derive ${path} from master`, () => { - let key = master.derivePath(path); + const key = master.derivePath(path); equal(key.toBase58(), kp.prv); equal(key.toPublic().toBase58(), kp.pub); }); diff --git a/test/http-test.js b/test/http-test.js index 19a647729..f0237c86e 100644 --- a/test/http-test.js +++ b/test/http-test.js @@ -38,12 +38,12 @@ describe('HTTP', function() { }); it('should create wallet', async () => { - let info = await wallet.create({ id: 'test' }); + const info = await wallet.create({ id: 'test' }); assert.equal(info.id, 'test'); }); it('should get info', async () => { - let info = await wallet.client.getInfo(); + const info = await wallet.client.getInfo(); assert.equal(info.network, node.network.type); assert.equal(info.version, pkg.version); assert.equal(info.pool.agent, node.pool.options.agent); @@ -52,7 +52,7 @@ describe('HTTP', function() { }); it('should get wallet info', async () => { - let info = await wallet.getInfo(); + const info = await wallet.getInfo(); assert.equal(info.id, 'test'); addr = info.account.receiveAddress; assert.equal(typeof addr, 'string'); @@ -98,7 +98,7 @@ describe('HTTP', function() { }); it('should get balance', async () => { - let balance = await wallet.getBalance(); + const balance = await wallet.getBalance(); assert.equal(balance.confirmed, 0); assert.equal(balance.unconfirmed, 201840); }); @@ -129,35 +129,35 @@ describe('HTTP', function() { }); it('should get a tx', async () => { - let tx = await wallet.getTX(hash); + const tx = await wallet.getTX(hash); assert(tx); assert.equal(tx.hash, hash); }); it('should generate new api key', async () => { - let t = wallet.token.toString('hex'); - let token = await wallet.retoken(null); + const t = wallet.token.toString('hex'); + const token = await wallet.retoken(null); assert(token.length === 64); assert.notEqual(token, t); }); it('should get balance', async () => { - let balance = await wallet.getBalance(); + const balance = await wallet.getBalance(); assert.equal(balance.unconfirmed, 199570); }); it('should execute an rpc call', async () => { - let info = await wallet.client.rpc.execute('getblockchaininfo', []); + const info = await wallet.client.rpc.execute('getblockchaininfo', []); assert.equal(info.blocks, 0); }); it('should execute an rpc call with bool parameter', async () => { - let info = await wallet.client.rpc.execute('getrawmempool', [true]); + const info = await wallet.client.rpc.execute('getrawmempool', [true]); assert.deepStrictEqual(info, {}); }); it('should create account', async () => { - let info = await wallet.createAccount('foo1'); + const info = await wallet.createAccount('foo1'); assert(info); assert(info.initialized); assert.equal(info.name, 'foo1'); @@ -167,7 +167,7 @@ describe('HTTP', function() { }); it('should create account', async () => { - let info = await wallet.createAccount('foo2', { + const info = await wallet.createAccount('foo2', { type: 'multisig', m: 1, n: 2 @@ -181,7 +181,7 @@ describe('HTTP', function() { }); it('should get a block template', async () => { - let json = await wallet.client.rpc.execute('getblocktemplate', []); + const json = await wallet.client.rpc.execute('getblocktemplate', []); assert.deepStrictEqual(json, { capabilities: [ 'proposal' ], mutable: [ 'time', 'transactions', 'prevblock' ], @@ -209,10 +209,10 @@ describe('HTTP', function() { }); it('should send a block template proposal', async () => { - let attempt = await node.miner.createBlock(); - let block = attempt.toBlock(); - let hex = block.toRaw().toString('hex'); - let json = await wallet.client.rpc.execute('getblocktemplate', [{ + const attempt = await node.miner.createBlock(); + const block = attempt.toBlock(); + const hex = block.toRaw().toString('hex'); + const json = await wallet.client.rpc.execute('getblocktemplate', [{ mode: 'proposal', data: hex }]); @@ -220,7 +220,7 @@ describe('HTTP', function() { }); it('should validate an address', async () => { - let json = await wallet.client.rpc.execute('validateaddress', [addr.toString()]); + const json = await wallet.client.rpc.execute('validateaddress', [addr.toString()]); assert.deepStrictEqual(json, { isvalid: true, address: addr.toString(), diff --git a/test/key-address-test.js b/test/key-address-test.js index a7674277c..fc0a3a6a9 100644 --- a/test/key-address-test.js +++ b/test/key-address-test.js @@ -4,8 +4,8 @@ const assert = require('assert'); const keyring = require('../lib/primitives/keyring'); describe('Keyring Address', function() { - let ukey = keyring.fromSecret('5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss'); - let ckey = keyring.fromSecret('L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1'); + const ukey = keyring.fromSecret('5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss'); + const ckey = keyring.fromSecret('L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1'); it('check uncompressed public key', () => { assert.equal( diff --git a/test/mempool-test.js b/test/mempool-test.js index be134bf10..83cdb0ddc 100644 --- a/test/mempool-test.js +++ b/test/mempool-test.js @@ -16,9 +16,9 @@ const Witness = require('../lib/script/witness'); const MemWallet = require('./util/memwallet'); describe('Mempool', function() { - let chain = new Chain({ db: 'memory' }); - let mempool = new Mempool({ chain: chain, db: 'memory' }); - let wallet = new MemWallet(); + const chain = new Chain({ db: 'memory' }); + const mempool = new Mempool({ chain: chain, db: 'memory' }); + const wallet = new MemWallet(); let cached; this.timeout(5000); @@ -53,8 +53,8 @@ describe('Mempool', function() { }); it('should handle incoming orphans and TXs', async () => { - let kp = KeyRing.generate(); - let w = wallet; + const kp = KeyRing.generate(); + const w = wallet; let t1, t2, t3, t4, f1, fake, prev, sig, balance, txs; t1 = new MTX(); @@ -152,8 +152,8 @@ describe('Mempool', function() { }); it('should handle locktime', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, sig; tx = new MTX(); @@ -178,8 +178,8 @@ describe('Mempool', function() { }); it('should handle invalid locktime', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, sig, err; tx = new MTX(); @@ -209,8 +209,8 @@ describe('Mempool', function() { }); it('should not cache a malleated wtx with mutated sig', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, prevs, sig, err; kp.witness = true; @@ -243,8 +243,8 @@ describe('Mempool', function() { }); it('should not cache a malleated tx with unnecessary witness', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, sig, err; tx = new MTX(); @@ -272,8 +272,8 @@ describe('Mempool', function() { }); it('should not cache a malleated wtx with wit removed', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, err; kp.witness = true; @@ -301,8 +301,8 @@ describe('Mempool', function() { }); it('should cache non-malleated tx without sig', async () => { - let w = wallet; - let kp = KeyRing.generate(); + const w = wallet; + const kp = KeyRing.generate(); let tx, prev, prevHash, err; tx = new MTX(); @@ -329,7 +329,7 @@ describe('Mempool', function() { }); it('should clear reject cache', async () => { - let w = wallet; + const w = wallet; let tx; tx = new MTX(); diff --git a/test/mnemonic-test.js b/test/mnemonic-test.js index bd5186e3d..f9cc1243c 100644 --- a/test/mnemonic-test.js +++ b/test/mnemonic-test.js @@ -8,10 +8,10 @@ const mnemonic2 = require('./data/mnemonic2'); describe('Mnemonic', function() { mnemonic1.forEach((data, i) => { - let entropy = Buffer.from(data[0], 'hex'); - let phrase = data[1]; - let seed = Buffer.from(data[2], 'hex'); - let xpriv = data[3]; + const entropy = Buffer.from(data[0], 'hex'); + const phrase = data[1]; + const seed = Buffer.from(data[2], 'hex'); + const xpriv = data[3]; it(`should create an english mnemonic (${i})`, () => { let mnemonic, key; @@ -30,11 +30,11 @@ describe('Mnemonic', function() { }); mnemonic2.forEach((data, i) => { - let entropy = Buffer.from(data.entropy, 'hex'); - let phrase = data.mnemonic; - let seed = Buffer.from(data.seed, 'hex'); - let passphrase = data.passphrase; - let xpriv = data.bip32_xprv; + const entropy = Buffer.from(data.entropy, 'hex'); + const phrase = data.mnemonic; + const seed = Buffer.from(data.seed, 'hex'); + const passphrase = data.passphrase; + const xpriv = data.bip32_xprv; it(`should create a japanese mnemonic (${i})`, () => { let mnemonic, key; @@ -53,8 +53,8 @@ describe('Mnemonic', function() { }); it('should verify phrase', () => { - let m1 = new HD.Mnemonic(); - let m2 = HD.Mnemonic.fromPhrase(m1.getPhrase()); + const m1 = new HD.Mnemonic(); + const m2 = HD.Mnemonic.fromPhrase(m1.getPhrase()); assert.deepEqual(m2.getEntropy(), m1.getEntropy()); assert.equal(m2.bits, m1.bits); assert.equal(m2.language, m1.language); diff --git a/test/node-test.js b/test/node-test.js index 53299ade9..2fddcff6c 100644 --- a/test/node-test.js +++ b/test/node-test.js @@ -31,7 +31,7 @@ describe('Node', function() { this.timeout(5000); async function mineBlock(tip, tx) { - let job = await miner.createJob(tip); + const job = await miner.createJob(tip); let rtx; if (!tx) @@ -67,7 +67,7 @@ describe('Node', function() { }); it('should mine a block', async () => { - let block = await miner.mineBlock(); + const block = await miner.mineBlock(); assert(block); await chain.add(block); }); @@ -158,12 +158,12 @@ describe('Node', function() { }); it('should check main chain', async () => { - let result = await tip1.isMainChain(); + const result = await tip1.isMainChain(); assert(!result); }); it('should mine a block after a reorg', async () => { - let block = await mineBlock(null, cb2); + const block = await mineBlock(null, cb2); let entry, result; await chain.add(block); @@ -177,8 +177,8 @@ describe('Node', function() { }); it('should prevent double spend on new chain', async () => { - let block = await mineBlock(null, cb2); - let tip = chain.tip; + const block = await mineBlock(null, cb2); + const tip = chain.tip; let err; try { @@ -193,8 +193,8 @@ describe('Node', function() { }); it('should fail to mine a block with coins on an alternate chain', async () => { - let block = await mineBlock(null, cb1); - let tip = chain.tip; + const block = await mineBlock(null, cb1); + const tip = chain.tip; let err; try { @@ -275,7 +275,7 @@ describe('Node', function() { }); it('should activate csv', async () => { - let deployments = chain.network.deployments; + const deployments = chain.network.deployments; let i, block, prev, state, cache; prev = await chain.tip.getPrevious(); @@ -314,7 +314,7 @@ describe('Node', function() { }); async function mineCSV(tx) { - let job = await miner.createJob(); + const job = await miner.createJob(); let redeemer; redeemer = new MTX(); @@ -340,7 +340,7 @@ describe('Node', function() { } it('should test csv', async () => { - let tx = (await chain.db.getBlock(chain.height)).txs[0]; + const tx = (await chain.db.getBlock(chain.height)).txs[0]; let block = await mineCSV(tx); let csv, job, redeemer; @@ -372,7 +372,7 @@ describe('Node', function() { }); it('should fail csv with bad sequence', async () => { - let csv = (await chain.db.getBlock(chain.height)).txs[1]; + const csv = (await chain.db.getBlock(chain.height)).txs[1]; let block, job, redeemer, err; redeemer = new MTX(); @@ -406,13 +406,13 @@ describe('Node', function() { }); it('should mine a block', async () => { - let block = await miner.mineBlock(); + const block = await miner.mineBlock(); assert(block); await chain.add(block); }); it('should fail csv lock checks', async () => { - let tx = (await chain.db.getBlock(chain.height)).txs[0]; + const tx = (await chain.db.getBlock(chain.height)).txs[0]; let block = await mineCSV(tx); let csv, job, redeemer, err; @@ -460,7 +460,7 @@ describe('Node', function() { }); it('should not get a block template', async () => { - let json = await node.rpc.call({ + const json = await node.rpc.call({ method: 'getblocktemplate' }, {}); assert(json.error); @@ -517,7 +517,7 @@ describe('Node', function() { }); it('should send a block template proposal', async () => { - let attempt = await node.miner.createBlock(); + const attempt = await node.miner.createBlock(); let block, hex, json; attempt.refresh(); @@ -539,8 +539,8 @@ describe('Node', function() { }); it('should submit a block', async () => { - let block = await node.miner.mineBlock(); - let hex = block.toRaw().toString('hex'); + const block = await node.miner.mineBlock(); + const hex = block.toRaw().toString('hex'); let json; json = await node.rpc.call({ @@ -554,7 +554,7 @@ describe('Node', function() { }); it('should validate an address', async () => { - let addr = new Address(); + const addr = new Address(); let json; addr.network = node.network; diff --git a/test/protocol-test.js b/test/protocol-test.js index a3a7a8aa7..b70b61bc2 100644 --- a/test/protocol-test.js +++ b/test/protocol-test.js @@ -11,8 +11,8 @@ const packets = require('../lib/net/packets'); const network = Network.get('main'); describe('Protocol', function() { - let pkg = require('../lib/pkg'); - let agent = `/bcoin:${pkg.version}/`; + const pkg = require('../lib/pkg'); + const agent = `/bcoin:${pkg.version}/`; let parser, framer, v1, v2, hosts; beforeEach(() => { @@ -22,7 +22,7 @@ describe('Protocol', function() { function packetTest(command, payload, test) { it(`should encode/decode ${command}`, (cb) => { - let ver = Buffer.from(framer.packet(command, payload.toRaw())); + const ver = Buffer.from(framer.packet(command, payload.toRaw())); parser.once('packet', (packet) => { assert.equal(packet.cmd, command); test(packet); diff --git a/test/script-test.js b/test/script-test.js index 825eca92f..ff051937a 100644 --- a/test/script-test.js +++ b/test/script-test.js @@ -46,22 +46,22 @@ describe('Script', function() { }); it('should encode/decode numbers', () => { - let script = [0, 0x51, 0x52, 0x60]; - let encoded = Script.fromArray(script).raw; - let decoded = Script(encoded).toArray(); + const script = [0, 0x51, 0x52, 0x60]; + const encoded = Script.fromArray(script).raw; + const decoded = Script(encoded).toArray(); assert.deepEqual(decoded, script); }); it('should recognize a P2SH output', () => { - let hex = 'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87'; - let decoded = Script.fromRaw(hex, 'hex'); + const hex = 'a91419a7d869032368fd1f1e26e5e73a4ad0e474960e87'; + const decoded = Script.fromRaw(hex, 'hex'); assert(decoded.isScripthash()); }); it('should recognize a Null Data output', () => { - let hex = '6a28590c080112220a1b353930632e6f7267282a5f' + const hex = '6a28590c080112220a1b353930632e6f7267282a5f' + '5e294f7665726c6179404f7261636c65103b1a010c'; - let decoded = Script.fromRaw(hex, 'hex'); + const decoded = Script.fromRaw(hex, 'hex'); assert(decoded.isNulldata()); }); @@ -232,8 +232,8 @@ describe('Script', function() { let witness = Array.isArray(data[0]) ? data.shift() : []; let input = data[0] ? data[0].trim() : data[0] || ''; let output = data[1] ? data[1].trim() : data[1] || ''; - let names = data[2] ? data[2].trim().split(/,\s*/) : []; - let expected = data[3] || ''; + const names = data[2] ? data[2].trim().split(/,\s*/) : []; + const expected = data[3] || ''; let comments = Array.isArray(data[4]) ? data[4].join('. ') : data[4] || ''; let amount = 0; let flags = 0; @@ -260,7 +260,7 @@ describe('Script', function() { } [false, true].forEach((noCache) => { - let suffix = noCache ? 'without cache' : 'with cache'; + const suffix = noCache ? 'without cache' : 'with cache'; it(`should handle script test ${suffix}:${comments}`, () => { let prev, tx, err, res; diff --git a/test/scrypt-test.js b/test/scrypt-test.js index 51ba3ff8a..e8a1e6add 100644 --- a/test/scrypt-test.js +++ b/test/scrypt-test.js @@ -5,9 +5,9 @@ const scrypt = require('../lib/crypto/scrypt'); describe('Scrypt', function() { it('should perform scrypt with N=16', () => { - let pass = Buffer.from(''); - let salt = Buffer.from(''); - let result = scrypt.derive(pass, salt, 16, 1, 1, 64); + const pass = Buffer.from(''); + const salt = Buffer.from(''); + const result = scrypt.derive(pass, salt, 16, 1, 1, 64); assert.equal(result.toString('hex'), '' + '77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3f' + 'ede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628' @@ -15,9 +15,9 @@ describe('Scrypt', function() { }); it('should perform scrypt with N=1024', () => { - let pass = Buffer.from('password'); - let salt = Buffer.from('NaCl'); - let result = scrypt.derive(pass, salt, 1024, 8, 16, 64); + const pass = Buffer.from('password'); + const salt = Buffer.from('NaCl'); + const result = scrypt.derive(pass, salt, 1024, 8, 16, 64); assert.equal(result.toString('hex'), '' + 'fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e773' + '76634b3731622eaf30d92e22a3886ff109279d9830dac727afb9' @@ -25,9 +25,9 @@ describe('Scrypt', function() { }); it('should perform scrypt with N=16384', () => { - let pass = Buffer.from('pleaseletmein'); - let salt = Buffer.from('SodiumChloride'); - let result = scrypt.derive(pass, salt, 16384, 8, 1, 64); + const pass = Buffer.from('pleaseletmein'); + const salt = Buffer.from('SodiumChloride'); + const result = scrypt.derive(pass, salt, 16384, 8, 1, 64); assert.equal(result.toString('hex'), '' + '7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b54' + '3f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d' diff --git a/test/siphash-test.js b/test/siphash-test.js index 5ed0ec3ea..da05caadc 100644 --- a/test/siphash-test.js +++ b/test/siphash-test.js @@ -6,22 +6,22 @@ const siphash256 = siphash.siphash256; describe('SipHash', function() { it('should perform siphash with no data', () => { - let data = Buffer.alloc(0); - let key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); + const data = Buffer.alloc(0); + const key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); assert.deepEqual(siphash256(data, key), [1919933255, -586281423]); }); it('should perform siphash with data', () => { - let data = Buffer.from('0001020304050607', 'hex'); - let key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); + const data = Buffer.from('0001020304050607', 'hex'); + const key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); assert.deepEqual(siphash256(data, key), [-1812597383, -1701632926]); }); it('should perform siphash with uint256', () => { - let data = Buffer.from( + const data = Buffer.from( '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', 'hex'); - let key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); + const key = Buffer.from('000102030405060708090a0b0c0d0e0f', 'hex'); assert.deepEqual(siphash256(data, key), [1898402095, 1928494286]); }); }); diff --git a/test/tx-test.js b/test/tx-test.js index 0f874eaef..886b8dc64 100644 --- a/test/tx-test.js +++ b/test/tx-test.js @@ -40,7 +40,7 @@ function clearCache(tx, noCache) { function parseTest(data) { let [coins, tx, names] = data; - let view = new CoinView(); + const view = new CoinView(); let flags = 0; let coin; @@ -91,7 +91,7 @@ function parseTest(data) { } function sigopContext(scriptSig, witness, scriptPubkey) { - let view = new CoinView(); + const view = new CoinView(); let input, output, fund, spend; input = new Input(); @@ -130,7 +130,7 @@ function sigopContext(scriptSig, witness, scriptPubkey) { } describe('TX', function() { - let raw = '010000000125393c67cd4f581456dd0805fa8e9db3abdf90dbe1d4b53e28' + + const raw = '010000000125393c67cd4f581456dd0805fa8e9db3abdf90dbe1d4b53e28' + '6490f35d22b6f2010000006b483045022100f4fa5ced20d2dbd2f905809d' + '79ebe34e03496ef2a48a04d0a9a1db436a211dd202203243d086398feb4a' + 'c21b3b79884079036cd5f3707ba153b383eabefa656512dd0121022ebabe' + @@ -138,7 +138,7 @@ describe('TX', function() { 'ffffff0254150000000000001976a9140740345f114e1a1f37ac1cc442b4' + '32b91628237e88ace7d27b00000000001976a91495ad422bb5911c2c9fe6' + 'ce4f82a13c85f03d9b2e88ac00000000'; - let inp = '01000000052fa236559f51f343f0905ea627a955f421a198541d928798b8' + + const inp = '01000000052fa236559f51f343f0905ea627a955f421a198541d928798b8' + '186980273942ec010000006b483045022100ae27626778eba264d56883f5' + 'edc1a49897bf209e98f21c870a55d13bec916e1802204b66f4e3235143d1' + '1aef327d9454754cd1f28807c3bf9996c107900df9d19ea60121022ebabe' + @@ -168,18 +168,18 @@ describe('TX', function() { '2e88ac00000000'; [false, true].forEach((noCache) => { - let suffix = noCache ? 'without cache' : 'with cache'; + const suffix = noCache ? 'without cache' : 'with cache'; it(`should decode/encode with parser/framer ${suffix}`, () => { - let tx = TX.fromRaw(raw, 'hex'); + const tx = TX.fromRaw(raw, 'hex'); clearCache(tx, noCache); assert.equal(tx.toRaw().toString('hex'), raw); }); it(`should be verifiable ${suffix}`, () => { - let tx = TX.fromRaw(raw, 'hex'); - let p = TX.fromRaw(inp, 'hex'); - let view = new CoinView(); + const tx = TX.fromRaw(raw, 'hex'); + const p = TX.fromRaw(inp, 'hex'); + const view = new CoinView(); view.addTX(p, -1); clearCache(tx, noCache); @@ -204,8 +204,8 @@ describe('TX', function() { }); it(`should verify high S value with only DERSIG enabled ${suffix}`, () => { - let coin = tx4.view.getOutputFor(tx4.tx.inputs[0]); - let flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG; + const coin = tx4.view.getOutputFor(tx4.tx.inputs[0]); + const flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG; clearCache(tx4.tx, noCache); assert(tx4.tx.verifyInput(0, coin, flags)); }); @@ -244,7 +244,7 @@ describe('TX', function() { }); [[valid, true], [invalid, false]].forEach((test) => { - let [arr, valid] = test; + const [arr, valid] = test; let comment = ''; arr.forEach((json, i) => { @@ -339,16 +339,16 @@ describe('TX', function() { clearCache(tx, noCache); it(`should get sighash of ${hash} (${hex}) ${suffix}`, () => { - let subscript = script.getSubscript(0).removeSeparators(); - let hash = tx.signatureHash(index, subscript, 0, type, 0); + const subscript = script.getSubscript(0).removeSeparators(); + const hash = tx.signatureHash(index, subscript, 0, type, 0); assert.equal(hash.toString('hex'), expected); }); }); }); function createInput(value, view) { - let hash = random.randomBytes(32).toString('hex'); - let output = new Output(); + const hash = random.randomBytes(32).toString('hex'); + const output = new Output(); output.value = value; view.addOutput(new Outpoint(hash, 0), output); return { @@ -360,8 +360,8 @@ describe('TX', function() { } it('should fail on >51 bit coin values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY + 1, view)], @@ -376,8 +376,8 @@ describe('TX', function() { }); it('should handle 51 bit coin values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -392,8 +392,8 @@ describe('TX', function() { }); it('should fail on >51 bit output values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -408,8 +408,8 @@ describe('TX', function() { }); it('should handle 51 bit output values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -424,8 +424,8 @@ describe('TX', function() { }); it('should fail on >51 bit fees', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY + 1, view)], @@ -440,8 +440,8 @@ describe('TX', function() { }); it('should fail on >51 bit values from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [ @@ -460,8 +460,8 @@ describe('TX', function() { }); it('should fail on >51 bit output values from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -486,8 +486,8 @@ describe('TX', function() { }); it('should fail on >51 bit fees from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [ @@ -506,7 +506,7 @@ describe('TX', function() { }); it('should fail to parse >53 bit values', () => { - let view = new CoinView(); + const view = new CoinView(); let tx, raw; tx = new TX({ @@ -542,8 +542,8 @@ describe('TX', function() { }); it('should fail on 53 bit coin values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(MAX_SAFE_INTEGER, view)], @@ -558,8 +558,8 @@ describe('TX', function() { }); it('should fail on 53 bit output values', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -574,8 +574,8 @@ describe('TX', function() { }); it('should fail on 53 bit fees', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(MAX_SAFE_INTEGER, view)], @@ -591,8 +591,8 @@ describe('TX', function() { [MAX_SAFE_ADDITION, MAX_SAFE_INTEGER].forEach((MAX) => { it('should fail on >53 bit values from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [ @@ -611,8 +611,8 @@ describe('TX', function() { }); it('should fail on >53 bit output values from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [createInput(consensus.MAX_MONEY, view)], @@ -637,8 +637,8 @@ describe('TX', function() { }); it('should fail on >53 bit fees from multiple', () => { - let view = new CoinView(); - let tx = new TX({ + const view = new CoinView(); + const tx = new TX({ version: 1, flag: 1, inputs: [ @@ -658,9 +658,9 @@ describe('TX', function() { }); it('should count sigops for multisig', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); - let pub = key.publicKey; + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); + const pub = key.publicKey; let ctx, output, input, witness; output = Script.fromMultisig(1, 2, [pub, pub]); @@ -680,9 +680,9 @@ describe('TX', function() { }); it('should count sigops for p2sh multisig', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); - let pub = key.publicKey; + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); + const pub = key.publicKey; let ctx, redeem, output, input, witness; redeem = Script.fromMultisig(1, 2, [pub, pub]); @@ -703,8 +703,8 @@ describe('TX', function() { }); it('should count sigops for p2wpkh', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); let ctx, output, input, witness; output = Script.fromProgram(0, key.getKeyHash()); @@ -739,8 +739,8 @@ describe('TX', function() { }); it('should count sigops for nested p2wpkh', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); let ctx, redeem, output, input, witness; redeem = Script.fromProgram(0, key.getKeyHash()); @@ -761,9 +761,9 @@ describe('TX', function() { }); it('should count sigops for p2wsh', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); - let pub = key.publicKey; + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); + const pub = key.publicKey; let ctx, redeem, output, input, witness; redeem = Script.fromMultisig(1, 2, [pub, pub]); @@ -786,9 +786,9 @@ describe('TX', function() { }); it('should count sigops for nested p2wsh', () => { - let flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; - let key = KeyRing.generate(); - let pub = key.publicKey; + const flags = Script.flags.VERIFY_WITNESS | Script.flags.VERIFY_P2SH; + const key = KeyRing.generate(); + const pub = key.publicKey; let ctx, wscript, redeem, output, input, witness; wscript = Script.fromMultisig(1, 2, [pub, pub]); diff --git a/test/util/common.js b/test/util/common.js index e0070f26c..feea54245 100644 --- a/test/util/common.js +++ b/test/util/common.js @@ -5,16 +5,16 @@ const TX = require('../../lib/primitives/tx'); const CoinView = require('../../lib/coins/coinview'); exports.parseTX = function parseTX(file) { - let data = fs.readFileSync(`${__dirname}/../${file}`, 'utf8'); - let parts = data.trim().split(/\n+/); - let raw = parts[0]; - let tx = TX.fromRaw(raw.trim(), 'hex'); - let view = new CoinView(); - let txs = [tx]; + const data = fs.readFileSync(`${__dirname}/../${file}`, 'utf8'); + const parts = data.trim().split(/\n+/); + const raw = parts[0]; + const tx = TX.fromRaw(raw.trim(), 'hex'); + const view = new CoinView(); + const txs = [tx]; for (let i = 1; i < parts.length; i++) { - let raw = parts[i]; - let prev = TX.fromRaw(raw.trim(), 'hex'); + const raw = parts[i]; + const prev = TX.fromRaw(raw.trim(), 'hex'); view.addTX(prev, -1); txs.push(prev); } diff --git a/test/util/memwallet.js b/test/util/memwallet.js index 486ed43ff..2345b0f48 100644 --- a/test/util/memwallet.js +++ b/test/util/memwallet.js @@ -100,9 +100,9 @@ MemWallet.prototype.init = function init() { }; MemWallet.prototype.createReceive = function createReceive() { - let index = this.receiveDepth++; - let key = this.deriveReceive(index); - let hash = key.getHash('hex'); + const index = this.receiveDepth++; + const key = this.deriveReceive(index); + const hash = key.getHash('hex'); this.filter.add(hash, 'hex'); this.paths.set(hash, new Path(hash, 0, index)); this.receive = key; @@ -110,9 +110,9 @@ MemWallet.prototype.createReceive = function createReceive() { }; MemWallet.prototype.createChange = function createChange() { - let index = this.changeDepth++; - let key = this.deriveChange(index); - let hash = key.getHash('hex'); + const index = this.changeDepth++; + const key = this.deriveChange(index); + const hash = key.getHash('hex'); this.filter.add(hash, 'hex'); this.paths.set(hash, new Path(hash, 1, index)); this.change = key; @@ -144,7 +144,7 @@ MemWallet.prototype.deriveKey = function deriveKey(branch, index) { }; MemWallet.prototype.getKey = function getKey(hash) { - let path = this.paths.get(hash); + const path = this.paths.get(hash); if (!path) return; return this.derivePath(path); @@ -163,8 +163,8 @@ MemWallet.prototype.getUndo = function getUndo(key) { }; MemWallet.prototype.addCoin = function addCoin(coin) { - let op = Outpoint(coin.hash, coin.index); - let key = op.toKey(); + const op = Outpoint(coin.hash, coin.index); + const key = op.toKey(); this.filter.add(op.toRaw()); @@ -175,7 +175,7 @@ MemWallet.prototype.addCoin = function addCoin(coin) { }; MemWallet.prototype.removeCoin = function removeCoin(key) { - let coin = this.coins.get(key); + const coin = this.coins.get(key); if (!coin) return; @@ -199,9 +199,9 @@ MemWallet.prototype.getChange = function getChange() { }; MemWallet.prototype.getCoins = function getCoins() { - let coins = []; + const coins = []; - for (let coin of this.coins.values()) + for (const coin of this.coins.values()) coins.push(coin); return coins; @@ -242,7 +242,7 @@ MemWallet.prototype.removeBlock = function removeBlock(entry, txs) { }; MemWallet.prototype.addTX = function addTX(tx, height) { - let hash = tx.hash('hex'); + const hash = tx.hash('hex'); let result = false; let i, op, path, addr, coin, input, output; @@ -293,7 +293,7 @@ MemWallet.prototype.addTX = function addTX(tx, height) { }; MemWallet.prototype.removeTX = function removeTX(tx, height) { - let hash = tx.hash('hex'); + const hash = tx.hash('hex'); let result = false; let i, op, coin, input; @@ -334,7 +334,7 @@ MemWallet.prototype.removeTX = function removeTX(tx, height) { }; MemWallet.prototype.deriveInputs = function deriveInputs(mtx) { - let keys = []; + const keys = []; let i, input, coin, addr, path, key; for (i = 0; i < mtx.inputs.length; i++) { @@ -363,7 +363,7 @@ MemWallet.prototype.deriveInputs = function deriveInputs(mtx) { }; MemWallet.prototype.fund = function fund(mtx, options) { - let coins = this.getCoins(); + const coins = this.getCoins(); if (!options) options = {}; @@ -382,18 +382,18 @@ MemWallet.prototype.fund = function fund(mtx, options) { }; MemWallet.prototype.template = function template(mtx) { - let keys = this.deriveInputs(mtx); + const keys = this.deriveInputs(mtx); mtx.template(keys); }; MemWallet.prototype.sign = function sign(mtx) { - let keys = this.deriveInputs(mtx); + const keys = this.deriveInputs(mtx); mtx.template(keys); mtx.sign(keys); }; MemWallet.prototype.create = async function create(options) { - let mtx = new MTX(options); + const mtx = new MTX(options); await this.fund(mtx, options); @@ -413,7 +413,7 @@ MemWallet.prototype.create = async function create(options) { }; MemWallet.prototype.send = async function send(options) { - let mtx = await this.create(options); + const mtx = await this.create(options); this.addTX(mtx.toTX()); return mtx; }; diff --git a/test/util/node-context.js b/test/util/node-context.js index b8f8c6db0..57d7a5dfe 100644 --- a/test/util/node-context.js +++ b/test/util/node-context.js @@ -55,25 +55,25 @@ NodeContext.prototype.init = function() { }; NodeContext.prototype.open = function open() { - let jobs = []; + const jobs = []; - for (let node of this.nodes) + for (const node of this.nodes) jobs.push(node.open()); return Promise.all(jobs); }; NodeContext.prototype.close = function close() { - let jobs = []; + const jobs = []; - for (let node of this.nodes) + for (const node of this.nodes) jobs.push(node.close()); return Promise.all(jobs); }; NodeContext.prototype.connect = async function connect() { - for (let node of this.nodes) { + for (const node of this.nodes) { await node.connect(); await co.timeout(1000); } @@ -90,7 +90,7 @@ NodeContext.prototype.disconnect = async function disconnect() { }; NodeContext.prototype.startSync = function startSync() { - for (let node of this.nodes) { + for (const node of this.nodes) { node.chain.synced = true; node.chain.emit('full'); node.startSync(); @@ -98,12 +98,12 @@ NodeContext.prototype.startSync = function startSync() { }; NodeContext.prototype.stopSync = function stopSync() { - for (let node of this.nodes) + for (const node of this.nodes) node.stopSync(); }; NodeContext.prototype.generate = async function generate(index, blocks) { - let node = this.nodes[index]; + const node = this.nodes[index]; let i, block; assert(node); @@ -115,7 +115,7 @@ NodeContext.prototype.generate = async function generate(index, blocks) { }; NodeContext.prototype.height = function height(index) { - let node = this.nodes[index]; + const node = this.nodes[index]; assert(node); diff --git a/test/utils-test.js b/test/utils-test.js index 98313f44e..6187f0226 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -37,7 +37,7 @@ describe('Utils', function() { ]; it('should encode/decode base58', () => { - let buf = Buffer.from('000000deadbeef', 'hex'); + const buf = Buffer.from('000000deadbeef', 'hex'); let b = base58.encode(buf); let i, r; @@ -53,7 +53,7 @@ describe('Utils', function() { }); it('should verify proof-of-work', () => { - let bits = 0x1900896c; + const bits = 0x1900896c; let hash; hash = Buffer.from( @@ -204,9 +204,9 @@ describe('Utils', function() { ]; unsigned.forEach((num) => { - let buf1 = Buffer.allocUnsafe(8); - let buf2 = Buffer.allocUnsafe(8); - let bits = num.bitLength(); + const buf1 = Buffer.allocUnsafe(8); + const buf2 = Buffer.allocUnsafe(8); + const bits = num.bitLength(); it(`should write+read a ${bits} bit unsigned int`, () => { let n1, n2; @@ -222,10 +222,10 @@ describe('Utils', function() { }); signed.forEach((num) => { - let buf1 = Buffer.allocUnsafe(8); - let buf2 = Buffer.allocUnsafe(8); - let bits = num.bitLength(); - let sign = num.isNeg() ? 'negative' : 'positive'; + const buf1 = Buffer.allocUnsafe(8); + const buf2 = Buffer.allocUnsafe(8); + const bits = num.bitLength(); + const sign = num.isNeg() ? 'negative' : 'positive'; it(`should write+read a ${bits} bit ${sign} int`, () => { let n1, n2; @@ -323,16 +323,16 @@ describe('Utils', function() { }); it('should do proper schnorr', () => { - let key = secp256k1.generatePrivateKey(); - let pub = secp256k1.publicKeyCreate(key, true); - let msg = digest.hash256(Buffer.from('foo', 'ascii')); - let sig = schnorr.sign(msg, key); + const key = secp256k1.generatePrivateKey(); + const pub = secp256k1.publicKeyCreate(key, true); + const msg = digest.hash256(Buffer.from('foo', 'ascii')); + const sig = schnorr.sign(msg, key); assert(schnorr.verify(msg, sig, pub)); assert.deepEqual(schnorr.recover(sig, msg), pub); }); it('should validate integers 0 and 1 as booleans', () => { - let validator = new Validator({shouldBeTrue: 1, shouldBeFalse: 0}); + const validator = new Validator({shouldBeTrue: 1, shouldBeFalse: 0}); assert(validator.bool('shouldBeTrue') === true); assert(validator.bool('shouldBeFalse') === false); }); diff --git a/test/wallet-test.js b/test/wallet-test.js index bf12536a6..8c58acef5 100644 --- a/test/wallet-test.js +++ b/test/wallet-test.js @@ -23,7 +23,7 @@ const KEY2 = 'xprv9s21ZrQH143K3mqiSThzPtWAabQ22Pjp3uSNnZ53A5bQ4udp' + 'faKekc2m4AChLYH1XDzANhrSdxHYWUeTWjYJwFwWFyHkTMnMeAcW4JyRCZa'; let globalHeight = 1; -let globalTime = util.now(); +const globalTime = util.now(); function nextBlock(height) { let hash, prev; @@ -70,8 +70,8 @@ describe('Wallet', function() { }); it('should generate new key and address', async () => { - let w = await wdb.create(); - let addr = w.getAddress('string'); + const w = await wdb.create(); + const addr = w.getAddress('string'); assert(addr); assert(Address.fromString(addr)); }); @@ -103,7 +103,7 @@ describe('Wallet', function() { }); async function testP2PKH(witness, bullshitNesting) { - let flags = Script.flags.STANDARD_VERIFY_FLAGS; + const flags = Script.flags.STANDARD_VERIFY_FLAGS; let w, addr, src, tx; w = await wdb.create({ witness: witness }); @@ -180,8 +180,8 @@ describe('Wallet', function() { }); it('should handle missed and invalid txs', async () => { - let w = await wdb.create(); - let f = await wdb.create(); + const w = await wdb.create(); + const f = await wdb.create(); let t1, t2, t3, t4, f1, fake, balance, txs; // Coinbase @@ -284,7 +284,7 @@ describe('Wallet', function() { }); it('should cleanup spenders after double-spend', async () => { - let w = doubleSpendWallet; + const w = doubleSpendWallet; let tx, txs, total, balance; tx = new MTX(); @@ -445,8 +445,8 @@ describe('Wallet', function() { }); it('should fill tx with inputs', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); let view, t1, t2, t3, err; // Coinbase @@ -490,8 +490,8 @@ describe('Wallet', function() { }); it('should fill tx with inputs with accurate fee', async () => { - let w1 = await wdb.create({ master: KEY1 }); - let w2 = await wdb.create({ master: KEY2 }); + const w1 = await wdb.create({ master: KEY1 }); + const w2 = await wdb.create({ master: KEY2 }); let view, t1, t2, t3, balance, err; // Coinbase @@ -549,9 +549,9 @@ describe('Wallet', function() { }); it('should sign multiple inputs using different keys', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); - let to = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); + const to = await wdb.create(); let t1, t2, tx, cost, total, coins1, coins2; // Coinbase @@ -616,9 +616,9 @@ describe('Wallet', function() { }); async function testMultisig(witness, bullshitNesting, cb) { - let flags = Script.flags.STANDARD_VERIFY_FLAGS; - let rec = bullshitNesting ? 'nested' : 'receive'; - let depth = bullshitNesting ? 'nestedDepth' : 'receiveDepth'; + const flags = Script.flags.STANDARD_VERIFY_FLAGS; + const rec = bullshitNesting ? 'nested' : 'receive'; + const depth = bullshitNesting ? 'nestedDepth' : 'receiveDepth'; let options, w1, w2, w3, receive, b58; let addr, paddr, utx, send, change; let view, block; @@ -755,8 +755,8 @@ describe('Wallet', function() { }); it('should fill tx with account 1', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); let account, accounts, rec, t1, t2, t3, err; account = await w1.createAccount({ name: 'foo' }); @@ -810,7 +810,7 @@ describe('Wallet', function() { }); it('should fail to fill tx with account 1', async () => { - let w = await wdb.create(); + const w = await wdb.create(); let acc, account, t1, t2, err; wallet = w; @@ -890,7 +890,7 @@ describe('Wallet', function() { }); it('should fill tx with inputs when encrypted', async () => { - let w = await wdb.create({ passphrase: 'foo' }); + const w = await wdb.create({ passphrase: 'foo' }); let t1, t2, err; w.master.stop(); @@ -928,8 +928,8 @@ describe('Wallet', function() { }); it('should fill tx with inputs with subtract fee (1)', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); let t1, t2; // Coinbase @@ -957,8 +957,8 @@ describe('Wallet', function() { }); it('should fill tx with inputs with subtract fee (2)', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); let options, t1, t2; // Coinbase @@ -991,8 +991,8 @@ describe('Wallet', function() { }); it('should fill tx with smart coin selection', async () => { - let w1 = await wdb.create(); - let w2 = await wdb.create(); + const w1 = await wdb.create(); + const w2 = await wdb.create(); let found = false; let total = 0; let i, options, t1, t2, t3, block, coins, coin; @@ -1085,19 +1085,19 @@ describe('Wallet', function() { }); it('should get range of txs', async () => { - let w = wallet; - let txs = await w.getRange({ start: util.now() - 1000 }); + const w = wallet; + const txs = await w.getRange({ start: util.now() - 1000 }); assert.equal(txs.length, 2); }); it('should get range of txs from account', async () => { - let w = wallet; - let txs = await w.getRange('foo', { start: util.now() - 1000 }); + const w = wallet; + const txs = await w.getRange('foo', { start: util.now() - 1000 }); assert.equal(txs.length, 2); }); it('should not get range of txs from non-existent account', async () => { - let w = wallet; + const w = wallet; let txs, err; try { @@ -1112,14 +1112,14 @@ describe('Wallet', function() { }); it('should get account balance', async () => { - let w = wallet; - let balance = await w.getBalance('foo'); + const w = wallet; + const balance = await w.getBalance('foo'); assert.equal(balance.unconfirmed, 21840); }); it('should import privkey', async () => { - let key = KeyRing.generate(); - let w = await wdb.create({ passphrase: 'test' }); + const key = KeyRing.generate(); + const w = await wdb.create({ passphrase: 'test' }); let options, k, t1, t2, wtx; await w.importKey('default', key, 'test'); @@ -1161,9 +1161,9 @@ describe('Wallet', function() { }); it('should import pubkey', async () => { - let priv = KeyRing.generate(); - let key = new KeyRing(priv.publicKey); - let w = await wdb.create({ watchOnly: true }); + const priv = KeyRing.generate(); + const key = new KeyRing(priv.publicKey); + const w = await wdb.create({ watchOnly: true }); let k; await w.importKey('default', key); @@ -1177,8 +1177,8 @@ describe('Wallet', function() { }); it('should import address', async () => { - let key = KeyRing.generate(); - let w = await wdb.create({ watchOnly: true }); + const key = KeyRing.generate(); + const w = await wdb.create({ watchOnly: true }); let k; await w.importAddress('default', key.getAddress()); @@ -1192,25 +1192,25 @@ describe('Wallet', function() { }); it('should get details', async () => { - let w = wallet; - let txs = await w.getRange('foo', { start: util.now() - 1000 }); - let details = await w.toDetails(txs); + const w = wallet; + const txs = await w.getRange('foo', { start: util.now() - 1000 }); + const details = await w.toDetails(txs); assert(details.some((tx) => { return tx.toJSON().outputs[0].path.name === 'foo'; })); }); it('should rename wallet', async () => { - let w = wallet; + const w = wallet; await wallet.rename('test'); - let txs = await w.getRange('foo', { start: util.now() - 1000 }); - let details = await w.toDetails(txs); + const txs = await w.getRange('foo', { start: util.now() - 1000 }); + const details = await w.toDetails(txs); assert.equal(details[0].toJSON().id, 'test'); }); it('should change passphrase with encrypted imports', async () => { - let w = ewallet; - let addr = ekey.getAddress(); + const w = ewallet; + const addr = ekey.getAddress(); let path, d1, d2, k; assert(w.master.encrypted);