From 296e65d0fd2f2d2d32b687133af3a6417ff8010b Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sat, 1 Jul 2017 06:21:15 -0700 Subject: [PATCH] refactor: use es6 template strings everywhere. --- bench/buffer.js | 2 +- bench/coins-old.js | 2 +- bench/coins.js | 2 +- bench/tx.js | 4 +- browser/server.js | 10 ++-- lib/blockchain/chain.js | 5 +- lib/btc/amount.js | 4 +- lib/btc/uri.js | 12 ++--- lib/crypto/rsa.js | 2 +- lib/db/ldb.js | 13 ++--- lib/hd/mnemonic.js | 2 +- lib/http/base.js | 7 +-- lib/http/request.js | 6 +-- lib/net/packets.js | 10 ++-- lib/net/peer.js | 8 +-- lib/net/pool.js | 7 ++- lib/net/upnp.js | 31 ++++++------ lib/node/config.js | 4 +- lib/node/logger.js | 21 +++----- lib/primitives/address.js | 6 +-- lib/primitives/netaddress.js | 6 +-- lib/primitives/outpoint.js | 2 +- lib/protocol/errors.js | 6 +-- lib/script/common.js | 14 +++--- lib/script/program.js | 8 ++- lib/script/script.js | 2 +- lib/script/stack.js | 2 +- lib/script/witness.js | 2 +- lib/utils/ip.js | 14 +++--- lib/utils/pem.js | 6 +-- lib/utils/validator.js | 4 +- lib/wallet/http.js | 5 +- lib/wallet/path.js | 10 +--- lib/wallet/txdb.js | 4 +- lib/wallet/walletdb.js | 3 +- migrate/chaindb0to1.js | 2 +- migrate/chaindb1to2.js | 2 +- migrate/ensure-tip-index.js | 2 +- migrate/walletdb2to3.js | 4 +- migrate/walletdb3to4.js | 4 +- migrate/walletdb4to5.js | 4 +- migrate/walletdb5to6.js | 4 +- scripts/dump.js | 4 +- test/bech32-test.js | 10 ++-- test/block-test.js | 18 +++---- test/gcs-test.js | 2 +- test/hd-test.js | 2 +- test/mnemonic-test.js | 4 +- test/protocol-test.js | 4 +- test/script-test.js | 19 +++---- test/tx-test.js | 97 ++++++++++++++++-------------------- test/util/common.js | 2 +- test/util/node-context.js | 32 +++--------- test/utils-test.js | 29 +++++------ webpack.node.js | 2 +- webpack/bindings.js | 2 +- 56 files changed, 227 insertions(+), 268 deletions(-) diff --git a/bench/buffer.js b/bench/buffer.js index 1990fd469..f2af99cc1 100644 --- a/bench/buffer.js +++ b/bench/buffer.js @@ -6,7 +6,7 @@ const BufferWriter = require('../lib/utils/writer'); const StaticWriter = require('../lib/utils/staticwriter'); const bench = require('./bench'); -let wtx = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8'); +let wtx = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); let i, tx, end; wtx = Buffer.from(wtx.trim(), 'hex'); diff --git a/bench/coins-old.js b/bench/coins-old.js index 5b1edf159..4fcf5dfcd 100644 --- a/bench/coins-old.js +++ b/bench/coins-old.js @@ -5,7 +5,7 @@ const bench = require('./bench'); const Coins = require('../migrate/coins-old'); const TX = require('../lib/primitives/tx'); -let wtx = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8'); +let wtx = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); wtx = TX.fromRaw(wtx.trim(), 'hex'); let coins = Coins.fromTX(wtx); diff --git a/bench/coins.js b/bench/coins.js index f28af6810..3392b05f4 100644 --- a/bench/coins.js +++ b/bench/coins.js @@ -5,7 +5,7 @@ const Coins = require('../lib/coins/coins'); const TX = require('../lib/primitives/tx'); const bench = require('./bench'); -let raw = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8'); +let raw = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); let wtx = TX.fromRaw(raw.trim(), 'hex'); let coins = Coins.fromTX(wtx, 1); let i, j, end, hash; diff --git a/bench/tx.js b/bench/tx.js index 965df0c7b..7d0374260 100644 --- a/bench/tx.js +++ b/bench/tx.js @@ -17,7 +17,7 @@ let block = Block.fromJSON(json); let btx = { tx: block.txs[397], view: new CoinView() }; let tx3 = parseTX('../test/data/tx3.hex'); -let wtx = fs.readFileSync(__dirname + '/../test/data/wtx.hex', 'utf8'); +let wtx = fs.readFileSync(`${__dirname}/../test/data/wtx.hex`, 'utf8'); let i, tx, end, flags, input; wtx = Buffer.from(wtx.trim(), 'hex'); @@ -29,7 +29,7 @@ for (i = 0; i < tx.inputs.length; i++) { } function parseTX(file) { - let data = fs.readFileSync(__dirname + '/' + file, 'utf8'); + let data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); let parts = data.trim().split(/\n+/); let raw = parts[0]; let tx = TX.fromRaw(raw.trim(), 'hex'); diff --git a/browser/server.js b/browser/server.js index 0992da24b..778642fd6 100644 --- a/browser/server.js +++ b/browser/server.js @@ -5,11 +5,11 @@ const WSProxy = require('./wsproxy'); const fs = require('fs'); const server, proxy; -const index = fs.readFileSync(__dirname + '/index.html'); -const indexjs = fs.readFileSync(__dirname + '/index.js'); -const bcoin = fs.readFileSync(__dirname + '/bcoin.js'); -const master = fs.readFileSync(__dirname + '/bcoin-master.js'); -const worker = fs.readFileSync(__dirname + '/bcoin-worker.js'); +const index = fs.readFileSync(`${__dirname}/index.html`); +const indexjs = fs.readFileSync(`${__dirname}/index.js`); +const bcoin = fs.readFileSync(`${__dirname}/bcoin.js`); +const master = fs.readFileSync(`${__dirname}/bcoin-master.js`); +const worker = fs.readFileSync(`${__dirname}/bcoin-worker.js`); proxy = new WSProxy({ pow: process.argv.indexOf('--pow') !== -1, diff --git a/lib/blockchain/chain.js b/lib/blockchain/chain.js index acc1796d8..6f564a7c2 100644 --- a/lib/blockchain/chain.js +++ b/lib/blockchain/chain.js @@ -8,6 +8,7 @@ 'use strict'; const assert = require('assert'); +const path = require('path'); const AsyncObject = require('../utils/asyncobject'); const Network = require('../protocol/network'); const Logger = require('../node/logger'); @@ -2397,8 +2398,8 @@ ChainOptions.prototype.fromOptions = function fromOptions(options) { assert(typeof options.prefix === 'string'); this.prefix = options.prefix; this.location = this.spv - ? this.prefix + '/spvchain' - : this.prefix + '/chain'; + ? path.join(this.prefix, 'spvchain') + : path.join(this.prefix, 'chain'); } if (options.location != null) { diff --git a/lib/btc/amount.js b/lib/btc/amount.js index 0d9171363..b92669020 100644 --- a/lib/btc/amount.js +++ b/lib/btc/amount.js @@ -306,7 +306,7 @@ Amount.from = function from(unit, value, num) { */ Amount.prototype.inspect = function inspect() { - return ''; + return ``; }; /** @@ -360,7 +360,7 @@ Amount.serialize = function serialize(value, exp, num) { if (lo.length === 0) lo += '0'; - result = hi + '.' + lo; + result = `${hi}.${lo}`; if (negative) result = '-' + result; diff --git a/lib/btc/uri.js b/lib/btc/uri.js index 1b33b2ba8..ab8e24efe 100644 --- a/lib/btc/uri.js +++ b/lib/btc/uri.js @@ -161,16 +161,16 @@ URI.prototype.toString = function toString() { str += this.address.toString(); if (this.amount !== -1) - query.push('amount=' + Amount.btc(this.amount)); + query.push(`amount=${Amount.btc(this.amount)}`); if (this.label) - query.push('label=' + escape(this.label)); + query.push(`label=${escape(this.label)}`); if (this.message) - query.push('message=' + escape(this.message)); + query.push(`message=${escape(this.message)}`); if (this.request) - query.push('r=' + escape(this.request)); + query.push(`r=${escape(this.request)}`); if (query.length > 0) str += '?' + query.join('&'); @@ -184,7 +184,7 @@ URI.prototype.toString = function toString() { */ URI.prototype.inspect = function inspect() { - return ''; + return ``; }; /* @@ -240,7 +240,7 @@ function parsePairs(str) { data.r = unescape(value); break; default: - assert(false, 'Unknown querystring key: ' + value); + assert(false, `Unknown querystring key: ${value}.`); break; } diff --git a/lib/crypto/rsa.js b/lib/crypto/rsa.js index f35c564f0..903049bb3 100644 --- a/lib/crypto/rsa.js +++ b/lib/crypto/rsa.js @@ -73,5 +73,5 @@ exports.sign = function sign(alg, msg, key) { */ function normalizeAlg(alg, hash) { - return alg.toUpperCase() + '-' + hash.toUpperCase(); + return `${alg.toUpperCase()}-${hash.toUpperCase()}`; } diff --git a/lib/db/ldb.js b/lib/db/ldb.js index b20c7c194..8f9f42277 100644 --- a/lib/db/ldb.js +++ b/lib/db/ldb.js @@ -68,10 +68,7 @@ LDB.getName = function getName(db) { break; } - return { - name: name, - ext: ext - }; + return [name, ext]; }; /** @@ -81,18 +78,18 @@ LDB.getName = function getName(db) { */ LDB.getBackend = function getBackend(options) { - let result = LDB.getName(options.db); - let backend = backends.get(result.name); + let [name, ext] = LDB.getName(options.db); + let backend = backends.get(name); let location = options.location; if (typeof location !== 'string') { - assert(result.name === 'memory', 'Location required.'); + assert(name === 'memory', 'Location required.'); location = 'memory'; } return { backend: backend, - location: location + '.' + result.ext + location: `${location}.${ext}` }; }; diff --git a/lib/hd/mnemonic.js b/lib/hd/mnemonic.js index 72c40138b..b2ce5099f 100644 --- a/lib/hd/mnemonic.js +++ b/lib/hd/mnemonic.js @@ -525,7 +525,7 @@ Mnemonic.prototype.toString = function toString() { */ Mnemonic.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/http/base.js b/lib/http/base.js index 4268ce57c..74f784076 100644 --- a/lib/http/base.js +++ b/lib/http/base.js @@ -8,6 +8,7 @@ 'use strict'; const assert = require('assert'); +const path = require('path'); const EventEmitter = require('events'); const URL = require('url'); const {StringDecoder} = require('string_decoder'); @@ -205,7 +206,7 @@ HTTPBase.prototype.basicAuth = function basicAuth(options) { assert(typeof realm === 'string'); function fail(res) { - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); + res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`); res.setStatus(401); res.end(); } @@ -879,8 +880,8 @@ HTTPBaseOptions.prototype.fromOptions = function fromOptions(options) { if (options.prefix != null) { assert(typeof options.prefix === 'string'); this.prefix = options.prefix; - this.keyFile = this.prefix + '/key.pem'; - this.certFile = this.prefix + '/cert.pem'; + this.keyFile = path.join(this.prefix, 'key.pem'); + this.certFile = path.join(this.prefix, 'cert.pem'); } if (options.ssl != null) { diff --git a/lib/http/request.js b/lib/http/request.js index 433c66375..8c7d9d47e 100644 --- a/lib/http/request.js +++ b/lib/http/request.js @@ -239,9 +239,9 @@ RequestOptions.prototype.getHeaders = function getHeaders() { headers['Content-Length'] = this.body.length + ''; if (this.auth) { - let auth = this.auth.username + ':' + this.auth.password; - headers['Authorization'] = - 'Basic ' + Buffer.from(auth, 'utf8').toString('base64'); + let auth = `${this.auth.username}:${this.auth.password}`; + let data = Buffer.from(auth, 'utf8'); + headers['Authorization'] = `Basic ${data.toString('base64')}`; } return headers; diff --git a/lib/net/packets.js b/lib/net/packets.js index aa8dd49b1..2b4922440 100644 --- a/lib/net/packets.js +++ b/lib/net/packets.js @@ -1709,11 +1709,13 @@ 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; return ''; }; diff --git a/lib/net/peer.js b/lib/net/peer.js index e497c9765..e0beb5d16 100644 --- a/lib/net/peer.js +++ b/lib/net/peer.js @@ -2229,10 +2229,10 @@ Peer.prototype.hasCompact = function hasCompact() { Peer.prototype.inspect = function inspect() { return ''; }; diff --git a/lib/net/pool.js b/lib/net/pool.js index 4592389a7..67ebffe74 100644 --- a/lib/net/pool.js +++ b/lib/net/pool.js @@ -4377,10 +4377,9 @@ BroadcastItem.prototype.handleReject = function handleReject(peer) { */ BroadcastItem.prototype.inspect = function inspect() { - return ''; + let type = this.type === invTypes.TX ? 'tx' : 'block'; + let hash = util.revHex(this.hash); + return ``; }; /** diff --git a/lib/net/upnp.js b/lib/net/upnp.js index df25f3b27..f187b42cd 100644 --- a/lib/net/upnp.js +++ b/lib/net/upnp.js @@ -169,7 +169,7 @@ UPNP.prototype._discover = async function discover() { msg = '' + 'M-SEARCH * HTTP/1.1\r\n' - + 'HOST: ' + this.host + ':' + this.port + '\r\n' + + `HOST: ${this.host}:${this.port}\r\n` + 'MAN: ssdp:discover\r\n' + 'MX: 10\r\n' + 'ST: ssdp:all\r\n'; @@ -337,25 +337,25 @@ function UPNPService(options) { */ UPNPService.prototype.createRequest = function createRequest(action, args) { + let type = JSON.stringify(this.serviceType); let params = ''; - for (let arg of args) { - params += '<' + arg[0]+ '>'; - if (arg.length > 1) - params += arg[1]; - params += ''; + for (let [key, value] of args) { + params += `<${key}>`; + if (value != null) + params += value; + params += ``; } return '' + '' - + '' + + '' + '' - + '' - + params - + '' + + `` + + `${params}` + + `` + '' + ''; }; @@ -369,6 +369,7 @@ 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); let res, xml, err; @@ -381,7 +382,7 @@ UPNPService.prototype.soapRequest = async function soapRequest(action, args) { 'Content-Type': 'text/xml; charset="utf-8"', 'Content-Length': Buffer.byteLength(req, 'utf8') + '', 'Connection': 'close', - 'SOAPAction': JSON.stringify(this.serviceType + '#' + action) + 'SOAPAction': JSON.stringify(`${type}#${action}`) }, body: req }); @@ -701,7 +702,7 @@ function parseHost(uri) { assert(data.protocol === 'http:' || data.protocol === 'https:', 'Bad URL for location.'); - return data.protocol + '//' + data.host; + return `${data.protocol}//${data.host}`; } function prependHost(host, uri) { diff --git a/lib/node/config.js b/lib/node/config.js index f90d19dd1..dac2c469c 100644 --- a/lib/node/config.js +++ b/lib/node/config.js @@ -28,7 +28,7 @@ function Config(module) { this.module = module; this.network = 'main'; - this.prefix = path.join(HOME, '.' + module); + this.prefix = path.join(HOME, `.${module}`); this.options = Object.create(null); this.data = Object.create(null); @@ -592,7 +592,7 @@ Config.prototype.getPrefix = function getPrefix() { return prefix; } - prefix = path.join(HOME, '.' + this.module); + prefix = path.join(HOME, `.${this.module}`); network = this.str('network'); if (network) { diff --git a/lib/node/logger.js b/lib/node/logger.js index 884340782..2cf5dab0e 100644 --- a/lib/node/logger.js +++ b/lib/node/logger.js @@ -526,10 +526,10 @@ Logger.prototype.writeConsole = function writeConsole(level, module, args) { return; if (!process.stdout) { - msg += '[' + name + '] '; + msg += `[${name}] `; if (module) - msg += '(' + module + ') '; + msg += `(${module}) `; if (typeof args[0] === 'object') { return level === Logger.levels.ERROR @@ -548,15 +548,13 @@ Logger.prototype.writeConsole = function writeConsole(level, module, args) { color = Logger.styles[level]; assert(color); - msg += '\x1b[' + color + 'm'; - msg += '[' + name + ']'; - msg += '\x1b[m '; + msg += `\x1b[${color}m[${name}]\x1b[m `; } else { - msg += '[' + name + '] '; + msg += `[${name}] `; } if (module) - msg += '(' + module + ') '; + msg += `(${module}) `; msg += util.format(args, this.colors); msg += '\n'; @@ -585,13 +583,10 @@ Logger.prototype.writeStream = function writeStream(level, module, args) { if (this.closing) return; - msg += '['; - msg += name; - msg += ':' + util.date(); - msg += '] '; + msg += `[${name}:${util.date()}] `; if (module) - msg += '(' + module + ') '; + msg += `(${module}) `; msg += util.format(args, false); msg += '\n'; @@ -622,7 +617,7 @@ Logger.prototype.logError = function logError(level, module, err) { msg = (err.message + '').replace(/^ *Error: */, ''); if (level !== Logger.levels.ERROR) - msg = 'Error: ' + msg; + msg = `Error: ${msg}`; this.log(level, module, [msg]); diff --git a/lib/primitives/address.js b/lib/primitives/address.js index a3f73282e..b24b39cdf 100644 --- a/lib/primitives/address.js +++ b/lib/primitives/address.js @@ -290,9 +290,9 @@ Address.prototype.toString = function toString(network) { Address.prototype.inspect = function inspect() { return ''; }; diff --git a/lib/primitives/netaddress.js b/lib/primitives/netaddress.js index 15f98707f..d053107da 100644 --- a/lib/primitives/netaddress.js +++ b/lib/primitives/netaddress.js @@ -471,9 +471,9 @@ NetAddress.fromJSON = function fromJSON(json) { NetAddress.prototype.inspect = function inspect() { return ''; }; diff --git a/lib/primitives/outpoint.js b/lib/primitives/outpoint.js index fb2501c73..9195c61cd 100644 --- a/lib/primitives/outpoint.js +++ b/lib/primitives/outpoint.js @@ -283,7 +283,7 @@ Outpoint.toKey = function toKey(hash, index) { */ Outpoint.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/protocol/errors.js b/lib/protocol/errors.js index 8dbd925cc..f4e570f7c 100644 --- a/lib/protocol/errors.js +++ b/lib/protocol/errors.js @@ -53,10 +53,8 @@ function VerifyError(msg, code, reason, score, malleated) { this.hash = msg.hash('hex'); this.malleated = malleated || false; - this.message = 'Verification failure: ' + reason - + ' (code=' + code + ', score=' + score - + ', hash=' + msg.rhash() - + ')'; + this.message = `Verification failure: ${reason}` + + ` (code=${code} score=${score} hash=${msg.rhash()})`; } util.inherits(VerifyError, Error); diff --git a/lib/script/common.js b/lib/script/common.js index 7a27232df..2272e13a8 100644 --- a/lib/script/common.js +++ b/lib/script/common.js @@ -572,13 +572,13 @@ exports.formatCode = function formatCode(code) { value = value.toString(16); if (value.length < 2) value = '0' + value; - value = '0x' + value + ' 0x' + data.toString('hex'); + value = `0x${value} 0x${data.toString('hex')}`; out.push(value); continue; } value = exports.opcodesByVal[value]; - value = value + ' 0x' + size + ' 0x' + data.toString('hex'); + value = `${value} 0x${size} 0x${data.toString('hex')}`; out.push(value); continue; } @@ -601,7 +601,7 @@ exports.formatCode = function formatCode(code) { if (value.length < 2) value = '0' + value; - value = '0x' + value; + value = `0x${value}`; out.push(value); } @@ -625,12 +625,15 @@ exports.formatItem = function formatItem(data, decode) { let symbol = ''; if (exports.isSignatureEncoding(data)) { let type = data[data.length - 1]; + symbol = exports.hashTypeByVal[type & 0x1f] || ''; + if (symbol) { if (type & exports.hashType.ANYONECANPAY) symbol += '|ANYONECANPAY'; - symbol = '[' + symbol + ']'; + symbol = `[${symbol}]`; } + data = data.slice(0, -1); } return data.toString('hex') + symbol; @@ -831,10 +834,9 @@ exports.ScriptError = function ScriptError(code, op, ip) { if (typeof op === 'string') { this.message = op; } else if (op) { + this.message = `${code} (op=${op.toSymbol()}, ip=${ip})`; this.op = op.value; this.ip = ip; - this.message += ' (op=' + op.toSymbol() + ','; - this.message += ' ip=' + ip + ')'; } }; diff --git a/lib/script/program.js b/lib/script/program.js index 52ab3ff0e..8c7e63212 100644 --- a/lib/script/program.js +++ b/lib/script/program.js @@ -94,11 +94,9 @@ Program.prototype.isMalformed = function isMalformed() { */ Program.prototype.inspect = function inspect() { - return ''; + let data = this.data.toString('hex'); + let type = common.typesByVal[this.getType()].toLowerCase(); + return ``; }; /* diff --git a/lib/script/script.js b/lib/script/script.js index db90652aa..03b98d5e6 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -301,7 +301,7 @@ Script.prototype.inject = function inject(script) { */ Script.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/script/stack.js b/lib/script/stack.js index 7ac3b2125..5a5b9c727 100644 --- a/lib/script/stack.js +++ b/lib/script/stack.js @@ -56,7 +56,7 @@ Stack.prototype.__defineSetter__('length', function(length) { */ Stack.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/script/witness.js b/lib/script/witness.js index 03741f62c..aaa45643e 100644 --- a/lib/script/witness.js +++ b/lib/script/witness.js @@ -138,7 +138,7 @@ Witness.fromArray = function fromArray(items) { */ Witness.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/utils/ip.js b/lib/utils/ip.js index 63e561789..1969f5e19 100644 --- a/lib/utils/ip.js +++ b/lib/utils/ip.js @@ -131,12 +131,10 @@ IP.fromHostname = function fromHostname(addr, fallback) { host = IP.toString(raw); } - hostname = host; - if (type === IP.types.IPV6) - hostname = '[' + hostname + ']'; - - hostname += ':' + port; + hostname = `[${host}]:${port}`; + else + hostname = `${host}:${port}`; return new Address(host, port, type, hostname, raw); }; @@ -167,9 +165,9 @@ IP.toHostname = function toHostname(host, port) { host = IP.normalize(host); if (type === IP.types.IPV6) - host = '[' + host + ']'; + return `[${host}]:${port}`; - return host + ':' + port; + return `${host}:${port}`; }; /** @@ -424,7 +422,7 @@ IP.toString = function toString(raw) { if (IP.isOnion(raw)) { host = base32.encode(raw.slice(6)); - return host + '.onion'; + return `${host}.onion`; } host += raw.readUInt16BE(0, true).toString(16); diff --git a/lib/utils/pem.js b/lib/utils/pem.js index b2d108735..0878e7e6c 100644 --- a/lib/utils/pem.js +++ b/lib/utils/pem.js @@ -120,7 +120,7 @@ PEM.encode = function encode(der, type, suffix) { pem += der.slice(i, i + 64) + '\n'; return '' - + '-----BEGIN ' + type + '-----\n' - + pem - + '-----END ' + type + '-----\n'; + + `-----BEGIN ${type}-----\n` + + `${pem}` + + `-----END ${type}-----\n`; }; diff --git a/lib/utils/validator.js b/lib/utils/validator.js index 7982377d0..c0374e81e 100644 --- a/lib/utils/validator.js +++ b/lib/utils/validator.js @@ -585,7 +585,7 @@ Validator.prototype.func = function func(key, fallback) { function fmt(key) { if (typeof key === 'number') - return 'Param #' + key; + return `Param #${key}`; return key; } @@ -605,7 +605,7 @@ function ValidationError(key, type) { Error.captureStackTrace(this, ValidationError); this.type = 'ValidationError'; - this.message = `${fmt(key)} must be a ${type}.` + this.message = `${fmt(key)} must be a ${type}.`; } inherits(ValidationError, Error); diff --git a/lib/wallet/http.js b/lib/wallet/http.js index daacac10f..b631d8a26 100644 --- a/lib/wallet/http.js +++ b/lib/wallet/http.js @@ -8,6 +8,7 @@ 'use strict'; const assert = require('assert'); +const path = require('path'); const HTTPBase = require('../http/base'); const util = require('../utils/util'); const base58 = require('../utils/base58'); @@ -1010,8 +1011,8 @@ HTTPOptions.prototype.fromOptions = function fromOptions(options) { if (options.prefix != null) { assert(typeof options.prefix === 'string'); this.prefix = options.prefix; - this.keyFile = this.prefix + '/key.pem'; - this.certFile = this.prefix + '/cert.pem'; + this.keyFile = path.join(this.prefix, 'key.pem'); + this.certFile = path.join(this.prefix, 'cert.pem'); } if (options.host != null) { diff --git a/lib/wallet/path.js b/lib/wallet/path.js index 0f54833eb..88db8b55a 100644 --- a/lib/wallet/path.js +++ b/lib/wallet/path.js @@ -277,9 +277,7 @@ Path.prototype.toPath = function toPath() { if (this.keyType !== Path.types.HD) return null; - return 'm/' + this.account - + '\'/' + this.branch - + '/' + this.index; + return `m/${this.account}'/${this.branch}/${this.index}`; }; /** @@ -311,11 +309,7 @@ Path.prototype.toJSON = function toJSON() { */ Path.prototype.inspect = function inspect() { - return ''; + return ``; }; /** diff --git a/lib/wallet/txdb.js b/lib/wallet/txdb.js index 532edf1b4..c63b1fc4d 100644 --- a/lib/wallet/txdb.js +++ b/lib/wallet/txdb.js @@ -2586,8 +2586,8 @@ Balance.prototype.toJSON = function toJSON(minimal) { Balance.prototype.toString = function toString() { return ''; }; diff --git a/lib/wallet/walletdb.js b/lib/wallet/walletdb.js index dd3f9de8b..1864ff716 100644 --- a/lib/wallet/walletdb.js +++ b/lib/wallet/walletdb.js @@ -8,6 +8,7 @@ 'use strict'; const assert = require('assert'); +const path = require('path'); const AsyncObject = require('../utils/asyncobject'); const util = require('../utils/util'); const Lock = require('../utils/lock'); @@ -2238,7 +2239,7 @@ WalletOptions.prototype.fromOptions = function fromOptions(options) { if (options.prefix != null) { assert(typeof options.prefix === 'string'); this.prefix = options.prefix; - this.location = this.prefix + '/walletdb'; + this.location = path.join(this.prefix, 'walletdb'); } if (options.location != null) { diff --git a/migrate/chaindb0to1.js b/migrate/chaindb0to1.js index 5af5155e8..86db9e011 100644 --- a/migrate/chaindb0to1.js +++ b/migrate/chaindb0to1.js @@ -39,7 +39,7 @@ async function checkVersion() { ver = data.readUInt32LE(0, true); if (ver !== 0) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); } async function updateState() { diff --git a/migrate/chaindb1to2.js b/migrate/chaindb1to2.js index ba3e209b1..3792837e2 100644 --- a/migrate/chaindb1to2.js +++ b/migrate/chaindb1to2.js @@ -56,7 +56,7 @@ async function updateVersion() { ver = data.readUInt32LE(0, true); if (ver !== 1) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); ver = Buffer.allocUnsafe(4); ver.writeUInt32LE(2, 0, true); diff --git a/migrate/ensure-tip-index.js b/migrate/ensure-tip-index.js index 402f3e4c5..084637c87 100644 --- a/migrate/ensure-tip-index.js +++ b/migrate/ensure-tip-index.js @@ -37,7 +37,7 @@ async function checkVersion() { ver = data.readUInt32LE(0, true); if (ver !== 1) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); } function entryFromRaw(data) { diff --git a/migrate/walletdb2to3.js b/migrate/walletdb2to3.js index 2a438fc65..b7c22a63e 100644 --- a/migrate/walletdb2to3.js +++ b/migrate/walletdb2to3.js @@ -28,7 +28,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = process.env.HOME + '/walletdb-bak-' + Date.now() + '.ldb'; + let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -39,7 +39,7 @@ async function updateVersion() { ver = data.readUInt32LE(0, true); if (ver !== 2) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); console.log('Backing up DB to: %s.', bak); diff --git a/migrate/walletdb3to4.js b/migrate/walletdb3to4.js index 48827530e..005db2c06 100644 --- a/migrate/walletdb3to4.js +++ b/migrate/walletdb3to4.js @@ -25,7 +25,7 @@ db = bcoin.ldb({ }); async function updateVersion() { - let bak = process.env.HOME + '/walletdb-bak-' + Date.now() + '.ldb'; + let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -36,7 +36,7 @@ async function updateVersion() { ver = data.readUInt32LE(0, true); if (ver !== 3) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); console.log('Backing up DB to: %s.', bak); diff --git a/migrate/walletdb4to5.js b/migrate/walletdb4to5.js index fcba5bd0f..760ba34e7 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'; + let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -30,7 +30,7 @@ async function updateVersion() { ver = data.readUInt32LE(0, true); if (ver !== 4) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); console.log('Backing up DB to: %s.', bak); diff --git a/migrate/walletdb5to6.js b/migrate/walletdb5to6.js index 37b7e79cd..371897ba9 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'; + let bak = `${process.env.HOME}/walletdb-bak-${Date.now()}.ldb`; let data, ver; console.log('Checking version.'); @@ -33,7 +33,7 @@ async function updateVersion() { ver = data.readUInt32LE(0, true); if (ver !== 5) - throw Error('DB is version ' + ver + '.'); + throw Error(`DB is version ${ver}.`); console.log('Backing up DB to: %s.', bak); diff --git a/scripts/dump.js b/scripts/dump.js index 412c103ab..1af07baf8 100644 --- a/scripts/dump.js +++ b/scripts/dump.js @@ -7,12 +7,12 @@ const Coins = require('../lib/coins/coins'); const TX = require('../lib/primitives/tx'); const CoinView = require('../lib/coins/coinview'); -let SNAPSHOT = __dirname + '/../dump.heapsnapshot'; +let SNAPSHOT = `${__dirname}/../dump.heapsnapshot`; let tx = parseTX('../test/data/tx4.hex'); let raw, coins, entry; function parseTX(file) { - let data = fs.readFileSync(__dirname + '/' + file, 'utf8'); + let data = fs.readFileSync(`${__dirname}/${file}`, 'utf8'); let parts = data.trim().split(/\n+/); let raw = parts[0]; let tx = TX.fromRaw(raw.trim(), 'hex'); diff --git a/test/bech32-test.js b/test/bech32-test.js index a97888eb1..a50a28551 100644 --- a/test/bech32-test.js +++ b/test/bech32-test.js @@ -127,7 +127,7 @@ describe('Bech32', function() { } VALID_CHECKSUM.forEach((test) => { - it('should have valid checksum for ' + test, () => { + it(`should have valid checksum for ${test}`, () => { let ret = bech32.deserialize(test); assert(ret); }); @@ -136,7 +136,7 @@ describe('Bech32', function() { VALID_ADDRESS.forEach((test) => { let address = test[0]; let scriptpubkey = test[1]; - it('should have valid address for ' + address, () => { + it(`should have valid address for ${address}`, () => { let hrp = 'bc'; let ret, ok, output, recreate; @@ -172,7 +172,7 @@ describe('Bech32', function() { }); INVALID_ADDRESS.forEach((test) => { - it('should have invalid address for ' + test, () => { + it(`should have invalid address for ${test}`, () => { let ok1, ok2, ok; try { @@ -201,7 +201,7 @@ describe('Bech32', function() { if (i >= 2 && i <= 4) return; - it('should have valid address for ' + address, () => { + it(`should have valid address for ${address}`, () => { let ret, ok, output, recreate; try { @@ -235,7 +235,7 @@ describe('Bech32', function() { }); INVALID_ADDRESS.forEach((test) => { - it('should have invalid address for ' + test, () => { + it(`should have invalid address for ${test}`, () => { let ok1, ok2; try { diff --git a/test/block-test.js b/test/block-test.js index d0286a49f..5b7f32139 100644 --- a/test/block-test.js +++ b/test/block-test.js @@ -16,10 +16,10 @@ const encoding = require('../lib/utils/encoding'); const bip152 = require('../lib/net/bip152'); const block300025 = require('./data/block300025.json'); -const cmpct2block = fs.readFileSync(__dirname + '/data/cmpct2.bin'); +const cmpct2block = fs.readFileSync(`${__dirname}/data/cmpct2.bin`); -let cmpct1 = fs.readFileSync(__dirname + '/data/compactblock.hex', 'utf8'); -let cmpct2 = fs.readFileSync(__dirname + '/data/cmpct2', 'utf8'); +let cmpct1 = fs.readFileSync(`${__dirname}/data/compactblock.hex`, 'utf8'); +let cmpct2 = fs.readFileSync(`${__dirname}/data/cmpct2`, 'utf8'); cmpct1 = cmpct1.trim().split('\n'); cmpct2 = cmpct2.trim(); @@ -448,8 +448,8 @@ describe('Block', function() { }); it('should count sigops for block 928828 (testnet)', () => { - let blockRaw = fs.readFileSync(__dirname + '/data/block928828.raw'); - let undoRaw = fs.readFileSync(__dirname + '/data/undo928828.raw'); + let blockRaw = fs.readFileSync(`${__dirname}/data/block928828.raw`); + let undoRaw = fs.readFileSync(`${__dirname}/data/undo928828.raw`); let block = Block.fromRaw(blockRaw); let undo = UndoCoins.fromRaw(undoRaw); let view = applyUndo(block, undo); @@ -467,8 +467,8 @@ describe('Block', function() { }); it('should count sigops for block 928927 (testnet)', () => { - let blockRaw = fs.readFileSync(__dirname + '/data/block928927.raw'); - let undoRaw = fs.readFileSync(__dirname + '/data/undo928927.raw'); + let blockRaw = fs.readFileSync(`${__dirname}/data/block928927.raw`); + let undoRaw = fs.readFileSync(`${__dirname}/data/undo928927.raw`); let block = Block.fromRaw(blockRaw); let undo = UndoCoins.fromRaw(undoRaw); let view = applyUndo(block, undo); @@ -486,8 +486,8 @@ describe('Block', function() { }); it('should count sigops for block 1087400 (testnet)', () => { - let blockRaw = fs.readFileSync(__dirname + '/data/block1087400.raw'); - let undoRaw = fs.readFileSync(__dirname + '/data/undo1087400.raw'); + let blockRaw = fs.readFileSync(`${__dirname}/data/block1087400.raw`); + let undoRaw = fs.readFileSync(`${__dirname}/data/undo1087400.raw`); let block = Block.fromRaw(blockRaw); let undo = UndoCoins.fromRaw(undoRaw); let view = applyUndo(block, undo); diff --git a/test/gcs-test.js b/test/gcs-test.js index 8f0f64dd0..179d79e4e 100644 --- a/test/gcs-test.js +++ b/test/gcs-test.js @@ -8,7 +8,7 @@ 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 raw = fs.readFileSync(`${__dirname}/data/block928927.raw`); let block = Block.fromRaw(raw); describe('GCS', function() { diff --git a/test/hd-test.js b/test/hd-test.js index 3cd2a2a29..fb2a5db06 100644 --- a/test/hd-test.js +++ b/test/hd-test.js @@ -106,7 +106,7 @@ describe('HD', function() { if (path === 'seed' || path === 'm') return; - it('should derive ' + path + ' from master', () => { + it(`should derive ${path} from master`, () => { let key = master.derivePath(path); equal(key.toBase58(), kp.prv); equal(key.toPublic().toBase58(), kp.pub); diff --git a/test/mnemonic-test.js b/test/mnemonic-test.js index c4de3e42c..bd5186e3d 100644 --- a/test/mnemonic-test.js +++ b/test/mnemonic-test.js @@ -12,7 +12,7 @@ describe('Mnemonic', function() { let phrase = data[1]; let seed = Buffer.from(data[2], 'hex'); let xpriv = data[3]; - it('should create an english mnemonic (' + i + ')', () => { + it(`should create an english mnemonic (${i})`, () => { let mnemonic, key; mnemonic = new HD.Mnemonic({ @@ -35,7 +35,7 @@ describe('Mnemonic', function() { let seed = Buffer.from(data.seed, 'hex'); let passphrase = data.passphrase; let xpriv = data.bip32_xprv; - it('should create a japanese mnemonic (' + i + ')', () => { + it(`should create a japanese mnemonic (${i})`, () => { let mnemonic, key; mnemonic = new HD.Mnemonic({ diff --git a/test/protocol-test.js b/test/protocol-test.js index 8908a7339..b40f38fcb 100644 --- a/test/protocol-test.js +++ b/test/protocol-test.js @@ -12,7 +12,7 @@ const network = Network.get('main'); describe('Protocol', function() { let pkg = require('../lib/pkg'); - let agent = '/bcoin:' + pkg.version + '/'; + let agent = `/bcoin:${pkg.version}/`; let parser, framer, v1, v2, hosts; beforeEach(() => { @@ -21,7 +21,7 @@ describe('Protocol', function() { }); function packetTest(command, payload, test) { - it('should encode/decode ' + command, (cb) => { + it(`should encode/decode ${command}`, (cb) => { let ver = Buffer.from(framer.packet(command, payload.toRaw())); parser.once('packet', (packet) => { assert.equal(packet.cmd, command); diff --git a/test/script-test.js b/test/script-test.js index 842ba5f36..825eca92f 100644 --- a/test/script-test.js +++ b/test/script-test.js @@ -232,12 +232,11 @@ 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 flags = data[2] ? data[2].trim().split(/,\s*/) : []; + let names = data[2] ? data[2].trim().split(/,\s*/) : []; let expected = data[3] || ''; let comments = Array.isArray(data[4]) ? data[4].join('. ') : data[4] || ''; let amount = 0; - let flag = 0; - let i, name; + let flags = 0; if (data.length === 1) return; @@ -245,7 +244,7 @@ describe('Script', function() { if (!comments) comments = output.slice(0, 60); - comments += ' (' + expected + ')'; + comments += ` (${expected})`; if (witness.length !== 0) amount = witness.pop() * 100000000; @@ -254,17 +253,15 @@ describe('Script', function() { input = Script.fromString(input); output = Script.fromString(output); - for (i = 0; i < flags.length; i++) { - name = 'VERIFY_' + flags[i]; + for (let name of names) { + name = `VERIFY_${name}`; assert(Script.flags[name] != null, 'Unknown flag.'); - flag |= Script.flags[name]; + flags |= Script.flags[name]; } - flags = flag; - [false, true].forEach((noCache) => { - let suffix = noCache ? ' without cache' : ' with cache'; - it('should handle script test' + suffix + ': ' + comments, () => { + let suffix = noCache ? 'without cache' : 'with cache'; + it(`should handle script test ${suffix}:${comments}`, () => { let prev, tx, err, res; // Funding transaction. diff --git a/test/tx-test.js b/test/tx-test.js index 97e49eb0a..ef0dda2e0 100644 --- a/test/tx-test.js +++ b/test/tx-test.js @@ -38,29 +38,27 @@ function clearCache(tx, noCache) { } function parseTest(data) { - let coins = data[0]; - let tx = TX.fromRaw(data[1], 'hex'); - let flags = data[2] ? data[2].trim().split(/,\s*/) : []; + let [coins, tx, names] = data; let view = new CoinView(); - let flag = 0; - let i, name, coin, hash, index; - let item, script, amount, value; + let flags = 0; + let coin; - for (i = 0; i < flags.length; i++) { - name = 'VERIFY_' + flags[i]; + if (!names) + names = ''; + + tx = TX.fromRaw(tx, 'hex'); + names = names.trim().split(/,\s*/); + + for (let name of names) { + name = `VERIFY_${name}`; assert(Script.flags[name] != null, 'Unknown flag.'); - flag |= Script.flags[name]; + flags |= Script.flags[name]; } - flags = flag; - - for (i = 0; i < coins.length; i++) { - item = coins[i]; - hash = util.revHex(item[0]); - index = item[1]; - script = Script.fromString(item[2]); - amount = item[3] != null ? item[3] : '0'; - value = parseInt(amount, 10); + for (let [hash, index, script, value] of coins) { + hash = util.revHex(hash); + script = Script.fromString(script); + value = parseInt(value || '0', 10); if (index === -1) continue; @@ -169,15 +167,15 @@ describe('TX', function() { '2e88ac00000000'; [false, true].forEach((noCache) => { - let suffix = noCache ? ' without cache' : ' with cache'; + let suffix = noCache ? 'without cache' : 'with cache'; - it('should decode/encode with parser/framer' + suffix, () => { + it(`should decode/encode with parser/framer ${suffix}`, () => { let tx = TX.fromRaw(raw, 'hex'); clearCache(tx, noCache); assert.equal(tx.toRaw().toString('hex'), raw); }); - it('should be verifiable' + suffix, () => { + it(`should be verifiable ${suffix}`, () => { let tx = TX.fromRaw(raw, 'hex'); let p = TX.fromRaw(inp, 'hex'); let view = new CoinView(); @@ -189,34 +187,34 @@ describe('TX', function() { assert(tx.verify(view)); }); - it('should verify non-minimal output' + suffix, () => { + it(`should verify non-minimal output ${suffix}`, () => { clearCache(tx1.tx, noCache); assert(tx1.tx.verify(tx1.view, Script.flags.VERIFY_P2SH)); }); - it('should verify tx.version == 0' + suffix, () => { + it(`should verify tx.version == 0 ${suffix}`, () => { clearCache(tx2.tx, noCache); assert(tx2.tx.verify(tx2.view, Script.flags.VERIFY_P2SH)); }); - it('should verify sighash_single bug w/ findanddelete' + suffix, () => { + it(`should verify sighash_single bug w/ findanddelete ${suffix}`, () => { clearCache(tx3.tx, noCache); assert(tx3.tx.verify(tx3.view, Script.flags.VERIFY_P2SH)); }); - it('should verify high S value with only DERSIG enabled' + suffix, () => { + it(`should verify high S value with only DERSIG enabled ${suffix}`, () => { let coin = tx4.view.getOutput(tx4.tx.inputs[0]); let flags = Script.flags.VERIFY_P2SH | Script.flags.VERIFY_DERSIG; clearCache(tx4.tx, noCache); assert(tx4.tx.verifyInput(0, coin, flags)); }); - it('should verify the coolest tx ever sent' + suffix, () => { + it(`should verify the coolest tx ever sent ${suffix}`, () => { clearCache(coolest.tx, noCache); assert(coolest.tx.verify(coolest.view, Script.flags.VERIFY_NONE)); }); - it('should parse witness tx properly' + suffix, () => { + it(`should parse witness tx properly ${suffix}`, () => { let raw1, raw2, wtx2; clearCache(wtx.tx, noCache); @@ -245,8 +243,7 @@ describe('TX', function() { }); [[valid, true], [invalid, false]].forEach((test) => { - let arr = test[0]; - let valid = test[1]; + let [arr, valid] = test; let comment = ''; arr.forEach((json, i) => { @@ -276,19 +273,19 @@ describe('TX', function() { if (valid) { if (comments.indexOf('Coinbase') === 0) { - it('should handle valid coinbase' + suffix + ': ' + comments, () => { + it(`should handle valid coinbase ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.isSane()); }); return; } - it('should handle valid tx test' + suffix + ': ' + comments, () => { + it(`should handle valid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); }); } else { if (comments === 'Duplicate inputs') { - it('should handle duplicate input test' + suffix + ': ' + comments, () => { + it(`should handle duplicate input test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); assert.ok(!tx.isSane()); @@ -296,7 +293,7 @@ describe('TX', function() { return; } if (comments === 'Negative output') { - it('should handle invalid tx (negative)' + suffix + ': ' + comments, () => { + it(`should handle invalid tx (negative) ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(tx.verify(view, flags)); assert.ok(!tx.isSane()); @@ -304,13 +301,13 @@ describe('TX', function() { return; } if (comments.indexOf('Coinbase') === 0) { - it('should handle invalid coinbase' + suffix + ': ' + comments, () => { + it(`should handle invalid coinbase ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(!tx.isSane()); }); return; } - it('should handle invalid tx test' + suffix + ': ' + comments, () => { + it(`should handle invalid tx test ${suffix}: ${comments}`, () => { clearCache(tx, noCache); assert.ok(!tx.verify(view, flags)); }); @@ -319,34 +316,28 @@ describe('TX', function() { }); sighash.forEach((data) => { - let name, tx, script, index; - let type, expected, hexType; + let [tx, script, index, type, hash] = data; + let expected, hex; if (data.length === 1) return; - tx = TX.fromRaw(data[0], 'hex'); - clearCache(tx, noCache); - - script = Script.fromRaw(data[1], 'hex'); - - index = data[2]; - type = data[3]; - expected = util.revHex(data[4]); - hexType = type & 3; + tx = TX.fromRaw(tx, 'hex'); + script = Script.fromRaw(script, 'hex'); + expected = util.revHex(hash); + hex = type & 3; if (type & 0x80) - hexType |= 0x80; + hex |= 0x80; - hexType = hexType.toString(16); + hex = hex.toString(16); - if (hexType.length % 2 !== 0) - hexType = '0' + hexType; + if (hex.length % 2 !== 0) + hex = '0' + hex; - name = 'should get signature hash of ' - + data[4] + ' (' + hexType + ')' + suffix; + clearCache(tx, noCache); - it(name, () => { + it(`should get sighash of ${hash} (${hex}) ${suffix}`, () => { let subscript = script.getSubscript(0).removeSeparators(); let hash = tx.signatureHash(index, subscript, 0, type, 0); assert.equal(hash.toString('hex'), expected); diff --git a/test/util/common.js b/test/util/common.js index 3418193a5..e0070f26c 100644 --- a/test/util/common.js +++ b/test/util/common.js @@ -5,7 +5,7 @@ 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 data = fs.readFileSync(`${__dirname}/../${file}`, 'utf8'); let parts = data.trim().split(/\n+/); let raw = parts[0]; let tx = TX.fromRaw(raw.trim(), 'hex'); diff --git a/test/util/node-context.js b/test/util/node-context.js index a889dc508..b8f8c6db0 100644 --- a/test/util/node-context.js +++ b/test/util/node-context.js @@ -24,10 +24,8 @@ NodeContext.prototype.init = function() { port = this.network.port + i; last = port - 1; - if (last < this.network.port) { - // last = this.network.port + this.size - 1; + if (last < this.network.port) last = port; - } node = new FullNode({ network: this.network, @@ -44,7 +42,7 @@ NodeContext.prototype.init = function() { host: '127.0.0.1', port: port, seeds: [ - '127.0.0.1:' + last + `127.0.0.1:${last}` ] }); @@ -58,33 +56,24 @@ NodeContext.prototype.init = function() { NodeContext.prototype.open = function open() { let jobs = []; - let i, node; - for (i = 0; i < this.nodes.length; i++) { - node = this.nodes[i]; + for (let node of this.nodes) jobs.push(node.open()); - } return Promise.all(jobs); }; NodeContext.prototype.close = function close() { let jobs = []; - let i, node; - for (i = 0; i < this.nodes.length; i++) { - node = this.nodes[i]; + for (let node of this.nodes) jobs.push(node.close()); - } return Promise.all(jobs); }; NodeContext.prototype.connect = async function connect() { - let i, node; - - for (i = 0; i < this.nodes.length; i++) { - node = this.nodes[i]; + for (let node of this.nodes) { await node.connect(); await co.timeout(1000); } @@ -101,10 +90,7 @@ NodeContext.prototype.disconnect = async function disconnect() { }; NodeContext.prototype.startSync = function startSync() { - let i, node; - - for (i = 0; i < this.nodes.length; i++) { - node = this.nodes[i]; + for (let node of this.nodes) { node.chain.synced = true; node.chain.emit('full'); node.startSync(); @@ -112,12 +98,8 @@ NodeContext.prototype.startSync = function startSync() { }; NodeContext.prototype.stopSync = function stopSync() { - let i, node; - - for (i = 0; i < this.nodes.length; i++) { - node = this.nodes[i]; + for (let node of this.nodes) node.stopSync(); - } }; NodeContext.prototype.generate = async function generate(index, blocks) { diff --git a/test/utils-test.js b/test/utils-test.js index a920d2829..98313f44e 100644 --- a/test/utils-test.js +++ b/test/utils-test.js @@ -20,8 +20,14 @@ describe('Utils', function() { ['61', '2g'], ['626262', 'a3gV'], ['636363', 'aPEr'], - ['73696d706c792061206c6f6e6720737472696e67', '2cFupjhnEsSn59qHXstmK2ffpLv2'], - ['00eb15231dfceb60925886b67d065299925915aeb172c06647', '1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L'], + [ + '73696d706c792061206c6f6e6720737472696e67', + '2cFupjhnEsSn59qHXstmK2ffpLv2' + ], + [ + '00eb15231dfceb60925886b67d065299925915aeb172c06647', + '1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L' + ], ['516b6fcd0f', 'ABnLTmg'], ['bf4f89001e670274dd', '3SEo3LWLoPntC'], ['572e4794', '3EFU7m'], @@ -200,9 +206,9 @@ describe('Utils', function() { unsigned.forEach((num) => { let buf1 = Buffer.allocUnsafe(8); let buf2 = Buffer.allocUnsafe(8); - let msg = 'should write+read a ' + num.bitLength() + ' bit unsigned int'; + let bits = num.bitLength(); - it(msg, () => { + it(`should write+read a ${bits} bit unsigned int`, () => { let n1, n2; encoding.writeU64BN(buf1, num, 0); @@ -218,10 +224,10 @@ describe('Utils', function() { signed.forEach((num) => { let buf1 = Buffer.allocUnsafe(8); let buf2 = Buffer.allocUnsafe(8); - let msg = 'should write+read a ' + num.bitLength() - + ' bit ' + (num.isNeg() ? 'negative' : 'positive') + ' int'; + let bits = num.bitLength(); + let sign = num.isNeg() ? 'negative' : 'positive'; - it(msg, () => { + it(`should write+read a ${bits} bit ${sign} int`, () => { let n1, n2; encoding.write64BN(buf1, num, 0); @@ -233,10 +239,7 @@ describe('Utils', function() { assert.equal(n1.toNumber(), n2); }); - msg = 'should write+read a ' + num.bitLength() - + ' bit ' + (num.isNeg() ? 'negative' : 'positive') + ' int as unsigned'; - - it(msg, () => { + it(`should write+read a ${bits} bit ${sign} int as unsigned`, () => { let n1, n2; encoding.writeU64BN(buf1, num, 0); @@ -245,9 +248,7 @@ describe('Utils', function() { n1 = encoding.readU64BN(buf1, 0); if (num.isNeg()) { - assert.throws(() => { - encoding.readU64(buf2, 0); - }); + assert.throws(() => encoding.readU64(buf2, 0)); } else { n2 = encoding.readU64(buf2, 0); assert.equal(n1.toNumber(), n2); diff --git a/webpack.node.js b/webpack.node.js index 960cc8aed..76541c303 100644 --- a/webpack.node.js +++ b/webpack.node.js @@ -20,7 +20,7 @@ module.exports = { modules: ['node_modules'], extensions: ['.node', '.js', '.json'], alias: { - 'bindings': __dirname + '/webpack/bindings.js' + 'bindings': path.resolve(__dirname, 'webpack', 'bindings.js') } }, node: { diff --git a/webpack/bindings.js b/webpack/bindings.js index 919b3d236..b8ed4ff15 100644 --- a/webpack/bindings.js +++ b/webpack/bindings.js @@ -9,5 +9,5 @@ module.exports = function bindings(name) { case 'secp256k1': return require('secp256k1/build/Release/secp256k1.node'); } - throw new Error('Cannot find module "' + name + '".'); + throw new Error(`Cannot find module "${name}".`); };