fix(linting): Adding standard linting rules

This commit is contained in:
Chris Troutner
2021-01-02 15:41:12 -08:00
parent bdb4de0353
commit 3cedd251e5
102 changed files with 7280 additions and 5955 deletions
+30
View File
@@ -0,0 +1,30 @@
# http://editorconfig.org
# A special property that should be specified at the top of the file outside of
# any sections. Set to true to stop .editor config file search on current file
root = true
[*]
# Indentation style
# Possible values - tab, space
indent_style = space
# Indentation size in single-spaced characters
# Possible values - an integer, tab
indent_size = 2
# Line ending file format
# Possible values - lf, crlf, cr
end_of_line = lf
# File character encoding
# Possible values - latin1, utf-8, utf-16be, utf-16le
charset = utf-8
# Denotes whether to trim whitespace at the end of lines
# Possible values - true, false
trim_trailing_whitespace = true
# Denotes whether file should end with a newline
# Possible values - true, false
insert_final_newline = true
+6 -51
View File
@@ -1,55 +1,10 @@
{ {
"root": true, "extends": "standard",
"parserOptions": { "env": {
"ecmaVersion": 2018, "node": true,
"sourceType": "module" "mocha": true
}, },
"plugins": ["prettier"], "parserOptions": {
"rules": { "ecmaVersion": 8
"no-debugger": ["warn"],
"no-regex-spaces": ["error"],
"no-unsafe-negation": ["error"],
"curly": ["error", "multi-or-nest", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": ["error"],
"eqeqeq": ["error", "smart"],
"no-else-return": ["error"],
"no-extra-bind": ["error"],
"no-extra-label": ["error"],
"no-floating-decimal": ["error"],
"no-implicit-coercion": ["error", { "allow": ["!!"] }],
"wrap-iife": ["error", "inside"],
"strict": ["error", "global"],
"func-call-spacing": ["error", "never"],
"comma-style": ["error", "last"],
"keyword-spacing": ["error"],
"linebreak-style": ["error", "unix"],
"new-parens": ["error"],
"no-lonely-if": ["error"],
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1 }],
"no-whitespace-before-property": ["error"],
"semi": ["error", "never"],
"arrow-body-style": ["error", "as-needed"],
"arrow-parens": ["error", "as-needed"],
"arrow-spacing": ["error"],
"no-useless-computed-key": ["error"],
"no-useless-rename": ["error"],
"no-var": ["off"],
"prefer-spread": ["off"],
"prefer-template": ["error"],
"rest-spread-spacing": ["error", "never"],
"prefer-const": ["warn", { "destructuring": "all" }],
"no-unreachable": ["warn"],
"no-unused-vars": ["warn", { "args": "none" }],
"prettier/prettier": [
"warn",
{
"printWidth": 80,
"trailingComma": "none",
"singleQuote": false,
"semi": false
}
]
} }
} }
+1523 -215
View File
File diff suppressed because it is too large Load Diff
+6 -2
View File
@@ -20,7 +20,8 @@
"test:temp2": "mocha --timeout 30000 -g '#getStatus' test/unit/", "test:temp2": "mocha --timeout 30000 -g '#getStatus' test/unit/",
"coverage": "nyc report --reporter=text-lcov | coveralls", "coverage": "nyc report --reporter=text-lcov | coveralls",
"coverage:report": "nyc --reporter=html mocha --timeout 25000 test/unit/", "coverage:report": "nyc --reporter=html mocha --timeout 25000 test/unit/",
"docs": "./node_modules/.bin/apidoc -i src/ -o docs" "docs": "./node_modules/.bin/apidoc -i src/ -o docs",
"lint": "standard --env mocha --fix"
}, },
"license": "MIT", "license": "MIT",
"homepage": "https://github.com/Permissionless-Software-Foundation/bch-js", "homepage": "https://github.com/Permissionless-Software-Foundation/bch-js",
@@ -79,8 +80,10 @@
"coveralls": "^3.0.2", "coveralls": "^3.0.2",
"eslint": "5.16.0", "eslint": "5.16.0",
"eslint-config-prettier": "^6.0.0", "eslint-config-prettier": "^6.0.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-node": "^9.1.0", "eslint-plugin-node": "^9.1.0",
"eslint-plugin-prettier": "^3.1.0", "eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-standard": "^4.0.0",
"lodash.clonedeep": "^4.5.0", "lodash.clonedeep": "^4.5.0",
"mocha": "^6.1.4", "mocha": "^6.1.4",
"nock": "^10.0.6", "nock": "^10.0.6",
@@ -88,7 +91,8 @@
"nyc": "^14.1.0", "nyc": "^14.1.0",
"prettier": "^1.18.2", "prettier": "^1.18.2",
"semantic-release": "^17.3.1", "semantic-release": "^17.3.1",
"sinon": "^7.3.2" "sinon": "^7.3.2",
"standard": "^16.0.3"
}, },
"apidoc": { "apidoc": {
"title": "bch-js", "title": "bch-js",
+57 -56
View File
@@ -1,12 +1,12 @@
// const axios = require("axios") // const axios = require("axios")
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const cashaddr = require("cashaddrjs") const cashaddr = require('cashaddrjs')
const coininfo = require("@psf/coininfo") const coininfo = require('@psf/coininfo')
class Address { class Address {
constructor (config) { constructor (config) {
const tmp = {} const tmp = {}
if (!config || !config.restURL) tmp.restURL = `https://api.bchjs.cash/v4/` if (!config || !config.restURL) tmp.restURL = 'https://api.bchjs.cash/v4/'
else tmp.restURL = config.restURL else tmp.restURL = config.restURL
this.restURL = tmp.restURL this.restURL = tmp.restURL
@@ -59,29 +59,29 @@ class Address {
let bitcoincash let bitcoincash
switch (prefix) { switch (prefix) {
case "bitcoincash": case 'bitcoincash':
bitcoincash = coininfo.bitcoincash.main bitcoincash = coininfo.bitcoincash.main
break break
case "bchtest": case 'bchtest':
bitcoincash = coininfo.bitcoincash.test bitcoincash = coininfo.bitcoincash.test
break break
case "bchreg": case 'bchreg':
bitcoincash = coininfo.bitcoincash.regtest bitcoincash = coininfo.bitcoincash.regtest
break break
default: default:
throw `unsupported prefix : ${prefix}` throw new Error(`unsupported prefix : ${prefix}`)
} }
let version let version
switch (type) { switch (type) {
case "P2PKH": case 'P2PKH':
version = bitcoincash.versions.public version = bitcoincash.versions.public
break break
case "P2SH": case 'P2SH':
version = bitcoincash.versions.scripthash version = bitcoincash.versions.scripthash
break break
default: default:
throw `unsupported address type : ${type}` throw new Error(`unsupported address type : ${type}`)
} }
const hashBuf = Buffer.from(hash) const hashBuf = Buffer.from(hash)
@@ -116,7 +116,7 @@ class Address {
const decoded = this._decode(address) const decoded = this._decode(address)
let prefixString let prefixString
if (regtest) prefixString = "bchreg" if (regtest) prefixString = 'bchreg'
else prefixString = decoded.prefix else prefixString = decoded.prefix
const cashAddress = cashaddr.encode( const cashAddress = cashaddr.encode(
@@ -126,14 +126,14 @@ class Address {
) )
if (prefix) return cashAddress if (prefix) return cashAddress
return cashAddress.split(":")[1] return cashAddress.split(':')[1]
} }
// Converts any address format to hash160 // Converts any address format to hash160
toHash160 (address) { toHash160 (address) {
const legacyAddress = this.toLegacyAddress(address) const legacyAddress = this.toLegacyAddress(address)
const bytes = Bitcoin.address.fromBase58Check(legacyAddress) const bytes = Bitcoin.address.fromBase58Check(legacyAddress)
return bytes.hash.toString("hex") return bytes.hash.toString('hex')
} }
/** /**
@@ -157,7 +157,7 @@ class Address {
*/ */
// Converts hash160 to Legacy Address // Converts hash160 to Legacy Address
hash160ToLegacy (hash160, network = Bitcoin.networks.bitcoin.pubKeyHash) { hash160ToLegacy (hash160, network = Bitcoin.networks.bitcoin.pubKeyHash) {
const buffer = Buffer.from(hash160, "hex") const buffer = Buffer.from(hash160, 'hex')
const legacyAddress = Bitcoin.address.toBase58Check(buffer, network) const legacyAddress = Bitcoin.address.toBase58Check(buffer, network)
return legacyAddress return legacyAddress
} }
@@ -209,31 +209,31 @@ class Address {
switch (version) { switch (version) {
case info.main.versions.public: case info.main.versions.public:
return { return {
prefix: "bitcoincash", prefix: 'bitcoincash',
type: "P2PKH", type: 'P2PKH',
hash: hash, hash: hash,
format: "legacy" format: 'legacy'
} }
case info.main.versions.scripthash: case info.main.versions.scripthash:
return { return {
prefix: "bitcoincash", prefix: 'bitcoincash',
type: "P2SH", type: 'P2SH',
hash: hash, hash: hash,
format: "legacy" format: 'legacy'
} }
case info.test.versions.public: case info.test.versions.public:
return { return {
prefix: "bchtest", prefix: 'bchtest',
type: "P2PKH", type: 'P2PKH',
hash: hash, hash: hash,
format: "legacy" format: 'legacy'
} }
case info.test.versions.scripthash: case info.test.versions.scripthash:
return { return {
prefix: "bchtest", prefix: 'bchtest',
type: "P2SH", type: 'P2SH',
hash: hash, hash: hash,
format: "legacy" format: 'legacy'
} }
default: default:
throw new Error(`Invalid format : ${address}`) throw new Error(`Invalid format : ${address}`)
@@ -241,17 +241,17 @@ class Address {
} }
_decodeCashAddress (address) { _decodeCashAddress (address) {
if (address.indexOf(":") !== -1) { if (address.indexOf(':') !== -1) {
const decoded = cashaddr.decode(address) const decoded = cashaddr.decode(address)
decoded.format = "cashaddr" decoded.format = 'cashaddr'
return decoded return decoded
} }
const prefixes = ["bitcoincash", "bchtest", "bchreg"] const prefixes = ['bitcoincash', 'bchtest', 'bchreg']
for (let i = 0; i < prefixes.length; ++i) { for (let i = 0; i < prefixes.length; ++i) {
try { try {
const decoded = cashaddr.decode(`${prefixes[i]}:${address}`) const decoded = cashaddr.decode(`${prefixes[i]}:${address}`)
decoded.format = "cashaddr" decoded.format = 'cashaddr'
return decoded return decoded
} catch (error) {} } catch (error) {}
} }
@@ -264,7 +264,7 @@ class Address {
return { return {
legacyAddress: this.hash160ToLegacy(address), legacyAddress: this.hash160ToLegacy(address),
cashAddress: this.hash160ToCash(address), cashAddress: this.hash160ToCash(address),
format: "hash160" format: 'hash160'
} }
} catch (error) {} } catch (error) {}
@@ -304,7 +304,7 @@ class Address {
*/ */
// Test for address format. // Test for address format.
isLegacyAddress (address) { isLegacyAddress (address) {
return this.detectAddressFormat(address) === "legacy" return this.detectAddressFormat(address) === 'legacy'
} }
/** /**
@@ -339,7 +339,7 @@ class Address {
* // false * // false
*/ */
isCashAddress (address) { isCashAddress (address) {
return this.detectAddressFormat(address) === "cashaddr" return this.detectAddressFormat(address) === 'cashaddr'
} }
/** /**
@@ -358,7 +358,7 @@ class Address {
* // false * // false
*/ */
isHash160 (address) { isHash160 (address) {
return this.detectAddressFormat(address) === "hash160" return this.detectAddressFormat(address) === 'hash160'
} }
/** /**
@@ -394,10 +394,10 @@ class Address {
*/ */
// Test for address network. // Test for address network.
isMainnetAddress (address) { isMainnetAddress (address) {
if (address[0] === "x") return true if (address[0] === 'x') return true
else if (address[0] === "t") return false else if (address[0] === 't') return false
return this.detectAddressNetwork(address) === "mainnet" return this.detectAddressNetwork(address) === 'mainnet'
} }
/** /**
@@ -432,10 +432,10 @@ class Address {
* // true * // true
*/ */
isTestnetAddress (address) { isTestnetAddress (address) {
if (address[0] === "x") return false if (address[0] === 'x') return false
else if (address[0] === "t") return true else if (address[0] === 't') return true
return this.detectAddressNetwork(address) === "testnet" return this.detectAddressNetwork(address) === 'testnet'
} }
/** /**
@@ -474,7 +474,7 @@ class Address {
* // false * // false
*/ */
isRegTestAddress (address) { isRegTestAddress (address) {
return this.detectAddressNetwork(address) === "regtest" return this.detectAddressNetwork(address) === 'regtest'
} }
/** /**
@@ -511,7 +511,7 @@ class Address {
// Test for address type. // Test for address type.
isP2PKHAddress (address) { isP2PKHAddress (address) {
return this.detectAddressType(address) === "p2pkh" return this.detectAddressType(address) === 'p2pkh'
} }
/** /**
@@ -547,7 +547,7 @@ class Address {
*/ */
isP2SHAddress (address) { isP2SHAddress (address) {
return this.detectAddressType(address) === "p2sh" return this.detectAddressType(address) === 'p2sh'
} }
/** /**
@@ -621,18 +621,18 @@ class Address {
*/ */
// Detect address network. // Detect address network.
detectAddressNetwork (address) { detectAddressNetwork (address) {
if (address[0] === "x") return "mainnet" if (address[0] === 'x') return 'mainnet'
else if (address[0] === "t") return "testnet" else if (address[0] === 't') return 'testnet'
const decoded = this._decode(address) const decoded = this._decode(address)
switch (decoded.prefix) { switch (decoded.prefix) {
case "bitcoincash": case 'bitcoincash':
return "mainnet" return 'mainnet'
case "bchtest": case 'bchtest':
return "testnet" return 'testnet'
case "bchreg": case 'bchreg':
return "regtest" return 'regtest'
default: default:
throw new Error(`Invalid prefix : ${decoded.prefix}`) throw new Error(`Invalid prefix : ${decoded.prefix}`)
} }
@@ -705,7 +705,7 @@ class Address {
* // bchtest:qzd7dvlnfukggjqsf5ju0qqwwltakfumjsck33js6m * // bchtest:qzd7dvlnfukggjqsf5ju0qqwwltakfumjsck33js6m
* // bchtest:qq322ataqeas4n0pdn4gz2sdereh5ae43ylk4qdvus * // bchtest:qq322ataqeas4n0pdn4gz2sdereh5ae43ylk4qdvus
*/ */
fromXPub(xpub, path = "0/0") { fromXPub (xpub, path = '0/0') {
const HDNode = Bitcoin.HDNode.fromBase58( const HDNode = Bitcoin.HDNode.fromBase58(
xpub, xpub,
Bitcoin.networks[this.detectAddressNetwork(xpub)] Bitcoin.networks[this.detectAddressNetwork(xpub)]
@@ -738,12 +738,13 @@ class Address {
* bchjs.Address.fromOutputScript(scriptPubKey, 'testnet'); * bchjs.Address.fromOutputScript(scriptPubKey, 'testnet');
* // bchtest:pz0qcslrqn7hr44hsszwl4lw5r6udkg6zqh2hmtpyr * // bchtest:pz0qcslrqn7hr44hsszwl4lw5r6udkg6zqh2hmtpyr
*/ */
fromOutputScript(scriptPubKey, network = "mainnet") { fromOutputScript (scriptPubKey, network = 'mainnet') {
let netParam let netParam
if (network !== "bitcoincash" && network !== "mainnet") if (network !== 'bitcoincash' && network !== 'mainnet') {
netParam = Bitcoin.networks.testnet netParam = Bitcoin.networks.testnet
}
const regtest = network === "bchreg" const regtest = network === 'bchreg'
return this.toCashAddress( return this.toCashAddress(
Bitcoin.address.fromOutputScript(scriptPubKey, netParam), Bitcoin.address.fromOutputScript(scriptPubKey, netParam),
+31 -41
View File
@@ -7,66 +7,56 @@
*/ */
// bch-api mainnet. // bch-api mainnet.
const DEFAULT_REST_API = "https://api.fullstack.cash/v4/" const DEFAULT_REST_API = 'https://api.fullstack.cash/v4/'
// const DEFAULT_REST_API = "http://localhost:3000/v4/" // const DEFAULT_REST_API = "http://localhost:3000/v4/"
// local deps // local deps
const BitcoinCash = require("./bitcoincash") const BitcoinCash = require('./bitcoincash')
const Crypto = require("./crypto") const Crypto = require('./crypto')
const Util = require("./util") const Util = require('./util')
const Blockchain = require("./blockchain") const Blockchain = require('./blockchain')
const Control = require("./control") const Control = require('./control')
const Generating = require("./generating") const Generating = require('./generating')
const Mining = require("./mining") const Mining = require('./mining')
const RawTransactions = require("./raw-transactions") const RawTransactions = require('./raw-transactions')
const Mnemonic = require("./mnemonic") const Mnemonic = require('./mnemonic')
const Address = require("./address") const Address = require('./address')
const HDNode = require("./hdnode") const HDNode = require('./hdnode')
const TransactionBuilder = require("./transaction-builder") const TransactionBuilder = require('./transaction-builder')
const ECPair = require("./ecpair") const ECPair = require('./ecpair')
const Script = require("./script") const Script = require('./script')
const Price = require("./price") const Price = require('./price')
const Socket = require("./socket") const Socket = require('./socket')
const Schnorr = require("./schnorr") const Schnorr = require('./schnorr')
const SLP = require("./slp/slp") const SLP = require('./slp/slp')
const IPFS = require("./ipfs") const IPFS = require('./ipfs')
const Encryption = require("./encryption") const Encryption = require('./encryption')
// Indexers // Indexers
const OpenBazaar = require("./openbazaar") const OpenBazaar = require('./openbazaar')
const Ninsight = require("./ninsight") const Ninsight = require('./ninsight')
const Electrumx = require("./electrumx") const Electrumx = require('./electrumx')
class BCHJS { class BCHJS {
constructor (config) { constructor (config) {
// Try to retrieve the REST API URL from different sources. // Try to retrieve the REST API URL from different sources.
if (config && config.restURL && config.restURL !== "") if (config && config.restURL && config.restURL !== '') { this.restURL = config.restURL } else if (process.env.RESTURL && process.env.RESTURL !== '') { this.restURL = process.env.RESTURL } else this.restURL = DEFAULT_REST_API
this.restURL = config.restURL
else if (process.env.RESTURL && process.env.RESTURL !== "")
this.restURL = process.env.RESTURL
else this.restURL = DEFAULT_REST_API
// Retrieve the apiToken // Retrieve the apiToken
this.apiToken = "" // default value. this.apiToken = '' // default value.
if (config && config.apiToken && config.apiToken !== "") if (config && config.apiToken && config.apiToken !== '') { this.apiToken = config.apiToken } else if (process.env.BCHJSTOKEN && process.env.BCHJSTOKEN !== '') { this.apiToken = process.env.BCHJSTOKEN }
this.apiToken = config.apiToken
else if (process.env.BCHJSTOKEN && process.env.BCHJSTOKEN !== "")
this.apiToken = process.env.BCHJSTOKEN
// Retrieve the Basic Authentication password. // Retrieve the Basic Authentication password.
this.authPass = "" // default value. this.authPass = '' // default value.
if (config && config.authPass && config.authPass !== "") if (config && config.authPass && config.authPass !== '') { this.authPass = config.authPass } else if (process.env.BCHJSAUTHPASS && process.env.BCHJSAUTHPASS !== '') { this.authPass = process.env.BCHJSAUTHPASS }
this.authPass = config.authPass
else if (process.env.BCHJSAUTHPASS && process.env.BCHJSAUTHPASS !== "")
this.authPass = process.env.BCHJSAUTHPASS
// Generate a Basic Authentication token from an auth password // Generate a Basic Authentication token from an auth password
this.authToken = "" this.authToken = ''
if (this.authPass) { if (this.authPass) {
// console.log(`bch-js initialized with authPass: ${this.authPass}`) // console.log(`bch-js initialized with authPass: ${this.authPass}`)
// Generate the header for Basic Authentication. // Generate the header for Basic Authentication.
const combined = `fullstackcash:${this.authPass}` const combined = `fullstackcash:${this.authPass}`
var base64Credential = Buffer.from(combined).toString("base64") const base64Credential = Buffer.from(combined).toString('base64')
this.authToken = `Basic ${base64Credential}` this.authToken = `Basic ${base64Credential}`
} }
+25 -25
View File
@@ -1,13 +1,13 @@
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const sb = require("satoshi-bitcoin") const sb = require('satoshi-bitcoin')
const bitcoinMessage = require("bitcoinjs-message") const bitcoinMessage = require('bitcoinjs-message')
const bs58 = require("bs58") const bs58 = require('bs58')
const bip21 = require("@psf/bip21") const bip21 = require('@psf/bip21')
const coininfo = require("@psf/coininfo") const coininfo = require('@psf/coininfo')
const bip38 = require("bip38") const bip38 = require('bip38')
const wif = require("wif") const wif = require('wif')
const Buffer = require("safe-buffer").Buffer const Buffer = require('safe-buffer').Buffer
class BitcoinCash { class BitcoinCash {
constructor (address) { constructor (address) {
@@ -148,9 +148,9 @@ class BitcoinCash {
*/ */
// sign message // sign message
signMessageWithPrivKey (privateKeyWIF, message) { signMessageWithPrivKey (privateKeyWIF, message) {
const network = privateKeyWIF.charAt(0) === "c" ? "testnet" : "mainnet" const network = privateKeyWIF.charAt(0) === 'c' ? 'testnet' : 'mainnet'
let bitcoincash let bitcoincash
if (network === "mainnet") bitcoincash = coininfo.bitcoincash.main if (network === 'mainnet') bitcoincash = coininfo.bitcoincash.main
else bitcoincash = coininfo.bitcoincash.test else bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
@@ -161,7 +161,7 @@ class BitcoinCash {
const privateKey = keyPair.d.toBuffer(32) const privateKey = keyPair.d.toBuffer(32)
return bitcoinMessage return bitcoinMessage
.sign(message, privateKey, keyPair.compressed) .sign(message, privateKey, keyPair.compressed)
.toString("base64") .toString('base64')
} }
/** /**
@@ -223,7 +223,7 @@ class BitcoinCash {
*/ */
// encode base58Check // encode base58Check
encodeBase58Check (hex) { encodeBase58Check (hex) {
return bs58.encode(Buffer.from(hex, "hex")) return bs58.encode(Buffer.from(hex, 'hex'))
} }
/** /**
@@ -261,7 +261,7 @@ class BitcoinCash {
*/ */
// decode base58Check // decode base58Check
decodeBase58Check (address) { decodeBase58Check (address) {
return bs58.decode(address).toString("hex") return bs58.decode(address).toString('hex')
} }
/** /**
@@ -412,12 +412,12 @@ class BitcoinCash {
// assumes compressed pubkeys in all cases. // assumes compressed pubkeys in all cases.
const types = { const types = {
inputs: { inputs: {
"MULTISIG-P2SH": 49 * 4, 'MULTISIG-P2SH': 49 * 4,
"MULTISIG-P2WSH": 6 + 41 * 4, 'MULTISIG-P2WSH': 6 + 41 * 4,
"MULTISIG-P2SH-P2WSH": 6 + 76 * 4, 'MULTISIG-P2SH-P2WSH': 6 + 76 * 4,
P2PKH: 148 * 4, P2PKH: 148 * 4,
P2WPKH: 108 + 41 * 4, P2WPKH: 108 + 41 * 4,
"P2SH-P2WPKH": 108 + 64 * 4 'P2SH-P2WPKH': 108 + 64 * 4
}, },
outputs: { outputs: {
P2SH: 32 * 4, P2SH: 32 * 4,
@@ -428,22 +428,22 @@ class BitcoinCash {
} }
Object.keys(inputs).forEach(function (key) { Object.keys(inputs).forEach(function (key) {
if (key.slice(0, 8) === "MULTISIG") { if (key.slice(0, 8) === 'MULTISIG') {
// ex. "MULTISIG-P2SH:2-3" would mean 2 of 3 P2SH MULTISIG // ex. "MULTISIG-P2SH:2-3" would mean 2 of 3 P2SH MULTISIG
const keyParts = key.split(":") const keyParts = key.split(':')
if (keyParts.length !== 2) throw new Error(`invalid input: ${key}`) if (keyParts.length !== 2) throw new Error(`invalid input: ${key}`)
const newKey = keyParts[0] const newKey = keyParts[0]
const mAndN = keyParts[1].split("-").map(function(item) { const mAndN = keyParts[1].split('-').map(function (item) {
return parseInt(item) return parseInt(item)
}) })
totalWeight += types.inputs[newKey] * inputs[key] totalWeight += types.inputs[newKey] * inputs[key]
const multiplyer = newKey === "MULTISIG-P2SH" ? 4 : 1 const multiplyer = newKey === 'MULTISIG-P2SH' ? 4 : 1
totalWeight += (73 * mAndN[0] + 34 * mAndN[1]) * multiplyer totalWeight += (73 * mAndN[0] + 34 * mAndN[1]) * multiplyer
} else { } else {
totalWeight += types.inputs[key] * inputs[key] totalWeight += types.inputs[key] * inputs[key]
} }
if (key.indexOf("W") >= 0) hasWitness = true if (key.indexOf('W') >= 0) hasWitness = true
}) })
Object.keys(outputs).forEach(function (key) { Object.keys(outputs).forEach(function (key) {
@@ -509,10 +509,10 @@ class BitcoinCash {
* ) * )
* // cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm * // cSx7KzdH9EcvDEireu2WYpGnXdFYpta7sJUNt5kVCJgA7kcAU8Gm
*/ */
decryptBIP38(encryptedKey, passphrase, network = "mainnet") { decryptBIP38 (encryptedKey, passphrase, network = 'mainnet') {
const decryptedKey = bip38.decrypt(encryptedKey, passphrase) const decryptedKey = bip38.decrypt(encryptedKey, passphrase)
let prefix let prefix
if (network === "testnet") prefix = 0xef if (network === 'testnet') prefix = 0xef
else prefix = 0x80 else prefix = 0x80
return wif.encode(prefix, decryptedKey.privateKey, decryptedKey.compressed) return wif.encode(prefix, decryptedKey.privateKey, decryptedKey.compressed)
+22 -20
View File
@@ -3,7 +3,7 @@
- Add blockhash functionality back into getTxOutProof - Add blockhash functionality back into getTxOutProof
*/ */
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -211,7 +211,7 @@ class Blockchain {
* // [ '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ] * // [ '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f' ]
*/ */
async getBlockHash (height = 1) { async getBlockHash (height = 1) {
if (typeof height !== "string") height = JSON.stringify(height) if (typeof height !== 'string') height = JSON.stringify(height)
try { try {
const response = await axios.get( const response = await axios.get(
@@ -260,7 +260,7 @@ class Blockchain {
async getBlockHeader (hash, verbose = true) { async getBlockHeader (hash, verbose = true) {
try { try {
// Handle single hash. // Handle single hash.
if (typeof hash === "string") { if (typeof hash === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}blockchain/getBlockHeader/${hash}?verbose=${verbose}`, `${this.restURL}blockchain/getBlockHeader/${hash}?verbose=${verbose}`,
_this.axiosOptions _this.axiosOptions
@@ -283,7 +283,7 @@ class Blockchain {
return response.data return response.data
} }
throw new Error(`Input hash must be a string or array of strings.`) throw new Error('Input hash must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -367,7 +367,7 @@ class Blockchain {
// getMempoolAncestors // getMempoolAncestors
async getMempoolAncestors (txid, verbose = false) { async getMempoolAncestors (txid, verbose = false) {
if (typeof txid !== "string") txid = JSON.stringify(txid) if (typeof txid !== 'string') txid = JSON.stringify(txid)
try { try {
const response = await axios.get( const response = await axios.get(
@@ -382,7 +382,7 @@ class Blockchain {
} }
async getMempoolDescendants (txid, verbose = false) { async getMempoolDescendants (txid, verbose = false) {
if (typeof txid !== "string") txid = JSON.stringify(txid) if (typeof txid !== 'string') txid = JSON.stringify(txid)
try { try {
const response = await axios.get( const response = await axios.get(
@@ -481,7 +481,7 @@ class Blockchain {
// if (typeof txid !== "string") txid = JSON.stringify(txid) // if (typeof txid !== "string") txid = JSON.stringify(txid)
try { try {
if (typeof txid === "string") { if (typeof txid === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}blockchain/getMempoolEntry/${txid}`, `${this.restURL}blockchain/getMempoolEntry/${txid}`,
_this.axiosOptions _this.axiosOptions
@@ -501,7 +501,7 @@ class Blockchain {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -610,20 +610,22 @@ class Blockchain {
* *
* // null * // null
*/ */
async getTxOut(txid, n, include_mempool = true) { async getTxOut (txid, n, includeMempool = true) {
try { try {
// Input validation // Input validation
if (typeof txid !== "string" || txid.length !== 64) if (typeof txid !== 'string' || txid.length !== 64) {
throw new Error(`txid needs to be a proper transaction ID`) throw new Error('txid needs to be a proper transaction ID')
}
if (isNaN(n)) throw new Error(`n must be an integer`) if (isNaN(n)) throw new Error('n must be an integer')
if (typeof include_mempool !== "boolean") if (typeof includeMempool !== 'boolean') {
throw new Error(`include_mempool input must be of type boolean`) throw new Error('includeMempool input must be of type boolean')
}
// Send the request to the REST API. // Send the request to the REST API.
// const response = await axios.get( // const response = await axios.get(
// `${this.restURL}blockchain/getTxOut/${txid}/${n}?include_mempool=${include_mempool}`, // `${this.restURL}blockchain/getTxOut/${txid}/${n}?includeMempool=${includeMempool}`,
// _this.axiosOptions // _this.axiosOptions
// ) // )
const response = await axios.post( const response = await axios.post(
@@ -631,7 +633,7 @@ class Blockchain {
{ {
txid: txid, txid: txid,
vout: n, vout: n,
mempool: include_mempool mempool: includeMempool
}, },
_this.axiosOptions _this.axiosOptions
) )
@@ -682,7 +684,7 @@ class Blockchain {
async getTxOutProof (txids) { async getTxOutProof (txids) {
try { try {
// Single txid. // Single txid.
if (typeof txids === "string") { if (typeof txids === 'string') {
const path = `${this.restURL}blockchain/getTxOutProof/${txids}` const path = `${this.restURL}blockchain/getTxOutProof/${txids}`
// if (blockhash) path = `${path}?blockhash=${blockhash}` // if (blockhash) path = `${path}?blockhash=${blockhash}`
@@ -703,7 +705,7 @@ class Blockchain {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -789,7 +791,7 @@ class Blockchain {
async verifyTxOutProof (proof) { async verifyTxOutProof (proof) {
try { try {
// Single block // Single block
if (typeof proof === "string") { if (typeof proof === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}blockchain/verifyTxOutProof/${proof}`, `${this.restURL}blockchain/verifyTxOutProof/${proof}`,
_this.axiosOptions _this.axiosOptions
@@ -810,7 +812,7 @@ class Blockchain {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+1 -1
View File
@@ -2,7 +2,7 @@
API endpoints for basic control and information of the full node. API endpoints for basic control and information of the full node.
*/ */
const axios = require("axios") const axios = require('axios')
let _this // Global reference to the instance of this class. let _this // Global reference to the instance of this class.
+2 -2
View File
@@ -1,5 +1,5 @@
const randomBytes = require("randombytes") const randomBytes = require('randombytes')
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
class Crypto { class Crypto {
/** /**
+10 -6
View File
@@ -1,10 +1,11 @@
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require("@psf/coininfo") const coininfo = require('@psf/coininfo')
class ECPair { class ECPair {
static setAddress (address) { static setAddress (address) {
ECPair._address = address ECPair._address = address
} }
/** /**
* @api Ecpair.fromWIF() fromWIF() * @api Ecpair.fromWIF() fromWIF()
* @apiName fromWIF * @apiName fromWIF
@@ -22,18 +23,17 @@ class ECPair {
* */ * */
static fromWIF (privateKeyWIF) { static fromWIF (privateKeyWIF) {
let network let network
if (privateKeyWIF[0] === "L" || privateKeyWIF[0] === "K") if (privateKeyWIF[0] === 'L' || privateKeyWIF[0] === 'K') { network = 'mainnet' } else if (privateKeyWIF[0] === 'c') network = 'testnet'
network = "mainnet"
else if (privateKeyWIF[0] === "c") network = "testnet"
let bitcoincash let bitcoincash
if (network === "mainnet") bitcoincash = coininfo.bitcoincash.main if (network === 'mainnet') bitcoincash = coininfo.bitcoincash.main
else bitcoincash = coininfo.bitcoincash.test else bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
return Bitcoin.ECPair.fromWIF(privateKeyWIF, bitcoincashBitcoinJSLib) return Bitcoin.ECPair.fromWIF(privateKeyWIF, bitcoincashBitcoinJSLib)
} }
/** /**
* @api Ecpair.toWIF() toWIF() * @api Ecpair.toWIF() toWIF()
* @apiName toWIF * @apiName toWIF
@@ -68,6 +68,7 @@ class ECPair {
static verify (ecpair, buffer, signature) { static verify (ecpair, buffer, signature) {
return ecpair.verify(buffer, signature) return ecpair.verify(buffer, signature)
} }
/** /**
* @api Ecpair.fromPublicKey() fromPublicKey() * @api Ecpair.fromPublicKey() fromPublicKey()
* @apiName fromPublicKey * @apiName fromPublicKey
@@ -86,6 +87,7 @@ class ECPair {
static fromPublicKey (pubkeyBuffer) { static fromPublicKey (pubkeyBuffer) {
return Bitcoin.ECPair.fromPublicKeyBuffer(pubkeyBuffer) return Bitcoin.ECPair.fromPublicKeyBuffer(pubkeyBuffer)
} }
/** /**
* @api Ecpair.toPublicKey() toPublicKey() * @api Ecpair.toPublicKey() toPublicKey()
* @apiName toPublicKey * @apiName toPublicKey
@@ -108,6 +110,7 @@ class ECPair {
static toPublicKey (ecpair) { static toPublicKey (ecpair) {
return ecpair.getPublicKeyBuffer() return ecpair.getPublicKeyBuffer()
} }
/** /**
* @api Ecpair.toLegacyAddress() toLegacyAddress() * @api Ecpair.toLegacyAddress() toLegacyAddress()
* @apiName toLegacyAddress * @apiName toLegacyAddress
@@ -134,6 +137,7 @@ class ECPair {
static toLegacyAddress (ecpair) { static toLegacyAddress (ecpair) {
return ecpair.getAddress() return ecpair.getAddress()
} }
/** /**
* @api Ecpair.toCashAddress() toCashAddress() * @api Ecpair.toCashAddress() toCashAddress()
* @apiName toCashAddress * @apiName toCashAddress
+14 -16
View File
@@ -3,7 +3,7 @@
by FullStack.cash by FullStack.cash
*/ */
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -100,7 +100,7 @@ class ElectrumX {
async utxo (address) { async utxo (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}electrumx/utxos/${address}`, `${this.restURL}electrumx/utxos/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -120,7 +120,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -184,7 +184,7 @@ class ElectrumX {
async balance (address) { async balance (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}electrumx/balance/${address}`, `${this.restURL}electrumx/balance/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -204,7 +204,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -282,7 +282,7 @@ class ElectrumX {
async transactions (address) { async transactions (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}electrumx/transactions/${address}`, `${this.restURL}electrumx/transactions/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -302,7 +302,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -374,7 +374,7 @@ class ElectrumX {
async unconfirmed (address) { async unconfirmed (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}electrumx/unconfirmed/${address}`, `${this.restURL}electrumx/unconfirmed/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -394,7 +394,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -452,9 +452,7 @@ class ElectrumX {
} catch (error) { } catch (error) {
// console.log("error: ", error) // console.log("error: ", error)
if (error.response && error.response.data) { if (error.response && error.response.data) {
if (error.response && error.response.data) if (error.response && error.response.data) { throw new Error(error.response.data.error) } else throw error.response.data
throw new Error(error.response.data.error)
else throw error.response.data
} else { } else {
throw error throw error
} }
@@ -534,7 +532,7 @@ class ElectrumX {
async txData (txid) { async txData (txid) {
try { try {
// Handle single transaction. // Handle single transaction.
if (typeof txid === "string") { if (typeof txid === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}electrumx/tx/data/${txid}`, `${this.restURL}electrumx/tx/data/${txid}`,
_this.axiosOptions _this.axiosOptions
@@ -552,7 +550,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input txId must be a string or array of strings.`) throw new Error('Input txId must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -582,7 +580,7 @@ class ElectrumX {
*/ */
async broadcast (txHex) { async broadcast (txHex) {
try { try {
if (typeof txHex === "string") { if (typeof txHex === 'string') {
const response = await axios.post( const response = await axios.post(
`${this.restURL}electrumx/tx/broadcast`, `${this.restURL}electrumx/tx/broadcast`,
{ txHex }, { txHex },
@@ -592,7 +590,7 @@ class ElectrumX {
return response.data return response.data
} }
throw new Error(`Input txHex must be a string.`) throw new Error('Input txHex must be a string.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+2 -3
View File
@@ -2,7 +2,7 @@
This library contains useful functions that deal with encryption. This library contains useful functions that deal with encryption.
*/ */
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -35,8 +35,7 @@ class Encryption {
// Search the blockchain for a public key associated with a BCH address. // Search the blockchain for a public key associated with a BCH address.
async getPubKey (addr) { async getPubKey (addr) {
try { try {
if (!addr || typeof addr !== "string") if (!addr || typeof addr !== 'string') { throw new Error('Input must be a valid Bitcoin Cash address.') }
throw new Error(`Input must be a valid Bitcoin Cash address.`)
const response = await _this.axios.get( const response = await _this.axios.get(
`${this.restURL}encryption/publickey/${addr}`, `${this.restURL}encryption/publickey/${addr}`,
+1 -1
View File
@@ -1,4 +1,4 @@
const axios = require("axios") const axios = require('axios')
let _this let _this
+10 -12
View File
@@ -1,7 +1,7 @@
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require("@psf/coininfo") const coininfo = require('@psf/coininfo')
const bip32utils = require("@psf/bip32-utils") const bip32utils = require('@psf/bip32-utils')
const bchaddrjs = require("bchaddrjs-slp") const bchaddrjs = require('bchaddrjs-slp')
class HDNode { class HDNode {
constructor (address) { constructor (address) {
@@ -32,11 +32,9 @@ class HDNode {
* // create HDNode from seed buffer * // create HDNode from seed buffer
* bchjs.HDNode.fromSeed(seedBuffer); * bchjs.HDNode.fromSeed(seedBuffer);
*/ */
fromSeed(rootSeedBuffer, network = "mainnet") { fromSeed (rootSeedBuffer, network = 'mainnet') {
let bitcoincash let bitcoincash
if (network === "bitcoincash" || network === "mainnet") if (network === 'bitcoincash' || network === 'mainnet') { bitcoincash = coininfo.bitcoincash.main } else bitcoincash = coininfo.bitcoincash.test
bitcoincash = coininfo.bitcoincash.main
else bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
return Bitcoin.HDNode.fromSeedBuffer( return Bitcoin.HDNode.fromSeedBuffer(
@@ -331,8 +329,8 @@ class HDNode {
*/ */
fromXPriv (xpriv) { fromXPriv (xpriv) {
let bitcoincash let bitcoincash
if (xpriv[0] === "x") bitcoincash = coininfo.bitcoincash.main if (xpriv[0] === 'x') bitcoincash = coininfo.bitcoincash.main
else if (xpriv[0] === "t") bitcoincash = coininfo.bitcoincash.test else if (xpriv[0] === 't') bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
return Bitcoin.HDNode.fromBase58(xpriv, bitcoincashBitcoinJSLib) return Bitcoin.HDNode.fromBase58(xpriv, bitcoincashBitcoinJSLib)
@@ -354,8 +352,8 @@ class HDNode {
*/ */
fromXPub (xpub) { fromXPub (xpub) {
let bitcoincash let bitcoincash
if (xpub[0] === "x") bitcoincash = coininfo.bitcoincash.main if (xpub[0] === 'x') bitcoincash = coininfo.bitcoincash.main
else if (xpub[0] === "t") bitcoincash = coininfo.bitcoincash.test else if (xpub[0] === 't') bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
return Bitcoin.HDNode.fromBase58(xpub, bitcoincashBitcoinJSLib) return Bitcoin.HDNode.fromBase58(xpub, bitcoincashBitcoinJSLib)
+49 -39
View File
@@ -3,10 +3,10 @@
and downloading data from the IPFS network. and downloading data from the IPFS network.
*/ */
const axios = require("axios") const axios = require('axios')
const Uppy = require("@uppy/core") const Uppy = require('@uppy/core')
const Tus = require("@uppy/tus") const Tus = require('@uppy/tus')
const fs = require("fs") const fs = require('fs')
let _this let _this
@@ -14,8 +14,8 @@ class IPFS {
constructor (config) { constructor (config) {
this.IPFS_API = process.env.IPFS_API this.IPFS_API = process.env.IPFS_API
? process.env.IPFS_API ? process.env.IPFS_API
: // : `http://localhost:5001` : 'https://ipfs-api.fullstack.cash'
`https://ipfs-api.fullstack.cash` // : `http://localhost:5001`
// Default options when calling axios. // Default options when calling axios.
this.axiosOptions = { this.axiosOptions = {
@@ -38,7 +38,7 @@ class IPFS {
initUppy () { initUppy () {
const uppy = Uppy({ const uppy = Uppy({
allowMultipleUploads: false, allowMultipleUploads: false,
meta: { test: "avatar" }, meta: { test: 'avatar' },
debug: false, debug: false,
restrictions: { restrictions: {
maxFileSize: null, maxFileSize: null,
@@ -93,8 +93,9 @@ class IPFS {
async createFileModelServer (path) { async createFileModelServer (path) {
try { try {
// Ensure the file exists. // Ensure the file exists.
if (!_this.fs.existsSync(path)) if (!_this.fs.existsSync(path)) {
throw new Error(`Could not find this file: ${path}`) throw new Error(`Could not find this file: ${path}`)
}
// Read in the file. // Read in the file.
const fileBuf = _this.fs.readFileSync(path) const fileBuf = _this.fs.readFileSync(path)
@@ -103,11 +104,11 @@ class IPFS {
// console.log(`Buffer length: ${fileBuf.length}`) // console.log(`Buffer length: ${fileBuf.length}`)
// Get the file name from the path. // Get the file name from the path.
const splitPath = path.split("/") const splitPath = path.split('/')
const fileName = splitPath[splitPath.length - 1] const fileName = splitPath[splitPath.length - 1]
// Get the file extension. // Get the file extension.
const splitExt = fileName.split(".") const splitExt = fileName.split('.')
const fileExt = splitExt[splitExt.length - 1] const fileExt = splitExt[splitExt.length - 1]
const fileObj = { const fileObj = {
@@ -125,7 +126,7 @@ class IPFS {
return fileData.data return fileData.data
} catch (err) { } catch (err) {
console.error(`Error in createFileModel()`) console.error('Error in createFileModel()')
throw err throw err
} }
} }
@@ -160,12 +161,13 @@ class IPFS {
async uploadFileServer (path, modelId) { async uploadFileServer (path, modelId) {
try { try {
// Ensure the file exists. // Ensure the file exists.
if (!_this.fs.existsSync(path)) if (!_this.fs.existsSync(path)) {
throw new Error(`Could not find this file: ${path}`) throw new Error(`Could not find this file: ${path}`)
}
if (!modelId) { if (!modelId) {
throw new Error( throw new Error(
`Must include a file model ID in order to upload a file.` 'Must include a file model ID in order to upload a file.'
) )
} }
@@ -173,14 +175,14 @@ class IPFS {
const fileBuf = _this.fs.readFileSync(path) const fileBuf = _this.fs.readFileSync(path)
// Get the file name from the path. // Get the file name from the path.
const splitPath = path.split("/") const splitPath = path.split('/')
const fileName = splitPath[splitPath.length - 1] const fileName = splitPath[splitPath.length - 1]
// Prepare the upload object. Get a file ID from Uppy. // Prepare the upload object. Get a file ID from Uppy.
const id = _this.uppy.addFile({ const id = _this.uppy.addFile({
name: fileName, name: fileName,
data: fileBuf, data: fileBuf,
source: "Local", source: 'Local',
isRemote: false isRemote: false
}) })
// console.log(`id: ${JSON.stringify(id, null, 2)}`) // console.log(`id: ${JSON.stringify(id, null, 2)}`)
@@ -191,8 +193,9 @@ class IPFS {
// Upload the file to the server. // Upload the file to the server.
const upData = await _this.uppy.upload() const upData = await _this.uppy.upload()
if (upData.failed.length) if (upData.failed.length) {
throw new Error("The file could not be uploaded") throw new Error('The file could not be uploaded')
}
if (upData.successful.length) { if (upData.successful.length) {
delete upData.successful[0].data delete upData.successful[0].data
@@ -213,7 +216,7 @@ class IPFS {
return false return false
} catch (err) { } catch (err) {
console.error(`Error in bch-js/src/ipfs.js/upload(): `) console.error('Error in bch-js/src/ipfs.js/upload(): ')
throw err throw err
} }
} }
@@ -248,7 +251,7 @@ class IPFS {
*/ */
async getStatus (modelId) { async getStatus (modelId) {
try { try {
if (!modelId) throw new Error(`Must include a file model ID.`) if (!modelId) throw new Error('Must include a file model ID.')
const fileData = await _this.axios.get( const fileData = await _this.axios.get(
`${this.IPFS_API}/files/${modelId}` `${this.IPFS_API}/files/${modelId}`
@@ -266,10 +269,11 @@ class IPFS {
return fileObj return fileObj
} catch (err) { } catch (err) {
console.error(`Error in getStatus()`) console.error('Error in getStatus()')
throw err throw err
} }
} }
/** /**
* @api IPFS.createFileModelWeb() createFileModelWeb() * @api IPFS.createFileModelWeb() createFileModelWeb()
* @apiName createFileModelWeb() * @apiName createFileModelWeb()
@@ -313,18 +317,20 @@ class IPFS {
*/ */
async createFileModelWeb (file) { async createFileModelWeb (file) {
try { try {
if (!file) throw new Error(`File is required`) if (!file) throw new Error('File is required')
const { name, size } = file const { name, size } = file
if (!name || typeof name !== "string") if (!name || typeof name !== 'string') {
throw new Error(`File should have the property 'name' of string type`) throw new Error("File should have the property 'name' of string type")
}
if (!size || typeof size !== "number") if (!size || typeof size !== 'number') {
throw new Error(`File should have the property 'size' of number type`) throw new Error("File should have the property 'size' of number type")
}
// Get the file extension. // Get the file extension.
const splitExt = name.split(".") const splitExt = name.split('.')
const fileExt = splitExt[splitExt.length - 1] const fileExt = splitExt[splitExt.length - 1]
const fileObj = { const fileObj = {
@@ -342,7 +348,7 @@ class IPFS {
return fileData.data return fileData.data
} catch (err) { } catch (err) {
console.error(`Error in createFileModelWeb()`) console.error('Error in createFileModelWeb()')
throw err throw err
} }
} }
@@ -379,22 +385,25 @@ class IPFS {
*/ */
async uploadFileWeb (file, modelId) { async uploadFileWeb (file, modelId) {
try { try {
if (!file) throw new Error(`File is required`) if (!file) throw new Error('File is required')
const { name, type, size } = file const { name, type, size } = file
if (!name || typeof name !== "string") if (!name || typeof name !== 'string') {
throw new Error(`File should have the property 'name' of string type`) throw new Error("File should have the property 'name' of string type")
}
if (!type || typeof type !== "string") if (!type || typeof type !== 'string') {
throw new Error(`File should have the property 'type' of string type`) throw new Error("File should have the property 'type' of string type")
}
if (!size || typeof size !== "number") if (!size || typeof size !== 'number') {
throw new Error(`File should have the property 'size' of number type`) throw new Error("File should have the property 'size' of number type")
}
if (!modelId) { if (!modelId) {
throw new Error( throw new Error(
`Must include a file model ID in order to upload a file.` 'Must include a file model ID in order to upload a file.'
) )
} }
@@ -402,7 +411,7 @@ class IPFS {
const id = _this.uppy.addFile({ const id = _this.uppy.addFile({
name: name, name: name,
data: file, data: file,
source: "Local", source: 'Local',
isRemote: false isRemote: false
}) })
// console.log(`id: ${JSON.stringify(id, null, 2)}`) // console.log(`id: ${JSON.stringify(id, null, 2)}`)
@@ -413,8 +422,9 @@ class IPFS {
// Upload the file to the server. // Upload the file to the server.
const upData = await _this.uppy.upload() const upData = await _this.uppy.upload()
if (upData.failed.length) if (upData.failed.length) {
throw new Error("The file could not be uploaded") throw new Error('The file could not be uploaded')
}
if (upData.successful.length) { if (upData.successful.length) {
delete upData.successful[0].data delete upData.successful[0].data
@@ -435,7 +445,7 @@ class IPFS {
return false return false
} catch (err) { } catch (err) {
console.error(`Error in bch-js/src/ipfs.js/uploadFileWeb(): `) console.error('Error in bch-js/src/ipfs.js/uploadFileWeb(): ')
throw err throw err
} }
} }
+3 -3
View File
@@ -1,4 +1,4 @@
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -27,10 +27,10 @@ class Mining {
_this = this _this = this
} }
async getBlockTemplate(template_request) { async getBlockTemplate (templateRequest) {
try { try {
const response = await axios.get( const response = await axios.get(
`${this.restURL}mining/getBlockTemplate/${template_request}`, `${this.restURL}mining/getBlockTemplate/${templateRequest}`,
_this.axiosOptions _this.axiosOptions
) )
return response.data return response.data
+20 -20
View File
@@ -1,8 +1,11 @@
const BIP39 = require("bip39") /* eslint no-prototype-builtins: "off" */
const randomBytes = require("randombytes") /* eslint node/no-callback-literal: "off" */
const Bitcoin = require("@psf/bitcoincashjs-lib")
const Buffer = require("safe-buffer").Buffer const BIP39 = require('bip39')
const wif = require("wif") const randomBytes = require('randombytes')
const Bitcoin = require('@psf/bitcoincashjs-lib')
const Buffer = require('safe-buffer').Buffer
const wif = require('wif')
class Mnemonic { class Mnemonic {
constructor (address) { constructor (address) {
@@ -95,9 +98,6 @@ class Mnemonic {
* // generate 16 bytes of entropy * // generate 16 bytes of entropy
* let entropy = bchjs.Crypto.randomBytes(16); * let entropy = bchjs.Crypto.randomBytes(16);
* // * //
* // turn entropy to 12 japanese word mnemonic
* bchjs.Mnemonic.fromEntropy(entropy.toString('hex'), bchjs.Mnemonic.wordLists().japanese)
* // ぱそこん にあう にんめい きどく ちそう せんきょ かいが きおく いれる いねむり しいく きかんしゃ
*/ */
fromEntropy (bytes, wordlist) { fromEntropy (bytes, wordlist) {
return BIP39.entropyToMnemonic(bytes, wordlist) return BIP39.entropyToMnemonic(bytes, wordlist)
@@ -137,7 +137,7 @@ class Mnemonic {
* // <Buffer f3 79 da 02 cc 42 6e 6e 26 43 0d 25 e6 cc 37 2d fd 0a 1a 2e 4a 33 ac 4d c6 ae 6d 56 01 7f 64 2d> * // <Buffer f3 79 da 02 cc 42 6e 6e 26 43 0d 25 e6 cc 37 2d fd 0a 1a 2e 4a 33 ac 4d c6 ae 6d 56 01 7f 64 2d>
*/ */
toEntropy (mnemonic, wordlist) { toEntropy (mnemonic, wordlist) {
return Buffer.from(BIP39.mnemonicToEntropy(mnemonic, wordlist), "hex") return Buffer.from(BIP39.mnemonicToEntropy(mnemonic, wordlist), 'hex')
} }
/** /**
@@ -159,9 +159,9 @@ class Mnemonic {
*/ */
validate (mnemonic, wordlist) { validate (mnemonic, wordlist) {
// Preprocess the words // Preprocess the words
const words = mnemonic.split(" ") const words = mnemonic.split(' ')
// Detect blank phrase // Detect blank phrase
if (words.length === 0) return "Blank mnemonic" if (words.length === 0) return 'Blank mnemonic'
// Check each word // Check each word
for (let i = 0; i < words.length; i++) { for (let i = 0; i < words.length; i++) {
@@ -175,9 +175,9 @@ class Mnemonic {
// Check the words are valid // Check the words are valid
// const properPhrase = words.join() // const properPhrase = words.join()
const isValid = BIP39.validateMnemonic(mnemonic, wordlist) const isValid = BIP39.validateMnemonic(mnemonic, wordlist)
if (!isValid) return "Invalid mnemonic" if (!isValid) return 'Invalid mnemonic'
return "Valid mnemonic" return 'Valid mnemonic'
} }
/** /**
@@ -203,7 +203,7 @@ class Mnemonic {
* await bchjs.Mnemonic.toSeed('frost deliver coin clutch upon round scene wonder various wise luggage country', 'yayayayay'); * await bchjs.Mnemonic.toSeed('frost deliver coin clutch upon round scene wonder various wise luggage country', 'yayayayay');
* // <Buffer 1d 00 9f a3 a8 86 51 a4 04 d5 03 3d eb 6d b1 01 e2 f1 3b c3 c8 6d 1f b9 93 b4 d1 33 dc 84 21 12 2c 9b 52 10 ba d8 96 15 e0 b0 9a 34 33 52 f8 07 c8 c4 ... > * // <Buffer 1d 00 9f a3 a8 86 51 a4 04 d5 03 3d eb 6d b1 01 e2 f1 3b c3 c8 6d 1f b9 93 b4 d1 33 dc 84 21 12 2c 9b 52 10 ba d8 96 15 e0 b0 9a 34 33 52 f8 07 c8 c4 ... >
*/ */
toSeed(mnemonic, password = "") { toSeed (mnemonic, password = '') {
return BIP39.mnemonicToSeed(mnemonic, password) return BIP39.mnemonicToSeed(mnemonic, password)
} }
@@ -261,9 +261,9 @@ class Mnemonic {
* // address: 'bitcoincash:qphwlpu2wzjxrjts94pn4wh778fwsu2afg2aj5her9' } ] * // address: 'bitcoincash:qphwlpu2wzjxrjts94pn4wh778fwsu2afg2aj5her9' } ]
*/ */
async toKeypairs (mnemonic, numberOfKeypairs = 1, regtest = false) { async toKeypairs (mnemonic, numberOfKeypairs = 1, regtest = false) {
const rootSeedBuffer = await this.toSeed(mnemonic, "") const rootSeedBuffer = await this.toSeed(mnemonic, '')
const hdNode = Bitcoin.HDNode.fromSeedBuffer(rootSeedBuffer) const hdNode = Bitcoin.HDNode.fromSeedBuffer(rootSeedBuffer)
const HDPath = `44'/145'/0'/0/` const HDPath = "44'/145'/0'/0/"
const accounts = [] const accounts = []
@@ -366,7 +366,7 @@ const _extend = function(dst) {
* @param {Function} func * @param {Function} func
*/ */
const _defer = function (func) { const _defer = function (func) {
if (typeof setImmediate === "function") return setImmediate(func) if (typeof setImmediate === 'function') return setImmediate(func)
return setTimeout(func, 0) return setTimeout(func, 0)
} }
@@ -374,7 +374,7 @@ const _defer = function(func) {
/** /**
* Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance. * Based on the algorithm at http://en.wikipedia.org/wiki/Levenshtein_distance.
*/ */
var Levenshtein = { const Levenshtein = {
/** /**
* Calculate levenshtein distance of the two strings. * Calculate levenshtein distance of the two strings.
* *
@@ -457,7 +457,7 @@ var Levenshtein = {
i = 0 i = 0
j = -1 j = -1
var __calculate = function() { const __calculate = function () {
// reset timer // reset timer
startTime = new Date().valueOf() startTime = new Date().valueOf()
currentTime = startTime currentTime = startTime
@@ -499,7 +499,7 @@ var Levenshtein = {
} }
// send a progress update? // send a progress update?
if (null !== options.progress) { if (options.progress !== null) {
try { try {
options.progress.call(null, (i * 100.0) / str1.length) options.progress.call(null, (i * 100.0) / str1.length)
} catch (err) { } catch (err) {
+10 -10
View File
@@ -3,7 +3,7 @@
Bitcoin.com Bitcoin.com
*/ */
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -16,7 +16,7 @@ class Ninsight {
if (config) { if (config) {
this.ninsightURL = config.ninsightURL this.ninsightURL = config.ninsightURL
? config.ninsightURL ? config.ninsightURL
: `https://rest.bitcoin.com/v2` : 'https://rest.bitcoin.com/v2'
} }
// Add JWT token to the authorization header. // Add JWT token to the authorization header.
@@ -69,7 +69,7 @@ class Ninsight {
async utxo (address) { async utxo (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.post( const response = await axios.post(
`${this.ninsightURL}/address/utxo`, `${this.ninsightURL}/address/utxo`,
{ {
@@ -92,7 +92,7 @@ class Ninsight {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -137,7 +137,7 @@ class Ninsight {
*/ */
async unconfirmed (address) { async unconfirmed (address) {
try { try {
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.post( const response = await axios.post(
`${this.ninsightURL}/address/unconfirmed`, `${this.ninsightURL}/address/unconfirmed`,
{ {
@@ -159,7 +159,7 @@ class Ninsight {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -213,7 +213,7 @@ class Ninsight {
*/ */
async transactions (address) { async transactions (address) {
try { try {
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.post( const response = await axios.post(
`${this.ninsightURL}/address/transactions`, `${this.ninsightURL}/address/transactions`,
{ {
@@ -235,7 +235,7 @@ class Ninsight {
return response.data return response.data
} }
throw new Error(`Input address must be a string or array of strings.`) throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -286,7 +286,7 @@ class Ninsight {
*/ */
async txDetails (txid) { async txDetails (txid) {
try { try {
if (typeof txid === "string") { if (typeof txid === 'string') {
const response = await axios.post( const response = await axios.post(
`${this.ninsightURL}/transaction/details`, `${this.ninsightURL}/transaction/details`,
{ {
@@ -308,7 +308,7 @@ class Ninsight {
return response.data return response.data
} }
throw new Error(`Transaction ID must be a string or array of strings.`) throw new Error('Transaction ID must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+10 -10
View File
@@ -3,7 +3,7 @@
provides for their application. provides for their application.
*/ */
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -58,9 +58,9 @@ class OpenBazaar {
async balance (address) { async balance (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
let response let response
if (process.env.NETWORK === "testnet") { if (process.env.NETWORK === 'testnet') {
response = await axios.get( response = await axios.get(
`https://tbch.blockbook.api.openbazaar.org/api/address/${address}`, `https://tbch.blockbook.api.openbazaar.org/api/address/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -75,7 +75,7 @@ class OpenBazaar {
return response.data return response.data
} }
throw new Error(`Input address must be a string.`) throw new Error('Input address must be a string.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -112,9 +112,9 @@ class OpenBazaar {
async utxo (address) { async utxo (address) {
try { try {
// Handle single address. // Handle single address.
if (typeof address === "string") { if (typeof address === 'string') {
let response let response
if (process.env.NETWORK === "testnet") { if (process.env.NETWORK === 'testnet') {
response = await axios.get( response = await axios.get(
`https://tbch.blockbook.api.openbazaar.org/api/utxo/${address}`, `https://tbch.blockbook.api.openbazaar.org/api/utxo/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -127,7 +127,7 @@ class OpenBazaar {
} }
return response.data return response.data
} }
throw new Error(`Input address must be a string.`) throw new Error('Input address must be a string.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -202,9 +202,9 @@ class OpenBazaar {
async tx (txid) { async tx (txid) {
try { try {
// Handle single txid. // Handle single txid.
if (typeof txid === "string") { if (typeof txid === 'string') {
let response let response
if (process.env.NETWORK === "testnet") { if (process.env.NETWORK === 'testnet') {
response = await axios.get( response = await axios.get(
`https://tbch.blockbook.api.openbazaar.org/api/tx/${txid}`, `https://tbch.blockbook.api.openbazaar.org/api/tx/${txid}`,
_this.axiosOptions _this.axiosOptions
@@ -218,7 +218,7 @@ class OpenBazaar {
return response.data return response.data
} }
throw new Error(`Input txid must be a string.`) throw new Error('Input txid must be a string.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+2 -2
View File
@@ -1,4 +1,4 @@
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -30,7 +30,7 @@ class Price {
} }
// This endpoint is deprecated. Documentation removed. // This endpoint is deprecated. Documentation removed.
async current(currency = "usd") { async current (currency = 'usd') {
try { try {
const response = await this.axios.get( const response = await this.axios.get(
`https://index-api.bitcoin.com/api/v0/cash/price/${currency.toLowerCase()}` `https://index-api.bitcoin.com/api/v0/cash/price/${currency.toLowerCase()}`
+14 -14
View File
@@ -1,4 +1,4 @@
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -95,7 +95,7 @@ class RawTransactions {
async decodeRawTransaction (hex) { async decodeRawTransaction (hex) {
try { try {
// Single hex // Single hex
if (typeof hex === "string") { if (typeof hex === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}rawtransactions/decodeRawTransaction/${hex}`, `${this.restURL}rawtransactions/decodeRawTransaction/${hex}`,
_this.axiosOptions _this.axiosOptions
@@ -106,7 +106,7 @@ class RawTransactions {
// Array of hexes // Array of hexes
} else if (Array.isArray(hex)) { } else if (Array.isArray(hex)) {
const options = { const options = {
method: "POST", method: 'POST',
url: `${this.restURL}rawtransactions/decodeRawTransaction`, url: `${this.restURL}rawtransactions/decodeRawTransaction`,
data: { data: {
hexes: hex hexes: hex
@@ -120,7 +120,7 @@ class RawTransactions {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -164,7 +164,7 @@ class RawTransactions {
// if (typeof script !== "string") script = JSON.stringify(script) // if (typeof script !== "string") script = JSON.stringify(script)
try { try {
if (typeof script === "string") { if (typeof script === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}rawtransactions/decodeScript/${script}`, `${this.restURL}rawtransactions/decodeScript/${script}`,
_this.axiosOptions _this.axiosOptions
@@ -173,7 +173,7 @@ class RawTransactions {
return response.data return response.data
} else if (Array.isArray(script)) { } else if (Array.isArray(script)) {
const options = { const options = {
method: "POST", method: 'POST',
url: `${this.restURL}rawtransactions/decodeScript`, url: `${this.restURL}rawtransactions/decodeScript`,
data: { data: {
hexes: script hexes: script
@@ -187,7 +187,7 @@ class RawTransactions {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -260,7 +260,7 @@ class RawTransactions {
*/ */
async getRawTransaction (txid, verbose = false) { async getRawTransaction (txid, verbose = false) {
try { try {
if (typeof txid === "string") { if (typeof txid === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=${verbose}`, `${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=${verbose}`,
_this.axiosOptions _this.axiosOptions
@@ -269,7 +269,7 @@ class RawTransactions {
return response.data return response.data
} else if (Array.isArray(txid)) { } else if (Array.isArray(txid)) {
const options = { const options = {
method: "POST", method: 'POST',
url: `${this.restURL}rawtransactions/getRawTransaction`, url: `${this.restURL}rawtransactions/getRawTransaction`,
data: { data: {
txids: txid, txids: txid,
@@ -282,7 +282,7 @@ class RawTransactions {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
@@ -324,13 +324,13 @@ class RawTransactions {
async sendRawTransaction (hex, allowhighfees = false) { async sendRawTransaction (hex, allowhighfees = false) {
try { try {
// Single tx hex. // Single tx hex.
if (typeof hex === "string") { if (typeof hex === 'string') {
const response = await this.axios.get( const response = await this.axios.get(
`${this.restURL}rawtransactions/sendRawTransaction/${hex}`, `${this.restURL}rawtransactions/sendRawTransaction/${hex}`,
_this.axiosOptions _this.axiosOptions
) )
if (response.data === "66: insufficient priority") { if (response.data === '66: insufficient priority') {
console.warn( console.warn(
`WARN: Insufficient Priority! This is likely due to a fee that is too low, or insufficient funds. `WARN: Insufficient Priority! This is likely due to a fee that is too low, or insufficient funds.
Please ensure that there is BCH in the given wallet. If you are running on the testnet, get some Please ensure that there is BCH in the given wallet. If you are running on the testnet, get some
@@ -343,7 +343,7 @@ class RawTransactions {
// Array input // Array input
} else if (Array.isArray(hex)) { } else if (Array.isArray(hex)) {
const options = { const options = {
method: "POST", method: 'POST',
url: `${this.restURL}rawtransactions/sendRawTransaction`, url: `${this.restURL}rawtransactions/sendRawTransaction`,
data: { data: {
hexes: hex hexes: hex
@@ -355,7 +355,7 @@ class RawTransactions {
return response.data return response.data
} }
throw new Error(`Input hex must be a string or array of strings.`) throw new Error('Input hex must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+1 -1
View File
@@ -1,4 +1,4 @@
const schnorr = require("bip-schnorr") const schnorr = require('bip-schnorr')
class Schnorr { class Schnorr {
constructor (config) { constructor (config) {
+2 -2
View File
@@ -1,5 +1,5 @@
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const opcodes = require("@psf/bitcoincash-ops") const opcodes = require('@psf/bitcoincash-ops')
class Script { class Script {
constructor () { constructor () {
+11 -5
View File
@@ -1,8 +1,8 @@
const BCHJSAddress = require("../address") const BCHJSAddress = require('../address')
// const bchAddress = new BCHJSAddress() // const bchAddress = new BCHJSAddress()
let bchAddress let bchAddress
const bchaddrjs = require("bchaddrjs-slp") const bchaddrjs = require('bchaddrjs-slp')
class Address extends BCHJSAddress { class Address extends BCHJSAddress {
constructor (config) { constructor (config) {
@@ -56,7 +56,7 @@ class Address extends BCHJSAddress {
this._ensureValidAddress(address) this._ensureValidAddress(address)
const slpAddress = bchaddrjs.toSlpAddress(address) const slpAddress = bchaddrjs.toSlpAddress(address)
if (prefix) return slpAddress if (prefix) return slpAddress
return slpAddress.split(":")[1] return slpAddress.split(':')[1]
} }
/** /**
@@ -102,7 +102,7 @@ class Address extends BCHJSAddress {
this._ensureValidAddress(address) this._ensureValidAddress(address)
const cashAddress = bchaddrjs.toCashAddress(address) const cashAddress = bchaddrjs.toCashAddress(address)
if (prefix) return cashAddress if (prefix) return cashAddress
return cashAddress.split(":")[1] return cashAddress.split(':')[1]
} }
/** /**
@@ -306,6 +306,7 @@ class Address extends BCHJSAddress {
const cashAddr = bchaddrjs.toCashAddress(address) const cashAddr = bchaddrjs.toCashAddress(address)
return bchAddress.isTestnetAddress(cashAddr) return bchAddress.isTestnetAddress(cashAddr)
} }
/** /**
* @api SLP.Address.isP2PKHAddress() isP2PKHAddress() * @api SLP.Address.isP2PKHAddress() isP2PKHAddress()
* @apiName isP2PKHAddress * @apiName isP2PKHAddress
@@ -358,6 +359,7 @@ class Address extends BCHJSAddress {
const cashAddr = bchaddrjs.toCashAddress(address) const cashAddr = bchaddrjs.toCashAddress(address)
return bchAddress.isP2PKHAddress(cashAddr) return bchAddress.isP2PKHAddress(cashAddr)
} }
/** /**
* @api SLP.Address.isP2SHAddress() isP2SHAddress() * @api SLP.Address.isP2SHAddress() isP2SHAddress()
* @apiName isP2SHAddress * @apiName isP2SHAddress
@@ -410,6 +412,7 @@ class Address extends BCHJSAddress {
const cashAddr = bchaddrjs.toCashAddress(address) const cashAddr = bchaddrjs.toCashAddress(address)
return bchAddress.isP2SHAddress(cashAddr) return bchAddress.isP2SHAddress(cashAddr)
} }
/** /**
* @api SLP.Address.detectAddressFormat() detectAddressFormat() * @api SLP.Address.detectAddressFormat() detectAddressFormat()
* @apiName detectAddressFormat * @apiName detectAddressFormat
@@ -459,10 +462,11 @@ class Address extends BCHJSAddress {
*/ */
detectAddressFormat (address) { detectAddressFormat (address) {
this._ensureValidAddress(address) this._ensureValidAddress(address)
if (bchaddrjs.isSlpAddress(address)) return "slpaddr" if (bchaddrjs.isSlpAddress(address)) return 'slpaddr'
return bchAddress.detectAddressFormat(address) return bchAddress.detectAddressFormat(address)
} }
/** /**
* @api SLP.Address.detectAddressNetwork() detectAddressNetwork() * @api SLP.Address.detectAddressNetwork() detectAddressNetwork()
* @apiName detectAddressNetwork * @apiName detectAddressNetwork
@@ -515,6 +519,7 @@ class Address extends BCHJSAddress {
const cashAddr = bchaddrjs.toCashAddress(address) const cashAddr = bchaddrjs.toCashAddress(address)
return bchAddress.detectAddressNetwork(cashAddr) return bchAddress.detectAddressNetwork(cashAddr)
} }
/** /**
* @api SLP.Address.detectAddressType() detectAddressType() * @api SLP.Address.detectAddressType() detectAddressType()
* @apiName detectAddressType * @apiName detectAddressType
@@ -567,6 +572,7 @@ class Address extends BCHJSAddress {
const cashAddr = bchaddrjs.toCashAddress(address) const cashAddr = bchaddrjs.toCashAddress(address)
return bchAddress.detectAddressType(cashAddr) return bchAddress.detectAddressType(cashAddr)
} }
/* /*
async details(address) { async details(address) {
let tmpBITBOX let tmpBITBOX
+2 -2
View File
@@ -1,9 +1,9 @@
// const BCHJS = require("../bch-js") // const BCHJS = require("../bch-js")
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
const BCHJSECPair = require("../ecpair") const BCHJSECPair = require('../ecpair')
const bchaddrjs = require("bchaddrjs-slp") const bchaddrjs = require('bchaddrjs-slp')
class ECPair extends BCHJSECPair { class ECPair extends BCHJSECPair {
/* /*
+31 -25
View File
@@ -8,14 +8,14 @@
(Parent) token. (Parent) token.
*/ */
const Address = require("./address") const Address = require('./address')
const BigNumber = require("bignumber.js") // const BigNumber = require('bignumber.js')
const slpMdm = require("slp-mdm") const slpMdm = require('slp-mdm')
// const addy = new Address() // const addy = new Address()
let addy let addy
const TransactionBuilder = require("../transaction-builder") const TransactionBuilder = require('../transaction-builder')
class TokenType1 { class TokenType1 {
constructor (config) { constructor (config) {
@@ -64,7 +64,7 @@ class TokenType1 {
// TODO: Add input validation. // TODO: Add input validation.
// Prevent error if user fails to add the document hash. // Prevent error if user fails to add the document hash.
if (!configObj.documentHash) configObj.documentHash = "" if (!configObj.documentHash) configObj.documentHash = ''
// If mint baton is not specified, then replace it with null. // If mint baton is not specified, then replace it with null.
if (!configObj.mintBatonVout) configObj.mintBatonVout = null if (!configObj.mintBatonVout) configObj.mintBatonVout = null
@@ -81,7 +81,7 @@ class TokenType1 {
return script return script
} catch (err) { } catch (err) {
console.log(`Error in generateNFTParentOpReturn()`) console.log('Error in generateNFTParentOpReturn()')
throw err throw err
} }
} }
@@ -131,26 +131,30 @@ class TokenType1 {
* // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft * // https://github.com/Permissionless-Software-Foundation/bch-js-examples/tree/master/applications/slp/nft
*/ */
mintNFTGroupOpReturn (tokenUtxos, mintQty, destroyBaton = false) { mintNFTGroupOpReturn (tokenUtxos, mintQty, destroyBaton = false) {
try { // try {
// Throw error if input is not an array. // Throw error if input is not an array.
if (!Array.isArray(tokenUtxos)) if (!Array.isArray(tokenUtxos)) {
throw new Error(`tokenUtxos must be an array.`) throw new Error('tokenUtxos must be an array.')
}
// Loop through the tokenUtxos array and find the minting baton. // Loop through the tokenUtxos array and find the minting baton.
let mintBatonUtxo let mintBatonUtxo
for (let i = 0; i < tokenUtxos.length; i++) { for (let i = 0; i < tokenUtxos.length; i++) {
if (tokenUtxos[i].utxoType === "minting-baton") if (tokenUtxos[i].utxoType === 'minting-baton') {
mintBatonUtxo = tokenUtxos[i] mintBatonUtxo = tokenUtxos[i]
} }
}
// Throw an error if the minting baton could not be found. // Throw an error if the minting baton could not be found.
if (!mintBatonUtxo) if (!mintBatonUtxo) {
throw new Error(`Minting baton could not be found in tokenUtxos array.`) throw new Error('Minting baton could not be found in tokenUtxos array.')
}
const tokenId = mintBatonUtxo.tokenId const tokenId = mintBatonUtxo.tokenId
if (!tokenId) if (!tokenId) {
throw new Error(`tokenId property not found in mint-baton UTXO.`) throw new Error('tokenId property not found in mint-baton UTXO.')
}
// Signal that the baton should be passed or detroyed. // Signal that the baton should be passed or detroyed.
let batonVout = 2 let batonVout = 2
@@ -163,10 +167,10 @@ class TokenType1 {
) )
return script return script
} catch (err) { // } catch (err) {
// console.log(`Error in generateMintOpReturn()`) // // console.log(`Error in generateMintOpReturn()`)
throw err // throw err
} // }
} }
/** /**
@@ -205,7 +209,7 @@ class TokenType1 {
// TODO: Add input validation. // TODO: Add input validation.
// Prevent error if user fails to add the document hash. // Prevent error if user fails to add the document hash.
if (!configObj.documentHash) configObj.documentHash = "" if (!configObj.documentHash) configObj.documentHash = ''
// If mint baton is not specified, then replace it with null. // If mint baton is not specified, then replace it with null.
if (!configObj.mintBatonVout) configObj.mintBatonVout = null if (!configObj.mintBatonVout) configObj.mintBatonVout = null
@@ -217,12 +221,12 @@ class TokenType1 {
configObj.documentHash, configObj.documentHash,
0, 0,
configObj.mintBatonVout, configObj.mintBatonVout,
new slpMdm.BN("1") new slpMdm.BN('1')
) )
return script return script
} catch (err) { } catch (err) {
console.log(`Error in generateNFTChildGenesisOpReturn()`) console.log('Error in generateNFTChildGenesisOpReturn()')
throw err throw err
} }
} }
@@ -278,8 +282,9 @@ class TokenType1 {
// Calculate the total amount of tokens owned by the wallet. // Calculate the total amount of tokens owned by the wallet.
let totalTokens = 0 let totalTokens = 0
for (let i = 0; i < tokenUtxos.length; i++) for (let i = 0; i < tokenUtxos.length; i++) {
totalTokens += tokenUtxos[i].tokenQty totalTokens += tokenUtxos[i].tokenQty
}
const change = totalTokens - sendQty const change = totalTokens - sendQty
@@ -312,7 +317,7 @@ class TokenType1 {
return { script, outputs } return { script, outputs }
} catch (err) { } catch (err) {
console.log(`Error in generateNFTChildSendOpReturn()`) console.log('Error in generateNFTChildSendOpReturn()')
throw err throw err
} }
} }
@@ -368,8 +373,9 @@ class TokenType1 {
// Calculate the total amount of tokens owned by the wallet. // Calculate the total amount of tokens owned by the wallet.
let totalTokens = 0 let totalTokens = 0
for (let i = 0; i < tokenUtxos.length; i++) for (let i = 0; i < tokenUtxos.length; i++) {
totalTokens += tokenUtxos[i].tokenQty totalTokens += tokenUtxos[i].tokenQty
}
const change = totalTokens - sendQty const change = totalTokens - sendQty
@@ -402,7 +408,7 @@ class TokenType1 {
return { script, outputs } return { script, outputs }
} catch (err) { } catch (err) {
console.log(`Error in generateNFTGroupSendOpReturn()`) console.log('Error in generateNFTGroupSendOpReturn()')
throw err throw err
} }
} }
+5 -5
View File
@@ -8,12 +8,12 @@
// imports // imports
// require deps // require deps
// const BCHJS = require("../bch-js") // const BCHJS = require("../bch-js")
const Address = require("./address") const Address = require('./address')
const ECPair = require("./ecpair") const ECPair = require('./ecpair')
// const HDNode = require("./hdnode") // const HDNode = require("./hdnode")
const TokenType1 = require("./tokentype1") const TokenType1 = require('./tokentype1')
const NFT1 = require("./nft1") const NFT1 = require('./nft1')
const Utils = require("./utils") const Utils = require('./utils')
// SLP is a superset of BITBOX // SLP is a superset of BITBOX
class SLP { class SLP {
+41 -29
View File
@@ -5,16 +5,16 @@
// const BCHJS = require("../bch-js") // const BCHJS = require("../bch-js")
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
const Address = require("./address") const Address = require('./address')
const Script = require("../script") const Script = require('../script')
const BigNumber = require("bignumber.js") const BigNumber = require('bignumber.js')
const slpMdm = require("slp-mdm") const slpMdm = require('slp-mdm')
const axios = require("axios") const axios = require('axios')
// const addy = new Address() // const addy = new Address()
let addy let addy
const TransactionBuilder = require("../transaction-builder") const TransactionBuilder = require('../transaction-builder')
let _this // local global let _this // local global
@@ -125,11 +125,14 @@ class TokenType1 {
// console.log(`baseChange: `, baseChange) // console.log(`baseChange: `, baseChange)
// Check for potential burns // Check for potential burns
const outputQty = new BigNumber(baseChange).plus(new BigNumber(baseQty)) const outputQty = new BigNumber(baseChange).plus(
new BigNumber(baseQty)
)
const inputQty = new BigNumber(totalTokens) const inputQty = new BigNumber(totalTokens)
const tokenOutputDelta = outputQty.minus(inputQty).toString() !== "0" const tokenOutputDelta = outputQty.minus(inputQty).toString() !== '0'
if (tokenOutputDelta) if (tokenOutputDelta) {
throw "Token transaction inputs do not match outputs, cannot send transaction" throw new Error('Token transaction inputs do not match outputs, cannot send transaction')
}
// Generate the OP_RETURN as a Buffer. // Generate the OP_RETURN as a Buffer.
script = slpMdm.TokenType1.send(tokenId, [ script = slpMdm.TokenType1.send(tokenId, [
@@ -147,9 +150,10 @@ class TokenType1 {
const noChangeOutputQty = new BigNumber(baseQty) const noChangeOutputQty = new BigNumber(baseQty)
const noChangeInputQty = new BigNumber(totalTokens) const noChangeInputQty = new BigNumber(totalTokens)
const tokenSingleOutputError = const tokenSingleOutputError =
noChangeOutputQty.minus(noChangeInputQty).toString() !== "0" noChangeOutputQty.minus(noChangeInputQty).toString() !== '0'
if (tokenSingleOutputError) if (tokenSingleOutputError) {
throw "Token transaction inputs do not match outputs, cannot send transaction" throw new Error('Token transaction inputs do not match outputs, cannot send transaction')
}
// Generate the OP_RETURN as a Buffer. // Generate the OP_RETURN as a Buffer.
script = slpMdm.TokenType1.send(tokenId, [new slpMdm.BN(baseQty)]) script = slpMdm.TokenType1.send(tokenId, [new slpMdm.BN(baseQty)])
@@ -157,7 +161,7 @@ class TokenType1 {
return { script, outputs } return { script, outputs }
} catch (err) { } catch (err) {
console.log(`Error in generateSendOpReturn()`) console.log('Error in generateSendOpReturn()')
throw err throw err
} }
} }
@@ -215,8 +219,9 @@ class TokenType1 {
// Calculate the total amount of tokens owned by the wallet. // Calculate the total amount of tokens owned by the wallet.
let totalTokens = 0 let totalTokens = 0
for (let i = 0; i < tokenUtxos.length; i++) for (let i = 0; i < tokenUtxos.length; i++) {
totalTokens += tokenUtxos[i].tokenQty totalTokens += tokenUtxos[i].tokenQty
}
const remainder = totalTokens - burnQty const remainder = totalTokens - burnQty
@@ -232,7 +237,7 @@ class TokenType1 {
return script return script
} catch (err) { } catch (err) {
console.log(`Error in generateBurnOpReturn()`) console.log('Error in generateBurnOpReturn()')
throw err throw err
} }
} }
@@ -283,7 +288,7 @@ class TokenType1 {
baseQty = baseQty.toString() baseQty = baseQty.toString()
// Prevent error if user fails to add the document hash. // Prevent error if user fails to add the document hash.
if (!configObj.documentHash) configObj.documentHash = "" if (!configObj.documentHash) configObj.documentHash = ''
// If mint baton is not specified, then replace it with null. // If mint baton is not specified, then replace it with null.
if (!configObj.mintBatonVout) configObj.mintBatonVout = null if (!configObj.mintBatonVout) configObj.mintBatonVout = null
@@ -300,7 +305,7 @@ class TokenType1 {
return script return script
} catch (err) { } catch (err) {
console.log(`Error in generateGenesisOpReturn()`) console.log('Error in generateGenesisOpReturn()')
throw err throw err
} }
} }
@@ -354,27 +359,34 @@ class TokenType1 {
generateMintOpReturn (tokenUtxos, mintQty, destroyBaton = false) { generateMintOpReturn (tokenUtxos, mintQty, destroyBaton = false) {
try { try {
// Throw error if input is not an array. // Throw error if input is not an array.
if (!Array.isArray(tokenUtxos)) if (!Array.isArray(tokenUtxos)) {
throw new Error(`tokenUtxos must be an array.`) throw new Error('tokenUtxos must be an array.')
}
// Loop through the tokenUtxos array and find the minting baton. // Loop through the tokenUtxos array and find the minting baton.
let mintBatonUtxo let mintBatonUtxo
for (let i = 0; i < tokenUtxos.length; i++) { for (let i = 0; i < tokenUtxos.length; i++) {
if (tokenUtxos[i].utxoType === "minting-baton") if (tokenUtxos[i].utxoType === 'minting-baton') {
mintBatonUtxo = tokenUtxos[i] mintBatonUtxo = tokenUtxos[i]
} }
}
// Throw an error if the minting baton could not be found. // Throw an error if the minting baton could not be found.
if (!mintBatonUtxo) if (!mintBatonUtxo) {
throw new Error(`Minting baton could not be found in tokenUtxos array.`) throw new Error(
'Minting baton could not be found in tokenUtxos array.'
)
}
const tokenId = mintBatonUtxo.tokenId const tokenId = mintBatonUtxo.tokenId
const decimals = mintBatonUtxo.decimals const decimals = mintBatonUtxo.decimals
if (!tokenId) if (!tokenId) {
throw new Error(`tokenId property not found in mint-baton UTXO.`) throw new Error('tokenId property not found in mint-baton UTXO.')
if (!decimals) }
throw new Error(`decimals property not found in mint-baton UTXO.`) if (!decimals) {
throw new Error('decimals property not found in mint-baton UTXO.')
}
let baseQty = new BigNumber(mintQty).times(10 ** decimals) let baseQty = new BigNumber(mintQty).times(10 ** decimals)
baseQty = baseQty.absoluteValue() baseQty = baseQty.absoluteValue()
@@ -393,7 +405,7 @@ class TokenType1 {
return script return script
} catch (err) { } catch (err) {
// console.log(`Error in generateMintOpReturn()`) console.log('Error in generateMintOpReturn()')
throw err throw err
} }
} }
@@ -449,7 +461,7 @@ class TokenType1 {
return slpSendObj return slpSendObj
} catch (err) { } catch (err) {
// console.log(err) console.log('Error in getHexOpReturn()')
throw err throw err
} }
} }
+66 -66
View File
@@ -1,7 +1,7 @@
// Public npm libraries // Public npm libraries
const axios = require("axios") const axios = require('axios')
const slpParser = require("slp-parser") const slpParser = require('slp-parser')
const BigNumber = require("bignumber.js") const BigNumber = require('bignumber.js')
// const Script = require("../script") // const Script = require("../script")
// const scriptLib = new Script() // const scriptLib = new Script()
@@ -200,13 +200,13 @@ class Utils {
let method let method
if (!id) { if (!id) {
method = "get" method = 'get'
path = `${this.restURL}slp/list` path = `${this.restURL}slp/list`
} else if (typeof id === "string") { } else if (typeof id === 'string') {
method = "get" method = 'get'
path = `${this.restURL}slp/list/${id}` path = `${this.restURL}slp/list/${id}`
} else if (typeof id === "object") { } else if (typeof id === 'object') {
method = "post" method = 'post'
path = `${this.restURL}slp/list` path = `${this.restURL}slp/list`
} }
@@ -214,7 +214,7 @@ class Utils {
try { try {
let response let response
if (method === "get") { if (method === 'get') {
response = await _this.axios.get(path, _this.axiosOptions) response = await _this.axios.get(path, _this.axiosOptions)
} else { } else {
response = await _this.axios.post( response = await _this.axios.post(
@@ -310,7 +310,7 @@ class Utils {
async balancesForAddress (address) { async balancesForAddress (address) {
try { try {
// Single address. // Single address.
if (typeof address === "string") { if (typeof address === 'string') {
const path = `${this.restURL}slp/balancesForAddress/${address}` const path = `${this.restURL}slp/balancesForAddress/${address}`
const response = await _this.axios.get(path, _this.axiosOptions) const response = await _this.axios.get(path, _this.axiosOptions)
@@ -332,7 +332,7 @@ class Utils {
return response.data return response.data
} }
throw new Error("Input address must be a string or array of strings.") throw new Error('Input address must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
throw error throw error
@@ -443,7 +443,7 @@ class Utils {
// Handle a single TXID or an array of TXIDs. // Handle a single TXID or an array of TXIDs.
let txids let txids
if (typeof txid === "string") txids = [txid] if (typeof txid === 'string') txids = [txid]
else txids = txid else txids = txid
try { try {
@@ -507,11 +507,12 @@ class Utils {
if ( if (
!txid || !txid ||
txid === "" || txid === '' ||
typeof txid !== "string" || typeof txid !== 'string' ||
txid.length !== 64 txid.length !== 64
) ) {
throw new Error("txid must be 64 character string.") throw new Error('txid must be 64 character string.')
}
const path = `${this.restURL}slp/validateTxid2/${txid}` const path = `${this.restURL}slp/validateTxid2/${txid}`
@@ -520,8 +521,9 @@ class Utils {
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
if (error.error && error.error.indexOf("Network error") > -1) if (error.error && error.error.indexOf('Network error') > -1) {
throw new Error("slp-validate timed out") throw new Error('slp-validate timed out')
}
throw error throw error
} }
@@ -653,7 +655,7 @@ class Utils {
// Handle a single TXID or an array of TXIDs. // Handle a single TXID or an array of TXIDs.
let txids let txids
if (typeof txid === "string") txids = [txid] if (typeof txid === 'string') txids = [txid]
else txids = txid else txids = txid
try { try {
@@ -859,11 +861,12 @@ class Utils {
try { try {
if ( if (
!txid || !txid ||
txid === "" || txid === '' ||
typeof txid !== "string" || typeof txid !== 'string' ||
txid.length !== 64 txid.length !== 64
) ) {
throw new Error("txid string must be included.") throw new Error('txid string must be included.')
}
// console.log(`this.restURL: ${this.restURL}`) // console.log(`this.restURL: ${this.restURL}`)
const path = `${this.restURL}slp/txDetails/${txid}` const path = `${this.restURL}slp/txDetails/${txid}`
@@ -929,8 +932,9 @@ class Utils {
// cache[txid] = returnValue // cache[txid] = returnValue
// Then pass that cache object back into this function every time its called. // Then pass that cache object back into this function every time its called.
if (cache) { if (cache) {
if (!(cache instanceof Object)) if (!(cache instanceof Object)) {
throw new Error("decodeOpReturn cache parameter must be Object") throw new Error('decodeOpReturn cache parameter must be Object')
}
const cachedVal = cache[txid] const cachedVal = cache[txid]
if (cachedVal) return cachedVal if (cachedVal) return cachedVal
@@ -938,8 +942,9 @@ class Utils {
try { try {
// Validate the txid input. // Validate the txid input.
if (!txid || txid === "" || typeof txid !== "string") if (!txid || txid === '' || typeof txid !== 'string') {
throw new Error("txid string must be included.") throw new Error('txid string must be included.')
}
// Retrieve the transaction object from the full node. // Retrieve the transaction object from the full node.
const path = `${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=true` const path = `${this.restURL}rawtransactions/getRawTransaction/${txid}?verbose=true`
@@ -951,19 +956,19 @@ class Utils {
const opReturn = txDetails.vout[0].scriptPubKey.hex const opReturn = txDetails.vout[0].scriptPubKey.hex
// console.log(`opReturn hex: ${opReturn}`) // console.log(`opReturn hex: ${opReturn}`)
const parsedData = _this.slpParser.parseSLP(Buffer.from(opReturn, "hex")) const parsedData = _this.slpParser.parseSLP(Buffer.from(opReturn, 'hex'))
// console.log(`parsedData: ${JSON.stringify(parsedData, null, 2)}`) // console.log(`parsedData: ${JSON.stringify(parsedData, null, 2)}`)
// Convert Buffer data to hex strings or utf8 strings. // Convert Buffer data to hex strings or utf8 strings.
let tokenData = {} let tokenData = {}
if (parsedData.transactionType === "SEND") { if (parsedData.transactionType === 'SEND') {
tokenData = { tokenData = {
tokenType: parsedData.tokenType, tokenType: parsedData.tokenType,
txType: parsedData.transactionType, txType: parsedData.transactionType,
tokenId: parsedData.data.tokenId.toString("hex"), tokenId: parsedData.data.tokenId.toString('hex'),
amounts: parsedData.data.amounts amounts: parsedData.data.amounts
} }
} else if (parsedData.transactionType === "GENESIS") { } else if (parsedData.transactionType === 'GENESIS') {
tokenData = { tokenData = {
tokenType: parsedData.tokenType, tokenType: parsedData.tokenType,
txType: parsedData.transactionType, txType: parsedData.transactionType,
@@ -976,11 +981,11 @@ class Utils {
mintBatonVout: parsedData.data.mintBatonVout, mintBatonVout: parsedData.data.mintBatonVout,
qty: parsedData.data.qty qty: parsedData.data.qty
} }
} else if (parsedData.transactionType === "MINT") { } else if (parsedData.transactionType === 'MINT') {
tokenData = { tokenData = {
tokenType: parsedData.tokenType, tokenType: parsedData.tokenType,
txType: parsedData.transactionType, txType: parsedData.transactionType,
tokenId: parsedData.data.tokenId.toString("hex"), tokenId: parsedData.data.tokenId.toString('hex'),
mintBatonVout: parsedData.data.mintBatonVout, mintBatonVout: parsedData.data.mintBatonVout,
qty: parsedData.data.qty qty: parsedData.data.qty
} }
@@ -1061,7 +1066,7 @@ class Utils {
const decodeOpReturnCache = {} const decodeOpReturnCache = {}
const cachedTxValidation = {} const cachedTxValidation = {}
// Throw error if input is not an array. // Throw error if input is not an array.
if (!Array.isArray(utxos)) throw new Error("Input must be an array.") if (!Array.isArray(utxos)) throw new Error('Input must be an array.')
// Loop through each element in the array and validate the input before // Loop through each element in the array and validate the input before
// further processing. // further processing.
@@ -1072,9 +1077,8 @@ class Utils {
// If Electrumx, convert the value to satoshis. // If Electrumx, convert the value to satoshis.
if (utxo.value) { if (utxo.value) {
utxo.satoshis = utxo.value utxo.satoshis = utxo.value
} } else {
// If there is neither a satoshis or value property, throw an error. // If there is neither a satoshis or value property, throw an error.
else {
throw new Error( throw new Error(
`utxo ${i} does not have a satoshis or value property.` `utxo ${i} does not have a satoshis or value property.`
) )
@@ -1085,9 +1089,8 @@ class Utils {
// If Electrumx, convert the tx_hash property to txid. // If Electrumx, convert the tx_hash property to txid.
if (utxo.tx_hash) { if (utxo.tx_hash) {
utxo.txid = utxo.tx_hash utxo.txid = utxo.tx_hash
} } else {
// If there is neither a txid or tx_hash property, throw an error. // If there is neither a txid or tx_hash property, throw an error.
else {
throw new Error( throw new Error(
`utxo ${i} does not have a txid or tx_hash property.` `utxo ${i} does not have a txid or tx_hash property.`
) )
@@ -1128,9 +1131,9 @@ class Utils {
// to display the unknown state. // to display the unknown state.
if ( if (
!err.message || !err.message ||
(err.message.indexOf("scriptpubkey not op_return") === -1 && (err.message.indexOf('scriptpubkey not op_return') === -1 &&
err.message.indexOf("lokad id") === -1 && err.message.indexOf('lokad id') === -1 &&
err.message.indexOf("trailing data") === -1) err.message.indexOf('trailing data') === -1)
) { ) {
// console.log( // console.log(
// `unknown error from decodeOpReturn(). Marking as 'null'`, // `unknown error from decodeOpReturn(). Marking as 'null'`,
@@ -1159,7 +1162,7 @@ class Utils {
// If there is an OP_RETURN, attempt to decode it. // If there is an OP_RETURN, attempt to decode it.
// Handle Genesis SLP transactions. // Handle Genesis SLP transactions.
if (txType === "genesis") { if (txType === 'genesis') {
if ( if (
utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output. utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output.
utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens. utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens.
@@ -1168,17 +1171,15 @@ class Utils {
// outAry[i] = false // outAry[i] = false
utxo.isValid = false utxo.isValid = false
outAry[i] = utxo outAry[i] = utxo
} } else {
// If this is a valid SLP UTXO, then return the decoded OP_RETURN data. // If this is a valid SLP UTXO, then return the decoded OP_RETURN data.
else {
// Minting Baton // Minting Baton
if (utxo.vout === slpData.mintBatonVout) { if (utxo.vout === slpData.mintBatonVout) {
utxo.utxoType = "minting-baton" utxo.utxoType = 'minting-baton'
} } else {
// Tokens // Tokens
else {
utxo.utxoType = "token" utxo.utxoType = 'token'
utxo.tokenQty = new BigNumber(slpData.qty) utxo.tokenQty = new BigNumber(slpData.qty)
.div(Math.pow(10, slpData.decimals)) .div(Math.pow(10, slpData.decimals))
.toString() .toString()
@@ -1198,7 +1199,7 @@ class Utils {
} }
// Handle Mint SLP transactions. // Handle Mint SLP transactions.
if (txType === "mint") { if (txType === 'mint') {
if ( if (
utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output. utxo.vout !== slpData.mintBatonVout && // UTXO is not a mint baton output.
utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens. utxo.vout !== 1 // UTXO is not the reciever of the genesis or mint tokens.
@@ -1207,10 +1208,9 @@ class Utils {
// outAry[i] = false // outAry[i] = false
utxo.isValid = false utxo.isValid = false
outAry[i] = utxo outAry[i] = utxo
} } else {
// If UTXO passes validation, then return formatted token data. // If UTXO passes validation, then return formatted token data.
else {
const genesisData = await this.decodeOpReturn( const genesisData = await this.decodeOpReturn(
slpData.tokenId, slpData.tokenId,
decodeOpReturnCache decodeOpReturnCache
@@ -1219,18 +1219,18 @@ class Utils {
// Minting Baton // Minting Baton
if (utxo.vout === slpData.mintBatonVout) { if (utxo.vout === slpData.mintBatonVout) {
utxo.utxoType = "minting-baton" utxo.utxoType = 'minting-baton'
} } else {
// Tokens // Tokens
else {
utxo.utxoType = "token" utxo.utxoType = 'token'
utxo.tokenQty = new BigNumber(slpData.qty) utxo.tokenQty = new BigNumber(slpData.qty)
.div(Math.pow(10, genesisData.decimals)) .div(Math.pow(10, genesisData.decimals))
.toString() .toString()
} }
// Hydrate the UTXO object with information about the SLP token. // Hydrate the UTXO object with information about the SLP token.
utxo.transactionType = "mint" utxo.transactionType = 'mint'
utxo.tokenId = slpData.tokenId utxo.tokenId = slpData.tokenId
utxo.tokenType = slpData.tokenType utxo.tokenType = slpData.tokenType
@@ -1247,7 +1247,7 @@ class Utils {
} }
// Handle Send SLP transactions. // Handle Send SLP transactions.
if (txType === "send") { if (txType === 'send') {
// Filter out any vouts that match. // Filter out any vouts that match.
// const voutMatch = slpData.spendData.filter(x => utxo.vout === x.vout) // const voutMatch = slpData.spendData.filter(x => utxo.vout === x.vout)
// console.log(`voutMatch: ${JSON.stringify(voutMatch, null, 2)}`) // console.log(`voutMatch: ${JSON.stringify(voutMatch, null, 2)}`)
@@ -1260,10 +1260,9 @@ class Utils {
// outAry[i] = false // outAry[i] = false
utxo.isValid = false utxo.isValid = false
outAry[i] = utxo outAry[i] = utxo
} } else {
// If UTXO passes validation, then return formatted token data. // If UTXO passes validation, then return formatted token data.
else {
const genesisData = await this.decodeOpReturn( const genesisData = await this.decodeOpReturn(
slpData.tokenId, slpData.tokenId,
decodeOpReturnCache decodeOpReturnCache
@@ -1273,8 +1272,8 @@ class Utils {
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`) // console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
// Hydrate the UTXO object with information about the SLP token. // Hydrate the UTXO object with information about the SLP token.
utxo.utxoType = "token" utxo.utxoType = 'token'
utxo.transactionType = "send" utxo.transactionType = 'send'
utxo.tokenId = slpData.tokenId utxo.tokenId = slpData.tokenId
utxo.tokenTicker = genesisData.ticker utxo.tokenTicker = genesisData.ticker
utxo.tokenName = genesisData.name utxo.tokenName = genesisData.name
@@ -1337,8 +1336,9 @@ class Utils {
// ) // )
// Handle corner case where SLPDB returns an array with a null element. // Handle corner case where SLPDB returns an array with a null element.
if (isValid[0] === null) if (isValid[0] === null) {
isValid = [{ txid: utxo.txid, valid: null }] isValid = [{ txid: utxo.txid, valid: null }]
}
isValid = isValid[0].valid isValid = isValid[0].valid
@@ -1596,7 +1596,7 @@ class Utils {
async hydrateUtxos (utxos) { async hydrateUtxos (utxos) {
try { try {
// Throw error if input is not an array. // Throw error if input is not an array.
if (!Array.isArray(utxos)) throw new Error("Input must be an array.") if (!Array.isArray(utxos)) throw new Error('Input must be an array.')
const response = await _this.axios.post( const response = await _this.axios.post(
`${this.restURL}slp/hydrateUtxos`, `${this.restURL}slp/hydrateUtxos`,
+5 -6
View File
@@ -1,15 +1,15 @@
const io = require("socket.io-client") const io = require('socket.io-client')
class Socket { class Socket {
constructor (config = {}) { constructor (config = {}) {
if (typeof config === "string") { if (typeof config === 'string') {
// TODO remove this check in v2.0 // TODO remove this check in v2.0
this.socket = io(`${config}`) this.socket = io(`${config}`)
} else { } else {
if (config.restURL) { if (config.restURL) {
this.socket = io(`${config.restURL}`) this.socket = io(`${config.restURL}`)
} else { } else {
const restURL = "https://rest.bitcoin.com" const restURL = 'https://rest.bitcoin.com'
this.socket = io(`${restURL}`) this.socket = io(`${restURL}`)
} }
@@ -20,9 +20,8 @@ class Socket {
listen (endpoint, cb) { listen (endpoint, cb) {
this.socket.emit(endpoint) this.socket.emit(endpoint)
if (endpoint === "blocks") this.socket.on("blocks", msg => cb(msg)) if (endpoint === 'blocks') this.socket.on('blocks', msg => cb(msg))
else if (endpoint === "transactions") else if (endpoint === 'transactions') { this.socket.on('transactions', msg => cb(msg)) }
this.socket.on("transactions", msg => cb(msg))
} }
} }
+11 -9
View File
@@ -1,18 +1,16 @@
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
const coininfo = require("@psf/coininfo") const coininfo = require('@psf/coininfo')
const bip66 = require("bip66") const bip66 = require('bip66')
const bip68 = require("bc-bip68") const bip68 = require('bc-bip68')
class TransactionBuilder { class TransactionBuilder {
static setAddress (address) { static setAddress (address) {
TransactionBuilder._address = address TransactionBuilder._address = address
} }
constructor(network = "mainnet") { constructor (network = 'mainnet') {
let bitcoincash let bitcoincash
if (network === "bitcoincash" || network === "mainnet") if (network === 'bitcoincash' || network === 'mainnet') { bitcoincash = coininfo.bitcoincash.main } else bitcoincash = coininfo.bitcoincash.test
bitcoincash = coininfo.bitcoincash.main
else bitcoincash = coininfo.bitcoincash.test
const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS() const bitcoincashBitcoinJSLib = bitcoincash.toBitcoinJS()
this.transaction = new Bitcoin.TransactionBuilder(bitcoincashBitcoinJSLib) this.transaction = new Bitcoin.TransactionBuilder(bitcoincashBitcoinJSLib)
@@ -33,7 +31,7 @@ class TransactionBuilder {
this.bip66 = bip66 this.bip66 = bip66
this.bip68 = bip68 this.bip68 = bip68
this.p2shInput = false this.p2shInput = false
this.tx // this.tx
} }
/** /**
@@ -65,6 +63,7 @@ class TransactionBuilder {
}) })
this.p2shInput = true this.p2shInput = true
} }
/** /**
* @api Transaction-Builder.addOutput() addOutput() * @api Transaction-Builder.addOutput() addOutput()
* @apiName AddOutput * @apiName AddOutput
@@ -89,6 +88,7 @@ class TransactionBuilder {
this.transaction.addOutput(scriptPubKey, amount) this.transaction.addOutput(scriptPubKey, amount)
} }
} }
/** /**
* @api Transaction-Builder.setLockTime() setLockTime() * @api Transaction-Builder.setLockTime() setLockTime()
* @apiName SetLockTime * @apiName SetLockTime
@@ -107,6 +107,7 @@ class TransactionBuilder {
setLockTime (locktime) { setLockTime (locktime) {
this.transaction.setLockTime(locktime) this.transaction.setLockTime(locktime)
} }
/** /**
* @api Transaction-Builder.sign() sign() * @api Transaction-Builder.sign() sign()
* @apiName Sign. * @apiName Sign.
@@ -144,6 +145,7 @@ class TransactionBuilder {
signatureAlgorithm signatureAlgorithm
) )
} }
/** /**
* @api Transaction-Builder.build() build() * @api Transaction-Builder.build() build()
* @apiName Build. * @apiName Build.
+4 -4
View File
@@ -1,4 +1,4 @@
const axios = require("axios") const axios = require('axios')
let _this let _this
@@ -75,7 +75,7 @@ class Util {
async validateAddress (address) { async validateAddress (address) {
try { try {
// Single block // Single block
if (typeof address === "string") { if (typeof address === 'string') {
const response = await axios.get( const response = await axios.get(
`${this.restURL}util/validateAddress/${address}`, `${this.restURL}util/validateAddress/${address}`,
_this.axiosOptions _this.axiosOptions
@@ -85,7 +85,7 @@ class Util {
// Array of blocks. // Array of blocks.
} else if (Array.isArray(address)) { } else if (Array.isArray(address)) {
const options = { const options = {
method: "POST", method: 'POST',
url: `${this.restURL}util/validateAddress`, url: `${this.restURL}util/validateAddress`,
data: { data: {
addresses: address addresses: address
@@ -99,7 +99,7 @@ class Util {
return response.data return response.data
} }
throw new Error(`Input must be a string or array of strings.`) throw new Error('Input must be a string or array of strings.')
} catch (error) { } catch (error) {
if (error.response && error.response.data) throw error.response.data if (error.response && error.response.data) throw error.response.data
else throw error else throw error
+6 -6
View File
@@ -3,16 +3,16 @@
*/ */
// const mocha = require("mocha") // const mocha = require("mocha")
const assert = require("chai").assert const assert = require('chai').assert
const sendToken = require("./send-token/send-token") const sendToken = require('./send-token/send-token')
describe("#end-to-end tests", () => { describe('#end-to-end tests', () => {
describe("#send-tokens", () => { describe('#send-tokens', () => {
it("SLPDB should update balances in less than 10 seconds", async () => { it('SLPDB should update balances in less than 10 seconds', async () => {
const result = await sendToken.sendTokenTest() const result = await sendToken.sendTokenTest()
assert(result, true, "True expected if test passed successfully.") assert(result, true, 'True expected if test passed successfully.')
}) })
}) })
}) })
+5 -5
View File
@@ -3,15 +3,15 @@
IPFS is working. IPFS is working.
*/ */
process.env.IPFS_API = `http://localhost:5001` process.env.IPFS_API = 'http://localhost:5001'
// process.env.IPFS_API = `https://ipfs-api.fullstack.cash` // process.env.IPFS_API = `https://ipfs-api.fullstack.cash`
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe(`#IPFS`, () => { describe('#IPFS', () => {
it("should upload a file to the server", async () => { it('should upload a file to the server', async () => {
const path = `${__dirname}/ipfs-e2e.js` const path = `${__dirname.toString()}/ipfs-e2e.js`
const fileModel = await bchjs.IPFS.createFileModel(path) const fileModel = await bchjs.IPFS.createFileModel(path)
console.log(`fileModel: ${JSON.stringify(fileModel, null, 2)}`) console.log(`fileModel: ${JSON.stringify(fileModel, null, 2)}`)
+12 -12
View File
@@ -12,37 +12,37 @@
mocha --timeout=30000 anonymous-rate-limits.js mocha --timeout=30000 anonymous-rate-limits.js
*/ */
const assert = require("chai").assert const assert = require('chai').assert
// const RESTURL = `https://abc.fullstack.cash/v4/` // const RESTURL = `https://abc.fullstack.cash/v4/`
const RESTURL = `https://bchn.fullstack.cash/v4/` const RESTURL = 'https://bchn.fullstack.cash/v4/'
// const RESTURL = `http://localhost:3000/v4/` // const RESTURL = `http://localhost:3000/v4/`
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({ restURL: RESTURL }) const bchjs = new BCHJS({ restURL: RESTURL })
describe("#anonymous rate limits", () => { describe('#anonymous rate limits', () => {
it("should allow an anonymous call to a full node endpoint", async () => { it('should allow an anonymous call to a full node endpoint', async () => {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
assert.property(result, "version") assert.property(result, 'version')
}).timeout(5000) }).timeout(5000)
it("should allow an anonymous call to an indexer", async () => { it('should allow an anonymous call to an indexer', async () => {
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" const addr = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "balance") assert.property(result, 'balance')
}).timeout(5000) }).timeout(5000)
it("should throw error when rate limit exceeded", async () => { it('should throw error when rate limit exceeded', async () => {
try { try {
for (let i = 0; i < 35; i++) await bchjs.Control.getNetworkInfo() for (let i = 0; i < 35; i++) await bchjs.Control.getNetworkInfo()
assert.fail("Unexpected result") assert.fail('Unexpected result')
} catch (err) { } catch (err) {
assert.include(err.error, "Too many requests") assert.include(err.error, 'Too many requests')
} }
}).timeout(20000) }).timeout(20000)
}) })
+12 -12
View File
@@ -7,49 +7,49 @@
- Update the PRO_PASS value with a current PRO_PASSES string used by bch-api. - Update the PRO_PASS value with a current PRO_PASSES string used by bch-api.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const PRO_PASS = "testpassword" const PRO_PASS = 'testpassword'
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({ const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`, // restURL: `https://bchn.fullstack.cash/v4/`,
restURL: `https://abc.fullstack.cash/v4/`, restURL: 'https://abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`, // restURL: `http://localhost:3000/v4/`,
authPass: PRO_PASS authPass: PRO_PASS
}) })
describe("#Basic Authentication rate limits", () => { describe('#Basic Authentication rate limits', () => {
it("should allow more than 20 RPM to full node", async () => { it('should allow more than 20 RPM to full node', async () => {
for (let i = 0; i < 22; i++) { for (let i = 0; i < 22; i++) {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 3 calls allowed") assert.property(result, 'version', 'more than 3 calls allowed')
} }
if (i === 15) { if (i === 15) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 10 calls allowed") assert.property(result, 'version', 'more than 10 calls allowed')
} }
} }
}).timeout(45000) }).timeout(45000)
it("should allow more than 20 RPM to an indexer", async () => { it('should allow more than 20 RPM to an indexer', async () => {
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" const addr = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
for (let i = 0; i < 22; i++) { for (let i = 0; i < 22; i++) {
const result = await bchjs.Blockbook.balance(addr) const result = await bchjs.Blockbook.balance(addr)
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "balance", "more than 3 calls allowed") assert.property(result, 'balance', 'more than 3 calls allowed')
} }
if (i === 15) { if (i === 15) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "balance", "more than 10 calls allowed") assert.property(result, 'balance', 'more than 10 calls allowed')
} }
} }
}).timeout(45000) }).timeout(45000)
+20 -20
View File
@@ -11,59 +11,59 @@
- Update the JWT_TOKEN value with a current free-level JWT token. - Update the JWT_TOKEN value with a current free-level JWT token.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const JWT_TOKEN = const JWT_TOKEN =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2YyMDIyMWMxMDAxMmFkOTQwMSIsImVtYWlsIjoiZGVtb0BkZW1vLmNvbSIsImFwaUxldmVsIjoxMCwicmF0ZUxpbWl0IjozLCJpYXQiOjE2MDQ4NTQ2OTEsImV4cCI6MTYwNzQ0NjY5MX0.iwse0z0KDKHx9graCxcOwj6lSlfKQAb1zLhmjvygvts" 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2YyMDIyMWMxMDAxMmFkOTQwMSIsImVtYWlsIjoiZGVtb0BkZW1vLmNvbSIsImFwaUxldmVsIjoxMCwicmF0ZUxpbWl0IjozLCJpYXQiOjE2MDQ4NTQ2OTEsImV4cCI6MTYwNzQ0NjY5MX0.iwse0z0KDKHx9graCxcOwj6lSlfKQAb1zLhmjvygvts'
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({ const bchjs = new BCHJS({
restURL: `https://api.fullstack.cash/v4/`, restURL: 'https://api.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`, // restURL: `http://localhost:3000/v4/`,
apiToken: JWT_TOKEN apiToken: JWT_TOKEN
}) })
describe("#free rate limits", () => { describe('#free rate limits', () => {
it("should allow an free call to an indexer", async () => { it('should allow an free call to an indexer', async () => {
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" const addr = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
const result = await bchjs.Blockbook.balance(addr) const result = await bchjs.Blockbook.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "balance") assert.property(result, 'balance')
}).timeout(5000) }).timeout(5000)
it("should allow up to 10 RPM to indexer, then throw error", async () => { it('should allow up to 10 RPM to indexer, then throw error', async () => {
try { try {
const addr = "bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0" const addr = 'bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0'
for (let i = 0; i < 15; i++) { for (let i = 0; i < 15; i++) {
const result = await await bchjs.Blockbook.balance(addr) const result = await await bchjs.Blockbook.balance(addr)
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "address", "more than 3 calls allowed") assert.property(result, 'address', 'more than 3 calls allowed')
} }
} }
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.error, err.error,
"currently 10 requests", 'currently 10 requests',
"more than 10 not allowed" 'more than 10 not allowed'
) )
assert.include(err.error, 10) assert.include(err.error, 10)
assert.notInclude(err.error, 3) assert.notInclude(err.error, 3)
} }
}).timeout(20000) }).timeout(20000)
it("should allow up to 10 RPM to full node, then throw error", async () => { it('should allow up to 10 RPM to full node, then throw error', async () => {
try { try {
for (let i = 0; i < 15; i++) { for (let i = 0; i < 15; i++) {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 3 calls allowed") assert.property(result, 'version', 'more than 3 calls allowed')
} }
} }
} catch (err) { } catch (err) {
@@ -71,22 +71,22 @@ describe("#free rate limits", () => {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.error, err.error,
"currently 10 requests", 'currently 10 requests',
"more than 10 not allowed" 'more than 10 not allowed'
) )
assert.include(err.error, 10) assert.include(err.error, 10)
assert.notInclude(err.error, 3) assert.notInclude(err.error, 3)
} }
}).timeout(20000) }).timeout(20000)
it("should throw error when rate limit exceeded 20 RPM for indexer endpoints", async () => { it('should throw error when rate limit exceeded 20 RPM for indexer endpoints', async () => {
try { try {
for (let i = 0; i < 22; i++) await bchjs.Control.getNetworkInfo() for (let i = 0; i < 22; i++) await bchjs.Control.getNetworkInfo()
assert.fail("unexpected result") assert.fail('unexpected result')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.error, "Too many requests") assert.include(err.error, 'Too many requests')
} }
}).timeout(20000) }).timeout(20000)
}) })
+14 -14
View File
@@ -11,26 +11,26 @@
- Update the JWT_TOKEN value with a paid tier JWT token. - Update the JWT_TOKEN value with a paid tier JWT token.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const JWT_TOKEN = const JWT_TOKEN =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M" 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M'
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({ const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`, // restURL: `https://bchn.fullstack.cash/v4/`,
restURL: `https:/abc.fullstack.cash/v4/`, restURL: 'https:/abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`, // restURL: `http://localhost:3000/v4/`,
apiToken: JWT_TOKEN apiToken: JWT_TOKEN
}) })
describe("#full node rate limits", () => { describe('#full node rate limits', () => {
it("should allow an free call to an indexer", async () => { it('should allow an free call to an indexer', async () => {
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" const addr = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "balance") assert.property(result, 'balance')
}).timeout(5000) }).timeout(5000)
// CT 11/8/20: New rate limits make this test invalid. // CT 11/8/20: New rate limits make this test invalid.
@@ -47,30 +47,30 @@ describe("#full node rate limits", () => {
// } // }
// }).timeout(10000) // }).timeout(10000)
it("should allow more than 20 RPM to full node", async () => { it('should allow more than 20 RPM to full node', async () => {
for (let i = 0; i < 22; i++) { for (let i = 0; i < 22; i++) {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 3 calls allowed") assert.property(result, 'version', 'more than 3 calls allowed')
} }
if (i === 15) { if (i === 15) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 10 calls allowed") assert.property(result, 'version', 'more than 10 calls allowed')
} }
} }
}).timeout(20000) }).timeout(20000)
it("should throw error for more than 100 RPM to fullnode", async () => { it('should throw error for more than 100 RPM to fullnode', async () => {
try { try {
console.log(`This test usually doesn't pass, because of latency.`) console.log('This test usually doesn\'t pass, because of latency.')
for (let i = 0; i < 100; i++) await bchjs.Control.getNetworkInfo() for (let i = 0; i < 100; i++) await bchjs.Control.getNetworkInfo()
} catch (err) { } catch (err) {
// console.log(`validating after 10th call`) // console.log(`validating after 10th call`)
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.error, "Too many requests") assert.include(err.error, 'Too many requests')
assert.include(err.error, 100) assert.include(err.error, 100)
} }
}).timeout(45000) }).timeout(45000)
+12 -12
View File
@@ -7,50 +7,50 @@
- Update the JWT_TOKEN value with a current indexer-level JWT token. - Update the JWT_TOKEN value with a current indexer-level JWT token.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const JWT_TOKEN = const JWT_TOKEN =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M" 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMzIyNzEwNCwiZXhwIjoxNjA1ODE5MTA0fQ.CV36grzdD36Ht3BwZGHG4XU40CVDzMRw9Ars1x1r27M'
const BCHJS = require("../../../src/bch-js") const BCHJS = require('../../../src/bch-js')
const bchjs = new BCHJS({ const bchjs = new BCHJS({
// restURL: `https://bchn.fullstack.cash/v4/`, // restURL: `https://bchn.fullstack.cash/v4/`,
restURL: `https://abc.fullstack.cash/v4/`, restURL: 'https://abc.fullstack.cash/v4/',
// restURL: `http://localhost:3000/v4/`, // restURL: `http://localhost:3000/v4/`,
apiToken: JWT_TOKEN apiToken: JWT_TOKEN
}) })
describe("#Indexer rate limits", () => { describe('#Indexer rate limits', () => {
it("should allow more than 20 RPM to full node", async () => { it('should allow more than 20 RPM to full node', async () => {
for (let i = 0; i < 22; i++) { for (let i = 0; i < 22; i++) {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 3 calls allowed") assert.property(result, 'version', 'more than 3 calls allowed')
} }
if (i === 15) { if (i === 15) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "version", "more than 10 calls allowed") assert.property(result, 'version', 'more than 10 calls allowed')
} }
} }
}).timeout(45000) }).timeout(45000)
it("should allow more than 20 RPM to an indexer", async () => { it('should allow more than 20 RPM to an indexer', async () => {
const addr = "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" const addr = 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
for (let i = 0; i < 22; i++) { for (let i = 0; i < 22; i++) {
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
if (i === 5) { if (i === 5) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "balance", "more than 3 calls allowed") assert.property(result, 'balance', 'more than 3 calls allowed')
} }
if (i === 15) { if (i === 15) {
// console.log(`validating 5th call: ${i}`) // console.log(`validating 5th call: ${i}`)
assert.property(result, "balance", "more than 10 calls allowed") assert.property(result, 'balance', 'more than 10 calls allowed')
} }
} }
}).timeout(45000) }).timeout(45000)
@@ -13,24 +13,25 @@
*/ */
// Replace the address below with the address you want to send the BCH to. // Replace the address below with the address you want to send the BCH to.
const RECV_ADDR1 = `bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05` const RECV_ADDR1 = 'bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05'
const RECV_ADDR2 = `bchtest:qz6yw0kqgfkknfy6jh2jvlfnkzmre3lt2u0pgcckdk` const RECV_ADDR2 = 'bchtest:qz6yw0kqgfkknfy6jh2jvlfnkzmre3lt2u0pgcckdk'
const SATOSHIS_TO_SEND = 1000 const SATOSHIS_TO_SEND = 1000
// Instantiate BITBOX. // Instantiate BITBOX.
const bitboxLib = "../../../lib/BITBOX" const bitboxLib = '../../../lib/BITBOX'
const BITBOXSDK = require(bitboxLib) const BITBOXSDK = require(bitboxLib)
const BITBOX = new BITBOXSDK({ restURL: "https://trest.bitcoin.com/v2/" }) const BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" }) // const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
const util = require("util") // const util = require('util')
// Open the wallet generated with create-wallet. // Open the wallet generated with create-wallet.
let walletInfo = {}
try { try {
var walletInfo = require(`./wallet.json`) walletInfo = require('./wallet.json')
} catch (err) { } catch (err) {
console.log( console.log(
`Could not open wallet.json. Generate a wallet with create-wallet first.` 'Could not open wallet.json. Generate a wallet with create-wallet first.'
) )
process.exit(0) process.exit(0)
} }
@@ -51,9 +52,9 @@ async function testSend() {
hex2 hex2
]) ])
console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`) console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`)
console.log(`Should return an array of TXID strings.`) console.log('Should return an array of TXID strings.')
} catch (err) { } catch (err) {
console.log(`Error in testSend: `, err) console.log('Error in testSend: ', err)
} }
} }
testSend() testSend()
@@ -68,7 +69,7 @@ async function buildTx1(recAddr) {
// Exit if the balance is zero. // Exit if the balance is zero.
if (balance <= 0.0) { if (balance <= 0.0) {
console.log(`Balance of sending address is zero. Exiting.`) console.log('Balance of sending address is zero. Exiting.')
process.exit(0) process.exit(0)
} }
@@ -77,8 +78,9 @@ async function buildTx1(recAddr) {
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`) console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`) console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
const balance2 = await getBCHBalance(recAddr, false) // const balance2 = await getBCHBalance(recAddr, false)
// console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`) // console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
await getBCHBalance(recAddr, false)
const u = await BITBOX.Address.utxo(SEND_ADDR) const u = await BITBOX.Address.utxo(SEND_ADDR)
// console.log(`u: ${JSON.stringify(u, null, 2)}`) // console.log(`u: ${JSON.stringify(u, null, 2)}`)
@@ -86,7 +88,7 @@ async function buildTx1(recAddr) {
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`) console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
// instance of transaction builder // instance of transaction builder
const transactionBuilder = new BITBOX.TransactionBuilder("testnet") const transactionBuilder = new BITBOX.TransactionBuilder('testnet')
const satoshisToSend = SATOSHIS_TO_SEND const satoshisToSend = SATOSHIS_TO_SEND
const originalAmount = utxo.satoshis const originalAmount = utxo.satoshis
@@ -137,7 +139,7 @@ async function buildTx1(recAddr) {
return hex return hex
} catch (err) { } catch (err) {
console.log(`Error in buildTx().`) console.log('Error in buildTx().')
throw err throw err
} }
} }
@@ -152,7 +154,7 @@ async function buildTx2(recAddr) {
// Exit if the balance is zero. // Exit if the balance is zero.
if (balance <= 0.0) { if (balance <= 0.0) {
console.log(`Balance of sending address is zero. Exiting.`) console.log('Balance of sending address is zero. Exiting.')
process.exit(0) process.exit(0)
} }
@@ -161,8 +163,9 @@ async function buildTx2(recAddr) {
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`) console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`) console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
const balance2 = await getBCHBalance(recAddr, false) // const balance2 = await getBCHBalance(recAddr, false)
// console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`) // console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
await getBCHBalance(recAddr, false)
const u = await BITBOX.Address.utxo(SEND_ADDR) const u = await BITBOX.Address.utxo(SEND_ADDR)
// console.log(`u: ${JSON.stringify(u, null, 2)}`) // console.log(`u: ${JSON.stringify(u, null, 2)}`)
@@ -170,7 +173,7 @@ async function buildTx2(recAddr) {
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`) console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
// instance of transaction builder // instance of transaction builder
const transactionBuilder = new BITBOX.TransactionBuilder("testnet") const transactionBuilder = new BITBOX.TransactionBuilder('testnet')
const satoshisToSend = SATOSHIS_TO_SEND const satoshisToSend = SATOSHIS_TO_SEND
const originalAmount = utxo.satoshis const originalAmount = utxo.satoshis
@@ -221,7 +224,7 @@ async function buildTx2(recAddr) {
return hex return hex
} catch (err) { } catch (err) {
console.log(`Error in buildTx().`) console.log('Error in buildTx().')
throw err throw err
} }
} }
@@ -232,13 +235,13 @@ function changeAddrFromMnemonic(mnemonic) {
const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic) const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic)
// master HDNode // master HDNode
const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "testnet") const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, 'testnet')
// HDNode of BIP44 account // HDNode of BIP44 account
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'") const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
// derive the first external change address HDNode which is going to spend utxo // derive the first external change address HDNode which is going to spend utxo
const change = BITBOX.HDNode.derivePath(account, "0/0") const change = BITBOX.HDNode.derivePath(account, '0/0')
return change return change
} }
@@ -254,7 +257,7 @@ async function getBCHBalance(addr, verbose) {
return bchBalance.balance return bchBalance.balance
} catch (err) { } catch (err) {
console.error(`Error in getBCHBalance: `, err) console.error('Error in getBCHBalance: ', err)
console.log(`addr: ${addr}`) console.log(`addr: ${addr}`)
throw err throw err
} }
@@ -13,23 +13,24 @@
*/ */
// Replace the address below with the address you want to send the BCH to. // Replace the address below with the address you want to send the BCH to.
const RECV_ADDR1 = `bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05` const RECV_ADDR1 = 'bchtest:qzfn2mly05t6fjsh5kjj0dqq0jjtct27ng089dgg05'
const SATOSHIS_TO_SEND = 1000 const SATOSHIS_TO_SEND = 1000
// Instantiate BITBOX. // Instantiate BITBOX.
const bitboxLib = "../../../lib/BITBOX" const bitboxLib = '../../../lib/BITBOX'
const BITBOXSDK = require(bitboxLib) const BITBOXSDK = require(bitboxLib)
const BITBOX = new BITBOXSDK({ restURL: "https://trest.bitcoin.com/v2/" }) const BITBOX = new BITBOXSDK({ restURL: 'https://trest.bitcoin.com/v2/' })
// const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" }) // const BITBOX = new BITBOXSDK({ restURL: "http://localhost:3000/v2/" })
const util = require("util") // const util = require('util')
// Open the wallet generated with create-wallet. // Open the wallet generated with create-wallet.
let walletInfo = {}
try { try {
var walletInfo = require(`./wallet.json`) walletInfo = require('./wallet.json')
} catch (err) { } catch (err) {
console.log( console.log(
`Could not open wallet.json. Generate a wallet with create-wallet first.` 'Could not open wallet.json. Generate a wallet with create-wallet first.'
) )
process.exit(0) process.exit(0)
} }
@@ -48,9 +49,9 @@ async function testSend() {
const broadcast = await BITBOX.RawTransactions.sendRawTransaction(hex1) const broadcast = await BITBOX.RawTransactions.sendRawTransaction(hex1)
console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`) console.log(`Transaction IDs: ${JSON.stringify(broadcast, null, 2)}`)
console.log(`Should return a TXID string.`) console.log('Should return a TXID string.')
} catch (err) { } catch (err) {
console.log(`Error in testSend: `, err) console.log('Error in testSend: ', err)
} }
} }
testSend() testSend()
@@ -65,7 +66,7 @@ async function buildTx1(recAddr) {
// Exit if the balance is zero. // Exit if the balance is zero.
if (balance <= 0.0) { if (balance <= 0.0) {
console.log(`Balance of sending address is zero. Exiting.`) console.log('Balance of sending address is zero. Exiting.')
process.exit(0) process.exit(0)
} }
@@ -74,8 +75,9 @@ async function buildTx1(recAddr) {
console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`) console.log(`Sender Legacy Address: ${SEND_ADDR_LEGACY}`)
console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`) console.log(`Receiver Legacy Address: ${RECV_ADDR_LEGACY}`)
const balance2 = await getBCHBalance(recAddr, false) // const balance2 = await getBCHBalance(recAddr, false)
// console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`) // console.log(`Balance of recieving address ${recAddr} is ${balance2} BCH.`)
await getBCHBalance(recAddr, false)
const u = await BITBOX.Address.utxo(SEND_ADDR) const u = await BITBOX.Address.utxo(SEND_ADDR)
// console.log(`u: ${JSON.stringify(u, null, 2)}`) // console.log(`u: ${JSON.stringify(u, null, 2)}`)
@@ -83,7 +85,7 @@ async function buildTx1(recAddr) {
console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`) console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
// instance of transaction builder // instance of transaction builder
const transactionBuilder = new BITBOX.TransactionBuilder("testnet") const transactionBuilder = new BITBOX.TransactionBuilder('testnet')
const satoshisToSend = SATOSHIS_TO_SEND const satoshisToSend = SATOSHIS_TO_SEND
const originalAmount = utxo.satoshis const originalAmount = utxo.satoshis
@@ -134,7 +136,7 @@ async function buildTx1(recAddr) {
return hex return hex
} catch (err) { } catch (err) {
console.log(`Error in buildTx().`) console.log('Error in buildTx().')
throw err throw err
} }
} }
@@ -145,13 +147,13 @@ function changeAddrFromMnemonic(mnemonic) {
const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic) const rootSeed = BITBOX.Mnemonic.toSeed(mnemonic)
// master HDNode // master HDNode
const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, "testnet") const masterHDNode = BITBOX.HDNode.fromSeed(rootSeed, 'testnet')
// HDNode of BIP44 account // HDNode of BIP44 account
const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'") const account = BITBOX.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
// derive the first external change address HDNode which is going to spend utxo // derive the first external change address HDNode which is going to spend utxo
const change = BITBOX.HDNode.derivePath(account, "0/0") const change = BITBOX.HDNode.derivePath(account, '0/0')
return change return change
} }
@@ -167,7 +169,7 @@ async function getBCHBalance(addr, verbose) {
return bchBalance.balance return bchBalance.balance
} catch (err) { } catch (err) {
console.error(`Error in getBCHBalance: `, err) console.error('Error in getBCHBalance: ', err)
console.log(`addr: ${addr}`) console.log(`addr: ${addr}`)
throw err throw err
} }
+10 -10
View File
@@ -8,7 +8,7 @@
*/ */
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
@@ -18,10 +18,10 @@ util.inspect.defaultOptions = {
// const SLPSDK = require("../../../lib/SLP") // const SLPSDK = require("../../../lib/SLP")
// const slpsdk = new SLPSDK() // const slpsdk = new SLPSDK()
const WALLET1 = `../wallet1.json` const WALLET1 = '../wallet1.json'
const WALLET2 = `../wallet2.json` const WALLET2 = '../wallet2.json'
const lib = require("../util/e2e-util") const lib = require('../util/e2e-util')
// The main test function. // The main test function.
// Sends a token and reports on how long it takes to show up in SLPDB production. // Sends a token and reports on how long it takes to show up in SLPDB production.
@@ -46,7 +46,7 @@ async function sendTokenTest() {
// Send a token to the recieving wallet. // Send a token to the recieving wallet.
await lib.sendToken(sendWallet, recvWallet) await lib.sendToken(sendWallet, recvWallet)
console.log(`Sent test token.`) console.log('Sent test token.')
// Track the time until the balance for the recieving wallet has been updated. // Track the time until the balance for the recieving wallet has been updated.
const startTime = new Date() const startTime = new Date()
@@ -56,7 +56,7 @@ async function sendTokenTest() {
for (let i = 0; i < 50; i++) { for (let i = 0; i < 50; i++) {
await sleep(waitTime) // Wait for a while before checking await sleep(waitTime) // Wait for a while before checking
console.log(`Checking token balance...`) console.log('Checking token balance...')
newBalance = await lib.getTestTokenBalance(recvWallet) newBalance = await lib.getTestTokenBalance(recvWallet)
// Break out of the loop once a new balance is detected. // Break out of the loop once a new balance is detected.
@@ -65,12 +65,12 @@ async function sendTokenTest() {
// Provide high-level warnings. // Provide high-level warnings.
const secondsPassed = (i * waitTime) / 1000 const secondsPassed = (i * waitTime) / 1000
if (secondsPassed > 60 * 10) { if (secondsPassed > 60 * 10) {
console.log(`More than 10 minutes passed.`) console.log('More than 10 minutes passed.')
return false // Fail the test. return false // Fail the test.
} else if (secondsPassed > 60 * 5) { } else if (secondsPassed > 60 * 5) {
console.log(`More than 5 minutes passed.`) console.log('More than 5 minutes passed.')
} else if (secondsPassed > 60) { } else if (secondsPassed > 60) {
console.log(`More than 1 minute passed.`) console.log('More than 1 minute passed.')
} }
} }
@@ -85,7 +85,7 @@ async function sendTokenTest() {
return deltaTime // Return the time in minutes it took for SLPDB to update. return deltaTime // Return the time in minutes it took for SLPDB to update.
} catch (err) { } catch (err) {
console.log(`Error in e2e/send-token.js/sendTokenTest(): `, err) console.log('Error in e2e/send-token.js/sendTokenTest(): ', err)
return false return false
} }
} }
+10 -9
View File
@@ -10,17 +10,17 @@ module.exports = {
threeDecimals threeDecimals
} }
const SLPSDK = require("../../../lib/SLP") const SLPSDK = require('../../../lib/SLP')
const slpsdk = new SLPSDK() const slpsdk = new SLPSDK()
const testTokenId = const testTokenId =
"cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67" 'cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67'
// Open a wallet and return an object with its address, BCH balance, and SLP // Open a wallet and return an object with its address, BCH balance, and SLP
// token balance. // token balance.
async function openWallet (filename) { async function openWallet (filename) {
try { try {
walletInfo = require(filename) const walletInfo = require(filename)
// const walletBalance = await getBalance(walletInfo) // const walletBalance = await getBalance(walletInfo)
// const walletBalance = await slpsdk.Utils.balancesForAddress( // const walletBalance = await slpsdk.Utils.balancesForAddress(
@@ -53,7 +53,7 @@ async function sendToken(wallet1, wallet2) {
// HDNode of BIP44 account // HDNode of BIP44 account
const account = slpsdk.HDNode.derivePath(masterHDNode, "m/44'/145'/0'") const account = slpsdk.HDNode.derivePath(masterHDNode, "m/44'/145'/0'")
const change = slpsdk.HDNode.derivePath(account, "0/0") const change = slpsdk.HDNode.derivePath(account, '0/0')
// get the cash address // get the cash address
// const cashAddress = slpsdk.HDNode.toCashAddress(change) // const cashAddress = slpsdk.HDNode.toCashAddress(change)
@@ -71,7 +71,7 @@ async function sendToken(wallet1, wallet2) {
tokenReceiverAddress, tokenReceiverAddress,
bchChangeReceiverAddress, bchChangeReceiverAddress,
tokenId: tokenId:
"cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67", 'cc1b2084a9c43bb5a633df7f38201adde5c5f5cef2fed945d12f8dcd4e505c67',
amount: 1 amount: 1
} }
@@ -79,11 +79,12 @@ async function sendToken(wallet1, wallet2) {
// Generate, sign, and broadcast a hex-encoded transaction for sending // Generate, sign, and broadcast a hex-encoded transaction for sending
// the tokens. // the tokens.
const sendTxId = await slpsdk.TokenType1.send(sendConfig) // const sendTxId = await slpsdk.TokenType1.send(sendConfig)
await slpsdk.TokenType1.send(sendConfig)
// console.log(`sendTxId: ${sendTxId}`) // console.log(`sendTxId: ${sendTxId}`)
} catch (err) { } catch (err) {
console.log(`Error in e2e-util.js/sendToken()`) console.log('Error in e2e-util.js/sendToken()')
throw err throw err
} }
} }
@@ -100,7 +101,7 @@ async function getTestTokenBalance(walletData) {
return testTokens[0].balance return testTokens[0].balance
} catch (err) { } catch (err) {
console.log(`Error in e2e-util.js/getTestTokenBalance()`) console.log('Error in e2e-util.js/getTestTokenBalance()')
throw err throw err
} }
} }
@@ -113,7 +114,7 @@ function threeDecimals(inNum) {
tempNum = tempNum / 1000 tempNum = tempNum / 1000
return tempNum return tempNum
} catch (err) { } catch (err) {
console.log(`Error in e2e-util.js/threeDecimals()`) console.log('Error in e2e-util.js/threeDecimals()')
throw err throw err
} }
} }
+80 -80
View File
@@ -7,109 +7,109 @@
of an e2e test to be properly tested. of an e2e test to be properly tested.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe(`#blockchain`, () => { describe('#blockchain', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#getBestBlockHash`, () => { describe('#getBestBlockHash', () => {
it(`should GET best block hash`, async () => { it('should GET best block hash', async () => {
const result = await bchjs.Blockchain.getBestBlockHash() const result = await bchjs.Blockchain.getBestBlockHash()
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.isString(result) assert.isString(result)
assert.equal(result.length, 64, "Specific hash length") assert.equal(result.length, 64, 'Specific hash length')
}) })
}) })
describe("#getBlockHeader", () => { describe('#getBlockHeader', () => {
it(`should GET block header for a single hash`, async () => { it('should GET block header for a single hash', async () => {
const hash = const hash =
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201" '000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201'
const result = await bchjs.Blockchain.getBlockHeader(hash) const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"hash", 'hash',
"confirmations", 'confirmations',
"height", 'height',
"version", 'version',
"versionHex", 'versionHex',
"merkleroot", 'merkleroot',
"time", 'time',
"mediantime", 'mediantime',
"nonce", 'nonce',
"bits", 'bits',
"difficulty", 'difficulty',
"chainwork", 'chainwork',
"previousblockhash", 'previousblockhash',
"nextblockhash", 'nextblockhash',
"nTx" 'nTx'
]) ])
}) })
it(`should GET block headers for an array of hashes`, async () => { it('should GET block headers for an array of hashes', async () => {
const hash = [ const hash = [
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201", '000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201',
"00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3" '00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3'
] ]
const result = await bchjs.Blockchain.getBlockHeader(hash) const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.isArray(result) assert.isArray(result)
assert.hasAllKeys(result[0], [ assert.hasAllKeys(result[0], [
"hash", 'hash',
"confirmations", 'confirmations',
"height", 'height',
"version", 'version',
"versionHex", 'versionHex',
"merkleroot", 'merkleroot',
"time", 'time',
"mediantime", 'mediantime',
"nonce", 'nonce',
"bits", 'bits',
"difficulty", 'difficulty',
"chainwork", 'chainwork',
"previousblockhash", 'previousblockhash',
"nextblockhash", 'nextblockhash',
"nTx" 'nTx'
]) ])
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
data.push( data.push(
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201" '000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201'
) )
} }
const result = await bchjs.Blockchain.getBlockHeader(data) const result = await bchjs.Blockchain.getBlockHeader(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#getMempoolEntry", () => { describe('#getMempoolEntry', () => {
/* /*
// To run this test, the txid must be unconfirmed. // To run this test, the txid must be unconfirmed.
const txid = const txid =
@@ -161,26 +161,26 @@ describe(`#blockchain`, () => {
}) })
*/ */
it(`should throw an error if txid is not in mempool`, async () => { it('should throw an error if txid is not in mempool', async () => {
try { try {
const txid = const txid =
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7" '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7'
await bchjs.Blockchain.getMempoolEntry(txid) await bchjs.Blockchain.getMempoolEntry(txid)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, `Transaction not in mempool`) assert.include(err.error, 'Transaction not in mempool')
} }
}) })
}) })
describe(`#getTxOutProof`, () => { describe('#getTxOutProof', () => {
it(`should get single tx out proof`, async () => { it('should get single tx out proof', async () => {
const txid = const txid =
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7" '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7'
const result = await bchjs.Blockchain.getTxOutProof(txid) const result = await bchjs.Blockchain.getTxOutProof(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -188,10 +188,10 @@ describe(`#blockchain`, () => {
assert.isString(result) assert.isString(result)
}) })
it(`should get an array of tx out proofs`, async () => { it('should get an array of tx out proofs', async () => {
const txid = [ const txid = [
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7", '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7',
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33" 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'
] ]
const result = await bchjs.Blockchain.getTxOutProof(txid) const result = await bchjs.Blockchain.getTxOutProof(txid)
@@ -202,11 +202,11 @@ describe(`#blockchain`, () => {
}) })
}) })
describe(`#verifyTxOutProof`, () => { describe('#verifyTxOutProof', () => {
const mockTxOutProof = const mockTxOutProof =
"0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01" '0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01'
it(`should verify a single proof`, async () => { it('should verify a single proof', async () => {
const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof) const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -214,11 +214,11 @@ describe(`#blockchain`, () => {
assert.isString(result[0]) assert.isString(result[0])
assert.equal( assert.equal(
result[0], result[0],
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7" '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7'
) )
}) })
it(`should verify an array of proofs`, async () => { it('should verify an array of proofs', async () => {
const proofs = [mockTxOutProof, mockTxOutProof] const proofs = [mockTxOutProof, mockTxOutProof]
const result = await bchjs.Blockchain.verifyTxOutProof(proofs) const result = await bchjs.Blockchain.verifyTxOutProof(proofs)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -227,11 +227,11 @@ describe(`#blockchain`, () => {
assert.isString(result[0]) assert.isString(result[0])
assert.equal( assert.equal(
result[0], result[0],
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7" '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7'
) )
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(mockTxOutProof) for (let i = 0; i < 25; i++) data.push(mockTxOutProof)
@@ -239,35 +239,35 @@ describe(`#blockchain`, () => {
const result = await bchjs.Blockchain.verifyTxOutProof(data) const result = await bchjs.Blockchain.verifyTxOutProof(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#getTxOut", () => { describe('#getTxOut', () => {
it("should get information on an unspent tx", async () => { it('should get information on an unspent tx', async () => {
const result = await bchjs.Blockchain.getTxOut( const result = await bchjs.Blockchain.getTxOut(
"62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8", '62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8',
0, 0,
true true
) )
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"bestblock", 'bestblock',
"confirmations", 'confirmations',
"value", 'value',
"scriptPubKey", 'scriptPubKey',
"coinbase" 'coinbase'
]) ])
}) })
it("should get information on a spent tx", async () => { it('should get information on a spent tx', async () => {
const result = await bchjs.Blockchain.getTxOut( const result = await bchjs.Blockchain.getTxOut(
"87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871", '87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871',
0, 0,
true true
) )
+15 -15
View File
@@ -5,20 +5,20 @@
TODO TODO
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#rawtransaction", () => { describe('#rawtransaction', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
@@ -29,29 +29,29 @@ describe("#rawtransaction", () => {
below expect error messages returned from the server, but at least test below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently. that the server is responding on those endpoints, and responds consistently.
*/ */
describe("sendRawTransaction", () => { describe('sendRawTransaction', () => {
it("should send a single transaction hex", async () => { it('should send a single transaction hex', async () => {
try { try {
const hex = const hex =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex) await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "bad-txns-inputs-missingorspent") assert.include(err.error, 'bad-txns-inputs-missingorspent')
} }
}) })
it("should send an array of tx hexes", async () => { it('should send an array of tx hexes', async () => {
try { try {
const hexes = [ const hexes = [
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000", '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
] ]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes) const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
@@ -59,8 +59,8 @@ describe("#rawtransaction", () => {
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "bad-txns-inputs-missingorspent") assert.include(err.error, 'bad-txns-inputs-missingorspent')
} }
}) })
}) })
+44 -44
View File
@@ -3,21 +3,21 @@
These tests are specific to the ABC chain. These tests are specific to the ABC chain.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
let bchjs let bchjs
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 1 depth: 1
} }
describe(`#SLP`, () => { describe('#SLP', () => {
// before(() => { // before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`) // console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`) // console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
@@ -30,63 +30,63 @@ describe(`#SLP`, () => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#util", () => { describe('#util', () => {
describe("#tokenUtxoDetails", () => { describe('#tokenUtxoDetails', () => {
it("should handle a range of UTXO types", async () => { it('should handle a range of UTXO types', async () => {
const utxos = [ const utxos = [
// Malformed SLP tx // Malformed SLP tx
{ {
note: "Malformed SLP tx", note: 'Malformed SLP tx',
tx_hash: tx_hash:
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Normal TX (non-SLP) // Normal TX (non-SLP)
{ {
note: "Normal TX (non-SLP)", note: 'Normal TX (non-SLP)',
tx_hash: tx_hash:
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
tx_pos: 0, tx_pos: 0,
value: 400000 value: 400000
}, },
// Valid PSF SLP tx // Valid PSF SLP tx
{ {
note: "Valid PSF SLP tx", note: 'Valid PSF SLP tx',
tx_hash: tx_hash:
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
{ {
note: "Valid SLP token not in whitelist", note: 'Valid SLP token not in whitelist',
tx_hash: tx_hash:
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on BCHN network. // Token send on BCHN network.
{ {
note: "Token send on BCHN network", note: 'Token send on BCHN network',
tx_hash: tx_hash:
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on ABC network. // Token send on ABC network.
{ {
note: "Token send on ABC network", note: 'Token send on ABC network',
tx_hash: tx_hash:
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d", '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Known invalid SLP token send of PSF tokens. // Known invalid SLP token send of PSF tokens.
{ {
note: "Known invalid SLP token send of PSF tokens", note: 'Known invalid SLP token send of PSF tokens',
tx_hash: tx_hash:
"2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74", '2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
} }
@@ -125,52 +125,52 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid3", () => { describe('#validateTxid3', () => {
it("should invalidate a known invalid TXID", async () => { it('should invalidate a known invalid TXID', async () => {
const txid = const txid =
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a" 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, null) assert.equal(result[0].valid, null)
}) })
it("should validate a known valid TXID", async () => { it('should validate a known valid TXID', async () => {
const txid = const txid =
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd" 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, true) assert.equal(result[0].valid, true)
}) })
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Unprocessed SLP TX // Unprocessed SLP TX
// "a0d6406eecfd8634158efa9314ff15b4cbf451938e9dc7b5678c46b41eabc6ed" // Mint baton // "a0d6406eecfd8634158efa9314ff15b4cbf451938e9dc7b5678c46b41eabc6ed" // Mint baton
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019" '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019'
] ]
const result = await bchjs.SLP.Utils.validateTxid3(txids) const result = await bchjs.SLP.Utils.validateTxid3(txids)
@@ -185,21 +185,21 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid", () => { describe('#validateTxid', () => {
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network. // Token send on BCHN network.
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network. // Token send on ABC network.
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d" '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
] ]
const result = await bchjs.SLP.Utils.validateTxid(txids) const result = await bchjs.SLP.Utils.validateTxid(txids)
+15 -15
View File
@@ -5,20 +5,20 @@
TODO TODO
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#rawtransaction", () => { describe('#rawtransaction', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
@@ -29,29 +29,29 @@ describe("#rawtransaction", () => {
below expect error messages returned from the server, but at least test below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently. that the server is responding on those endpoints, and responds consistently.
*/ */
describe("sendRawTransaction", () => { describe('sendRawTransaction', () => {
it("should send a single transaction hex", async () => { it('should send a single transaction hex', async () => {
try { try {
const hex = const hex =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex) await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
it("should send an array of tx hexes", async () => { it('should send an array of tx hexes', async () => {
try { try {
const hexes = [ const hexes = [
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000", '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
] ]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes) const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
@@ -59,8 +59,8 @@ describe("#rawtransaction", () => {
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
}) })
+44 -44
View File
@@ -3,21 +3,21 @@
These tests are specific to the ABC chain. These tests are specific to the ABC chain.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
let bchjs let bchjs
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 1 depth: 1
} }
describe(`#SLP`, () => { describe('#SLP', () => {
// before(() => { // before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`) // console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`) // console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
@@ -30,63 +30,63 @@ describe(`#SLP`, () => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#util", () => { describe('#util', () => {
describe("#tokenUtxoDetails", () => { describe('#tokenUtxoDetails', () => {
it("should handle a range of UTXO types", async () => { it('should handle a range of UTXO types', async () => {
const utxos = [ const utxos = [
// Malformed SLP tx // Malformed SLP tx
{ {
note: "Malformed SLP tx", note: 'Malformed SLP tx',
tx_hash: tx_hash:
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Normal TX (non-SLP) // Normal TX (non-SLP)
{ {
note: "Normal TX (non-SLP)", note: 'Normal TX (non-SLP)',
tx_hash: tx_hash:
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
tx_pos: 0, tx_pos: 0,
value: 400000 value: 400000
}, },
// Valid PSF SLP tx // Valid PSF SLP tx
{ {
note: "Valid PSF SLP tx", note: 'Valid PSF SLP tx',
tx_hash: tx_hash:
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
{ {
note: "Valid SLP token not in whitelist", note: 'Valid SLP token not in whitelist',
tx_hash: tx_hash:
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on BCHN network. // Token send on BCHN network.
{ {
note: "Token send on BCHN network", note: 'Token send on BCHN network',
tx_hash: tx_hash:
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on ABC network. // Token send on ABC network.
{ {
note: "Token send on ABC network", note: 'Token send on ABC network',
tx_hash: tx_hash:
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d", '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Known invalid SLP token send of PSF tokens. // Known invalid SLP token send of PSF tokens.
{ {
note: "Known invalid SLP token send of PSF tokens", note: 'Known invalid SLP token send of PSF tokens',
tx_hash: tx_hash:
"2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74", '2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
} }
@@ -125,51 +125,51 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid3", () => { describe('#validateTxid3', () => {
it("should invalidate a known invalid TXID", async () => { it('should invalidate a known invalid TXID', async () => {
const txid = const txid =
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a" 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, null) assert.equal(result[0].valid, null)
}) })
it("should validate a known valid TXID", async () => { it('should validate a known valid TXID', async () => {
const txid = const txid =
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd" 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, true) assert.equal(result[0].valid, true)
}) })
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Unprocessed SLP TX // Unprocessed SLP TX
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019" '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019'
] ]
const result = await bchjs.SLP.Utils.validateTxid3(txids) const result = await bchjs.SLP.Utils.validateTxid3(txids)
@@ -196,21 +196,21 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid", () => { describe('#validateTxid', () => {
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network. // Token send on BCHN network.
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network. // Token send on ABC network.
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d" '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
] ]
const result = await bchjs.SLP.Utils.validateTxid(txids) const result = await bchjs.SLP.Utils.validateTxid(txids)
+71 -71
View File
@@ -7,116 +7,116 @@
of an e2e test to be properly tested. of an e2e test to be properly tested.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: "https://testnet3.fullstack.cash/v4/" : 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL // if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` }) // const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#blockchain", () => { describe('#blockchain', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#getBestBlockHash", () => { describe('#getBestBlockHash', () => {
it("should GET best block hash", async () => { it('should GET best block hash', async () => {
const result = await bchjs.Blockchain.getBestBlockHash() const result = await bchjs.Blockchain.getBestBlockHash()
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.isString(result) assert.isString(result)
assert.equal(result.length, 64, "Specific hash length") assert.equal(result.length, 64, 'Specific hash length')
}) })
}) })
describe("#getBlockHeader", () => { describe('#getBlockHeader', () => {
it("should GET block header for a single hash", async () => { it('should GET block header for a single hash', async () => {
const hash = const hash =
"000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf" '000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf'
const result = await bchjs.Blockchain.getBlockHeader(hash) const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"hash", 'hash',
"confirmations", 'confirmations',
"height", 'height',
"version", 'version',
"versionHex", 'versionHex',
"merkleroot", 'merkleroot',
"time", 'time',
"mediantime", 'mediantime',
"nonce", 'nonce',
"bits", 'bits',
"difficulty", 'difficulty',
"chainwork", 'chainwork',
"previousblockhash", 'previousblockhash',
"nextblockhash", 'nextblockhash',
"nTx" 'nTx'
]) ])
}) })
it("should GET block headers for an array of hashes", async () => { it('should GET block headers for an array of hashes', async () => {
const hash = [ const hash = [
"000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf", '000000000000c57178ace90210289e6b5383134c5b5306e1cdd8395176e10aaf',
"00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2" '00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2'
] ]
const result = await bchjs.Blockchain.getBlockHeader(hash) const result = await bchjs.Blockchain.getBlockHeader(hash)
assert.isArray(result) assert.isArray(result)
assert.hasAllKeys(result[0], [ assert.hasAllKeys(result[0], [
"hash", 'hash',
"confirmations", 'confirmations',
"height", 'height',
"version", 'version',
"versionHex", 'versionHex',
"merkleroot", 'merkleroot',
"time", 'time',
"mediantime", 'mediantime',
"nonce", 'nonce',
"bits", 'bits',
"difficulty", 'difficulty',
"chainwork", 'chainwork',
"previousblockhash", 'previousblockhash',
"nextblockhash", 'nextblockhash',
"nTx" 'nTx'
]) ])
}) })
it("should throw error on array size rate limit", async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
data.push( data.push(
"00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2" '00000000000b7db4cbae48d852fcbef32f728014582094ad613fe12af6600ff2'
) )
} }
await bchjs.Blockchain.getBlockHeader(data) await bchjs.Blockchain.getBlockHeader(data)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#getMempoolEntry", () => { describe('#getMempoolEntry', () => {
/* /*
// To run this test, the txid must be unconfirmed. // To run this test, the txid must be unconfirmed.
const txid = const txid =
@@ -168,26 +168,26 @@ describe("#blockchain", () => {
}) })
*/ */
it("should throw an error if txid is not in mempool", async () => { it('should throw an error if txid is not in mempool', async () => {
try { try {
const txid = const txid =
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
await bchjs.Blockchain.getMempoolEntry(txid) await bchjs.Blockchain.getMempoolEntry(txid)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Transaction not in mempool") assert.include(err.error, 'Transaction not in mempool')
} }
}) })
}) })
describe("#getTxOutProof", () => { describe('#getTxOutProof', () => {
it("should get single tx out proof", async () => { it('should get single tx out proof', async () => {
const txid = const txid =
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const result = await bchjs.Blockchain.getTxOutProof(txid) const result = await bchjs.Blockchain.getTxOutProof(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -195,10 +195,10 @@ describe("#blockchain", () => {
assert.isString(result) assert.isString(result)
}) })
it("should get an array of tx out proofs", async () => { it('should get an array of tx out proofs', async () => {
const txid = [ const txid = [
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04", '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752" 'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
] ]
const result = await bchjs.Blockchain.getTxOutProof(txid) const result = await bchjs.Blockchain.getTxOutProof(txid)
@@ -209,11 +209,11 @@ describe("#blockchain", () => {
}) })
}) })
describe("#verifyTxOutProof", () => { describe('#verifyTxOutProof', () => {
const mockTxOutProof = const mockTxOutProof =
"00000020ac86ce8f2bda235c0dc135d18f6a777c44b121e8f41db8a51ca65000000000000cd4de3c49337712f3a1092c47c3bf73ec2f9b1cfd289ee991ede0b6eab4df229d5b8c5dffff001d82ce005b0700000003ec55d9142eac2c1d2229e5af24898b2590c111b62e2787fa1998d3d713fd432fd557124ed758fa156a6cdc6d317d5575aec2b86dfb159c62ecb4743f28bef1cb52e7a32fbec31e367ec152fdb952f75ee75bd8575f97b394093dbb0e6c694ffc0135" '00000020ac86ce8f2bda235c0dc135d18f6a777c44b121e8f41db8a51ca65000000000000cd4de3c49337712f3a1092c47c3bf73ec2f9b1cfd289ee991ede0b6eab4df229d5b8c5dffff001d82ce005b0700000003ec55d9142eac2c1d2229e5af24898b2590c111b62e2787fa1998d3d713fd432fd557124ed758fa156a6cdc6d317d5575aec2b86dfb159c62ecb4743f28bef1cb52e7a32fbec31e367ec152fdb952f75ee75bd8575f97b394093dbb0e6c694ffc0135'
it("should verify a single proof", async () => { it('should verify a single proof', async () => {
const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof) const result = await bchjs.Blockchain.verifyTxOutProof(mockTxOutProof)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -221,11 +221,11 @@ describe("#blockchain", () => {
assert.isString(result[0]) assert.isString(result[0])
assert.equal( assert.equal(
result[0], result[0],
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752" 'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
) )
}) })
it("should verify an array of proofs", async () => { it('should verify an array of proofs', async () => {
const proofs = [mockTxOutProof, mockTxOutProof] const proofs = [mockTxOutProof, mockTxOutProof]
const result = await bchjs.Blockchain.verifyTxOutProof(proofs) const result = await bchjs.Blockchain.verifyTxOutProof(proofs)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -234,11 +234,11 @@ describe("#blockchain", () => {
assert.isString(result[0]) assert.isString(result[0])
assert.equal( assert.equal(
result[0], result[0],
"fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752" 'fc4f696c0ebb3d0994b3975f57d85be75ef752b9fd52c17e361ec3be2fa3e752'
) )
}) })
it("should throw error on array size rate limit", async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(mockTxOutProof) for (let i = 0; i < 25; i++) data.push(mockTxOutProof)
@@ -246,10 +246,10 @@ describe("#blockchain", () => {
const result = await bchjs.Blockchain.verifyTxOutProof(data) const result = await bchjs.Blockchain.verifyTxOutProof(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
+7 -7
View File
@@ -2,27 +2,27 @@
Integration tests for bchjs control library. Integration tests for bchjs control library.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: `https://testnet3.fullstack.cash/v4/` : 'https://testnet3.fullstack.cash/v4/'
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
describe(`#control`, () => { describe('#control', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#getNetworkInfo`, () => { describe('#getNetworkInfo', () => {
it("should get info on the full node", async () => { it('should get info on the full node', async () => {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
console.log(`result: ${JSON.stringify(result, null, 2)}`) console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "version") assert.property(result, 'version')
}) })
}) })
}) })
+117 -121
View File
@@ -1,15 +1,15 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const sinon = require("sinon") const sinon = require('sinon')
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: `https://testnet3.fullstack.cash/v4/` : 'https://testnet3.fullstack.cash/v4/'
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
describe(`#ElectrumX`, () => { describe('#ElectrumX', () => {
let sandbox let sandbox
beforeEach(async () => { beforeEach(async () => {
@@ -20,176 +20,173 @@ describe(`#ElectrumX`, () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "height") assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], "tx_hash") assert.property(result.utxos[0], 'tx_hash')
assert.property(result.utxos[0], "tx_pos") assert.property(result.utxos[0], 'tx_pos')
assert.property(result.utxos[0], "value") assert.property(result.utxos[0], 'value')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
const addr = [ const addr = [
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2", 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
] ]
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "utxos") assert.property(result.utxos[0], 'utxos')
assert.isArray(result.utxos[0].utxos) assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], "address") assert.property(result.utxos[0], 'address')
assert.property(result.utxos[0].utxos[0], "height") assert.property(result.utxos[0].utxos[0], 'height')
assert.property(result.utxos[0].utxos[0], "tx_hash") assert.property(result.utxos[0].utxos[0], 'tx_hash')
assert.property(result.utxos[0].utxos[0], "tx_pos") assert.property(result.utxos[0].utxos[0], 'tx_pos')
assert.property(result.utxos[0].utxos[0], "value") assert.property(result.utxos[0].utxos[0], 'value')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#balance`, () => { describe('#balance', () => {
it(`should GET balance for a single address`, async () => { it('should GET balance for a single address', async () => {
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balance") assert.property(result, 'balance')
assert.property(result.balance, "confirmed") assert.property(result.balance, 'confirmed')
assert.property(result.balance, "unconfirmed") assert.property(result.balance, 'unconfirmed')
}) })
it(`should POST request for balances for an array of addresses`, async () => { it('should POST request for balances for an array of addresses', async () => {
const addr = [ const addr = [
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2", 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
] ]
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balances") assert.property(result, 'balances')
assert.isArray(result.balances) assert.isArray(result.balances)
assert.property(result.balances[0], "address") assert.property(result.balances[0], 'address')
assert.property(result.balances[0], "balance") assert.property(result.balances[0], 'balance')
assert.property(result.balances[0].balance, "confirmed") assert.property(result.balances[0].balance, 'confirmed')
assert.property(result.balances[0].balance, "unconfirmed") assert.property(result.balances[0].balance, 'unconfirmed')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should GET transaction history for a single address`, async () => { it('should GET transaction history for a single address', async () => {
const addr = "bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" const addr = 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "height") assert.property(result.transactions[0], 'height')
assert.property(result.transactions[0], "tx_hash") assert.property(result.transactions[0], 'tx_hash')
}) })
it(`should POST request for transaction history for an array of addresses`, async () => { it('should POST request for transaction history for an array of addresses', async () => {
const addr = [ const addr = [
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2", 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2',
"bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2" 'bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2'
] ]
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "address") assert.property(result.transactions[0], 'address')
assert.property(result.transactions[0], "transactions") assert.property(result.transactions[0], 'transactions')
assert.isArray(result.transactions[0].transactions) assert.isArray(result.transactions[0].transactions)
assert.property(result.transactions[0].transactions[0], "height") assert.property(result.transactions[0].transactions[0], 'height')
assert.property(result.transactions[0].transactions[0], "tx_hash") assert.property(result.transactions[0].transactions[0], 'tx_hash')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#unconfirmed`, () => { describe('#unconfirmed', () => {
// These tests won't work because unconfirmed transactions are transient in nature. // These tests won't work because unconfirmed transactions are transient in nature.
/* /*
it(`should GET unconfirmed UTXOs (mempool) for a single address`, async () => { it(`should GET unconfirmed UTXOs (mempool) for a single address`, async () => {
@@ -234,131 +231,130 @@ describe(`#ElectrumX`, () => {
}) })
*/ */
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2') }
addr.push("bchtest:qrvn2n228aa39xupcw9jw0d3fj8axxky656e4j62z2")
await bchjs.Electrumx.unconfirmed(addr) await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#blockHeader`, () => { describe('#blockHeader', () => {
it(`should GET block headers for given height and count`, async () => { it('should GET block headers for given height and count', async () => {
const height = 42 const height = 42
const count = 2 const count = 2
const result = await bchjs.Electrumx.blockHeader(height, count) const result = await bchjs.Electrumx.blockHeader(height, count)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "headers") assert.property(result, 'headers')
assert.isArray(result.headers) assert.isArray(result.headers)
assert.equal(result.headers.length, 2) assert.equal(result.headers.length, 2)
}) })
it(`should GET block headers for given height with default count = 1`, async () => { it('should GET block headers for given height with default count = 1', async () => {
const height = 42 const height = 42
const result = await bchjs.Electrumx.blockHeader(height) const result = await bchjs.Electrumx.blockHeader(height)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "headers") assert.property(result, 'headers')
assert.isArray(result.headers) assert.isArray(result.headers)
assert.equal(result.headers.length, 1) assert.equal(result.headers.length, 1)
}) })
}) })
describe(`#txData`, () => { describe('#txData', () => {
it(`should GET details for a single transaction`, async () => { it('should GET details for a single transaction', async () => {
const txid = const txid =
"76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee" '76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
const result = await bchjs.Electrumx.txData(txid) const result = await bchjs.Electrumx.txData(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "details") assert.property(result, 'details')
assert.isObject(result.details) assert.isObject(result.details)
assert.property(result.details, "blockhash") assert.property(result.details, 'blockhash')
assert.property(result.details, "hash") assert.property(result.details, 'hash')
assert.property(result.details, "hex") assert.property(result.details, 'hex')
assert.property(result.details, "vin") assert.property(result.details, 'vin')
assert.property(result.details, "vout") assert.property(result.details, 'vout')
assert.equal(result.details.hash, txid) assert.equal(result.details.hash, txid)
}) })
it(`should POST details for an array of transactions`, async () => { it('should POST details for an array of transactions', async () => {
const txids = [ const txids = [
"76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee", '76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee',
"76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee" '76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
] ]
const result = await bchjs.Electrumx.txData(txids) const result = await bchjs.Electrumx.txData(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "txid") assert.property(result.transactions[0], 'txid')
assert.property(result.transactions[0], "details") assert.property(result.transactions[0], 'details')
assert.property(result.transactions[0].details, "blockhash") assert.property(result.transactions[0].details, 'blockhash')
assert.property(result.transactions[0].details, "hash") assert.property(result.transactions[0].details, 'hash')
assert.property(result.transactions[0].details, "hex") assert.property(result.transactions[0].details, 'hex')
assert.property(result.transactions[0].details, "vin") assert.property(result.transactions[0].details, 'vin')
assert.property(result.transactions[0].details, "vout") assert.property(result.transactions[0].details, 'vout')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const txids = [] const txids = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
txids.push( txids.push(
"76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee" '76d2ee0ebd8b978742f6478ff9a12f478c34e4cee0a2b919059101d961bd01ee'
) )
} }
await bchjs.Electrumx.txData(txids) await bchjs.Electrumx.txData(txids)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#broadcast`, () => { describe('#broadcast', () => {
it(`should broadcast a single transaction`, async () => { it('should broadcast a single transaction', async () => {
const txHex = const txHex =
"020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000" '020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000'
try { try {
await bchjs.Electrumx.broadcast(txHex) await bchjs.Electrumx.broadcast(txHex)
} catch (err) { } catch (err) {
assert.property(err, "success") assert.property(err, 'success')
assert.equal(err.success, false) assert.equal(err.success, false)
assert.include( assert.include(
err.error, err.error,
"the transaction was rejected by network rules" 'the transaction was rejected by network rules'
) )
} }
}) })
+68 -68
View File
@@ -1,11 +1,11 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS({ ninsightURL: "https://trest.bitcoin.com/v2" }) const bchjs = new BCHJS({ ninsightURL: 'https://trest.bitcoin.com/v2' })
describe(`#Ninsight`, () => { describe('#Ninsight', () => {
let sandbox let sandbox
beforeEach(async () => { beforeEach(async () => {
@@ -16,34 +16,34 @@ describe(`#Ninsight`, () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
const addr = "bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr" const addr = 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr'
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
assert.property(result[0], "asm") assert.property(result[0], 'asm')
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0].utxos[0], "txid") assert.property(result[0].utxos[0], 'txid')
assert.property(result[0].utxos[0], "vout") assert.property(result[0].utxos[0], 'vout')
assert.property(result[0].utxos[0], "amount") assert.property(result[0].utxos[0], 'amount')
assert.property(result[0].utxos[0], "satoshis") assert.property(result[0].utxos[0], 'satoshis')
assert.property(result[0].utxos[0], "height") assert.property(result[0].utxos[0], 'height')
assert.property(result[0].utxos[0], "confirmations") assert.property(result[0].utxos[0], 'confirmations')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
const addr = [ const addr = [
"bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr", 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr',
"bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul" 'bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul'
] ]
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
@@ -52,12 +52,12 @@ describe(`#Ninsight`, () => {
assert.isArray(result) assert.isArray(result)
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
assert.property(result[0], "asm") assert.property(result[0], 'asm')
// assert.hasAnyKeys(result[0][0], [ // assert.hasAnyKeys(result[0][0], [
// "txid", // "txid",
@@ -68,76 +68,76 @@ describe(`#Ninsight`, () => {
// ]) // ])
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should POST transactions history for a single address`, async () => { it('should POST transactions history for a single address', async () => {
const addr = "bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr" const addr = 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr'
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], "vin") assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], "vout") assert.property(result[0].txs[0], 'vout')
}) })
it(`should POST transactions history for an array of addresses`, async () => { it('should POST transactions history for an array of addresses', async () => {
const addr = [ const addr = [
"bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr", 'bchtest:qzjtnzcvzxx7s0na88yrg3zl28wwvfp97538sgrrmr',
"bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul" 'bchtest:qp6hgvevf4gzz6l7pgcte3gaaud9km0l459fa23dul'
] ]
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], "vin") assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], "vout") assert.property(result[0].txs[0], 'vout')
}) })
}) })
describe(`#txDetails`, () => { describe('#txDetails', () => {
it(`should POST transactions details for a single address`, async () => { it('should POST transactions details for a single address', async () => {
const txid = const txid =
"76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea" '76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea'
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "version") assert.property(result[0], 'version')
assert.property(result[0], "locktime") assert.property(result[0], 'locktime')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
assert.property(result[0], "blockhash") assert.property(result[0], 'blockhash')
assert.property(result[0], "blockheight") assert.property(result[0], 'blockheight')
assert.property(result[0], "confirmations") assert.property(result[0], 'confirmations')
assert.property(result[0], "time") assert.property(result[0], 'time')
assert.property(result[0], "blocktime") assert.property(result[0], 'blocktime')
assert.property(result[0], "valueOut") assert.property(result[0], 'valueOut')
assert.property(result[0], "size") assert.property(result[0], 'size')
}) })
it(`should POST transactions details for an array of addresses`, async () => { it('should POST transactions details for an array of addresses', async () => {
const txid = [ const txid = [
"f191d1062789d7071da6f2168ba306869a829294f6b1c09d03492db4ca3a8e77", 'f191d1062789d7071da6f2168ba306869a829294f6b1c09d03492db4ca3a8e77',
"76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea" '76856d82e00b2696acd8d989e1fa6c46b431005046a285ce905814cac0ff8fea'
] ]
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
}) })
}) })
}) })
@@ -5,56 +5,56 @@
TODO TODO
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: `https://testnet3.fullstack.cash/v4/` : 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL // if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` }) // const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#rawtransaction", () => { describe('#rawtransaction', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#decodeRawTransaction", () => { describe('#decodeRawTransaction', () => {
it("should decode tx for a single hex", async () => { it('should decode tx for a single hex', async () => {
const hex = const hex =
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
const result = await bchjs.RawTransactions.decodeRawTransaction(hex) const result = await bchjs.RawTransactions.decodeRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout" 'vout'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
}) })
it("should decode an array of tx hexes", async () => { it('should decode an array of tx hexes', async () => {
const hexes = [ const hexes = [
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000", '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000',
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
] ]
const result = await bchjs.RawTransactions.decodeRawTransaction(hexes) const result = await bchjs.RawTransactions.decodeRawTransaction(hexes)
@@ -62,42 +62,42 @@ describe("#rawtransaction", () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout" 'vout'
]) ])
assert.isArray(result[0].vin) assert.isArray(result[0].vin)
assert.isArray(result[0].vout) assert.isArray(result[0].vout)
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
data.push( data.push(
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
) )
} }
const result = await bchjs.RawTransactions.decodeRawTransaction(data) const result = await bchjs.RawTransactions.decodeRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#getRawTransaction", () => { describe('#getRawTransaction', () => {
it("should decode a single txid, with concise output", async () => { it('should decode a single txid, with concise output', async () => {
const txid = const txid =
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const verbose = false const verbose = false
const result = await bchjs.RawTransactions.getRawTransaction( const result = await bchjs.RawTransactions.getRawTransaction(
@@ -109,9 +109,9 @@ describe("#rawtransaction", () => {
assert.isString(result) assert.isString(result)
}) })
it("should decode a single txid, with verbose output", async () => { it('should decode a single txid, with verbose output', async () => {
const txid = const txid =
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const verbose = true const verbose = true
const result = await bchjs.RawTransactions.getRawTransaction( const result = await bchjs.RawTransactions.getRawTransaction(
@@ -121,27 +121,27 @@ describe("#rawtransaction", () => {
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"hex", 'hex',
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"confirmations", 'confirmations',
"time", 'time',
"blocktime" 'blocktime'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
}) })
it("should decode an array of txids, with a concise output", async () => { it('should decode an array of txids, with a concise output', async () => {
const txid = [ const txid = [
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04", '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
] ]
const verbose = false const verbose = false
@@ -155,10 +155,10 @@ describe("#rawtransaction", () => {
assert.isString(result[0]) assert.isString(result[0])
}) })
it("should decode an array of txids, with a verbose output", async () => { it('should decode an array of txids, with a verbose output', async () => {
const txid = [ const txid = [
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04", '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04',
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
] ]
const verbose = true const verbose = true
@@ -170,50 +170,50 @@ describe("#rawtransaction", () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"hex", 'hex',
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"confirmations", 'confirmations',
"time", 'time',
"blocktime" 'blocktime'
]) ])
assert.isArray(result[0].vin) assert.isArray(result[0].vin)
assert.isArray(result[0].vout) assert.isArray(result[0].vout)
}) })
it(`should throw error on array size limit`, async () => { it('should throw error on array size limit', async () => {
try { try {
const dataMock = const dataMock =
"1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04" '1f121fb6a33f48cd426dde06aa20ce589dd97becabb835a8d33071cbf40c7d04'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.getRawTransaction(data) const result = await bchjs.RawTransactions.getRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#decodeScript", () => { describe('#decodeScript', () => {
it("should decode script for a single hex", async () => { it('should decode script for a single hex', async () => {
const hex = const hex =
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16" '4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16'
const result = await bchjs.RawTransactions.decodeScript(hex) const result = await bchjs.RawTransactions.decodeScript(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["asm", "type", "p2sh"]) assert.hasAllKeys(result, ['asm', 'type', 'p2sh'])
}) })
// CT 2/20/19 - Waiting for this PR to be merged complete the test: // CT 2/20/19 - Waiting for this PR to be merged complete the test:
@@ -237,29 +237,29 @@ describe("#rawtransaction", () => {
below expect error messages returned from the server, but at least test below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently. that the server is responding on those endpoints, and responds consistently.
*/ */
describe("sendRawTransaction", () => { describe('sendRawTransaction', () => {
it("should send a single transaction hex", async () => { it('should send a single transaction hex', async () => {
try { try {
const hex = const hex =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex) await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
it("should send an array of tx hexes", async () => { it('should send an array of tx hexes', async () => {
try { try {
const hexes = [ const hexes = [
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000", '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
] ]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes) const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
@@ -267,25 +267,25 @@ describe("#rawtransaction", () => {
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const dataMock = const dataMock =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.sendRawTransaction(data) const result = await bchjs.RawTransactions.sendRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
+61 -61
View File
@@ -2,110 +2,110 @@
Integration tests for the bchjs covering SLP tokens. Integration tests for the bchjs covering SLP tokens.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: `https://testnet3.fullstack.cash/v4/` : 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL // if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` }) // const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 1 depth: 1
} }
describe(`#SLP`, () => { describe('#SLP', () => {
beforeEach(async () => { beforeEach(async () => {
// Introduce a delay so that the BVT doesn't trip the rate limits. // Introduce a delay so that the BVT doesn't trip the rate limits.
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#util", () => { describe('#util', () => {
it(`should get information on the Oasis token`, async () => { it('should get information on the Oasis token', async () => {
const tokenId = `a371e9934c7695d08a5eb7f31d3bceb4f3644860cc67520cda1e149423b9ec39` const tokenId = 'a371e9934c7695d08a5eb7f31d3bceb4f3644860cc67520cda1e149423b9ec39'
const result = await bchjs.SLP.Utils.list(tokenId) const result = await bchjs.SLP.Utils.list(tokenId)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"decimals", 'decimals',
"timestamp", 'timestamp',
"timestamp_unix", 'timestamp_unix',
"versionType", 'versionType',
"documentUri", 'documentUri',
"symbol", 'symbol',
"name", 'name',
"containsBaton", 'containsBaton',
"id", 'id',
"documentHash", 'documentHash',
"initialTokenQty", 'initialTokenQty',
"blockCreated", 'blockCreated',
"blockLastActiveSend", 'blockLastActiveSend',
"blockLastActiveMint", 'blockLastActiveMint',
"txnsSinceGenesis", 'txnsSinceGenesis',
"validAddress", 'validAddress',
"totalMinted", 'totalMinted',
"totalBurned", 'totalBurned',
"circulatingSupply", 'circulatingSupply',
"mintingBatonStatus" 'mintingBatonStatus'
]) ])
}) })
}) })
describe("#decodeOpReturn", () => { describe('#decodeOpReturn', () => {
it("should decode the OP_RETURN for a SEND txid", async () => { it('should decode the OP_RETURN for a SEND txid', async () => {
const txid = const txid =
"ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1" 'ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1'
const result = await bchjs.SLP.Utils.decodeOpReturn(txid) const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["amounts", "tokenType", "tokenId", "txType"]) assert.hasAllKeys(result, ['amounts', 'tokenType', 'tokenId', 'txType'])
}) })
}) })
describe("#balancesForAddress", () => { describe('#balancesForAddress', () => {
it(`should fetch all balances for address: slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9`, async () => { it('should fetch all balances for address: slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9', async () => {
// Mock the call to rest.bitcoin.com // Mock the call to rest.bitcoin.com
if (process.env.TEST === "unit") { if (process.env.TEST === 'unit') {
sandbox sandbox
.stub(axios, "get") .stub(axios, 'get')
.resolves({ data: mockData.balancesForAddress }) .resolves({ data: mockData.balancesForAddress })
} }
const balances = await bchjs.SLP.Utils.balancesForAddress( const balances = await bchjs.SLP.Utils.balancesForAddress(
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9" 'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
) )
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`) // console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
assert.isArray(balances) assert.isArray(balances)
assert.hasAllKeys(balances[0], [ assert.hasAllKeys(balances[0], [
"tokenId", 'tokenId',
"balanceString", 'balanceString',
"balance", 'balance',
"decimalCount", 'decimalCount',
"slpAddress" 'slpAddress'
]) ])
}) })
it(`should fetch balances for multiple addresses`, async () => { it('should fetch balances for multiple addresses', async () => {
const addresses = [ const addresses = [
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9", 'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9',
"slptest:qr5uy4h8ysyhwkp9s245scckdnc7teyjqc5ft2z43h" 'slptest:qr5uy4h8ysyhwkp9s245scckdnc7teyjqc5ft2z43h'
] ]
// Mock the call to rest.bitcoin.com // Mock the call to rest.bitcoin.com
if (process.env.TEST === "unit") { if (process.env.TEST === 'unit') {
sandbox sandbox
.stub(axios, "post") .stub(axios, 'post')
.resolves({ data: mockData.balancesForAddresses }) .resolves({ data: mockData.balancesForAddresses })
} }
@@ -115,19 +115,19 @@ describe(`#SLP`, () => {
assert.isArray(balances) assert.isArray(balances)
assert.isArray(balances[0]) assert.isArray(balances[0])
assert.hasAllKeys(balances[0][0], [ assert.hasAllKeys(balances[0][0], [
"tokenId", 'tokenId',
"balanceString", 'balanceString',
"balance", 'balance',
"decimalCount", 'decimalCount',
"slpAddress" 'slpAddress'
]) ])
}) })
}) })
describe("#tokenUtxoDetails", () => { describe('#tokenUtxoDetails', () => {
it("should hydrate UTXOs", async () => { it('should hydrate UTXOs', async () => {
const bchAddr = bchjs.SLP.Address.toCashAddress( const bchAddr = bchjs.SLP.Address.toCashAddress(
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9" 'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
) )
const utxos = await bchjs.Electrumx.utxo([bchAddr]) const utxos = await bchjs.Electrumx.utxo([bchAddr])
@@ -145,12 +145,12 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#hydrateUtxos", () => { describe('#hydrateUtxos', () => {
// This test will error out if the LOCAL_RESTURL settings is not set properly // This test will error out if the LOCAL_RESTURL settings is not set properly
// in bch-api. // in bch-api.
it("should hydrate UTXOs", async () => { it('should hydrate UTXOs', async () => {
const bchAddr = bchjs.SLP.Address.toCashAddress( const bchAddr = bchjs.SLP.Address.toCashAddress(
"slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9" 'slptest:qz0kc67pm4emjyr3gaaa2wstdaykg9m4yqwlzpj3w9'
) )
const utxos = await bchjs.Electrumx.utxo([bchAddr]) const utxos = await bchjs.Electrumx.utxo([bchAddr])
@@ -166,10 +166,10 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid2", () => { describe('#validateTxid2', () => {
it("should validate a token txid", async () => { it('should validate a token txid', async () => {
const txid = const txid =
"ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1" 'ad28116e0818339342dddfc5f58ca8a5379ceb9679b4e4cbd72f4de905415ec1'
const validated = await bchjs.SLP.Utils.validateTxid(txid) const validated = await bchjs.SLP.Utils.validateTxid(txid)
// console.log(validated) // console.log(validated)
+30 -30
View File
@@ -3,73 +3,73 @@
rest.bitcoin.com. rest.bitcoin.com.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const RESTURL = process.env.RESTURL const RESTURL = process.env.RESTURL
? process.env.RESTURL ? process.env.RESTURL
: `https://testnet3.fullstack.cash/v4/` : 'https://testnet3.fullstack.cash/v4/'
// if (process.env.RESTURL) RESTURL = process.env.RESTURL // if (process.env.RESTURL) RESTURL = process.env.RESTURL
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
// const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` }) // const bchjs = new BCHJS({ restURL: `https://testnet.bchjs.cash/v4/` })
const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN }) const bchjs = new BCHJS({ restURL: RESTURL, apiToken: process.env.BCHJSTOKEN })
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe(`#util`, () => { describe('#util', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#validateAddress`, () => { describe('#validateAddress', () => {
it(`should return false for testnet addr on mainnet`, async () => { it('should return false for testnet addr on mainnet', async () => {
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peu` const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peu'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["isvalid"]) assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false) assert.equal(result.isvalid, false)
}) })
it(`should return false for bad address`, async () => { it('should return false for bad address', async () => {
const address = `bchtest:qqqk4y6lsl5da64sg53xezmplyu5kmpyz2ysaa5y` const address = 'bchtest:qqqk4y6lsl5da64sg53xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["isvalid"]) assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false) assert.equal(result.isvalid, false)
}) })
it(`should validate valid address`, async () => { it('should validate valid address', async () => {
const address = `bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y` const address = 'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"isvalid", 'isvalid',
"address", 'address',
"scriptPubKey", 'scriptPubKey',
// "ismine", // "ismine",
// "iswatchonly", // "iswatchonly",
"isscript" 'isscript'
]) ])
assert.equal(result.isvalid, true) assert.equal(result.isvalid, true)
}) })
it(`should validate an array of addresses`, async () => { it('should validate an array of addresses', async () => {
const address = [ const address = [
`bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y`, 'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y',
`bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh` 'bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh'
] ]
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
@@ -77,28 +77,28 @@ describe(`#util`, () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"isvalid", 'isvalid',
"address", 'address',
"scriptPubKey", 'scriptPubKey',
// "ismine", // "ismine",
// "iswatchonly", // "iswatchonly",
"isscript" 'isscript'
]) ])
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const dataMock = `bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh` const dataMock = 'bchtest:pq6k9969f6v6sg7a75jkru4n7wn9sknv5cztcp0dnh'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.Util.validateAddress(data) const result = await bchjs.Util.validateAddress(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
+6 -6
View File
@@ -2,22 +2,22 @@
Integration tests for bchjs control library. Integration tests for bchjs control library.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe(`#control`, () => { describe('#control', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#getNetworkInfo`, () => { describe('#getNetworkInfo', () => {
it("should get info on the full node", async () => { it('should get info on the full node', async () => {
const result = await bchjs.Control.getNetworkInfo() const result = await bchjs.Control.getNetworkInfo()
console.log(`result: ${JSON.stringify(result, null, 2)}`) console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "version") assert.property(result, 'version')
}) })
}) })
}) })
+116 -120
View File
@@ -1,11 +1,11 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe(`#ElectrumX`, () => { describe('#ElectrumX', () => {
let sandbox let sandbox
beforeEach(async () => { beforeEach(async () => {
@@ -16,176 +16,173 @@ describe(`#ElectrumX`, () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "height") assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], "tx_hash") assert.property(result.utxos[0], 'tx_hash')
assert.property(result.utxos[0], "tx_pos") assert.property(result.utxos[0], 'tx_pos')
assert.property(result.utxos[0], "value") assert.property(result.utxos[0], 'value')
}) })
it(`should POST request for UTXOs for an array of addresses`, async () => { it('should POST request for UTXOs for an array of addresses', async () => {
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "utxos") assert.property(result.utxos[0], 'utxos')
assert.isArray(result.utxos[0].utxos) assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], "address") assert.property(result.utxos[0], 'address')
assert.property(result.utxos[0].utxos[0], "height") assert.property(result.utxos[0].utxos[0], 'height')
assert.property(result.utxos[0].utxos[0], "tx_hash") assert.property(result.utxos[0].utxos[0], 'tx_hash')
assert.property(result.utxos[0].utxos[0], "tx_pos") assert.property(result.utxos[0].utxos[0], 'tx_pos')
assert.property(result.utxos[0].utxos[0], "value") assert.property(result.utxos[0].utxos[0], 'value')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf') }
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#balance`, () => { describe('#balance', () => {
it(`should GET balance for a single address`, async () => { it('should GET balance for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balance") assert.property(result, 'balance')
assert.property(result.balance, "confirmed") assert.property(result.balance, 'confirmed')
assert.property(result.balance, "unconfirmed") assert.property(result.balance, 'unconfirmed')
}) })
it(`should POST request for balances for an array of addresses`, async () => { it('should POST request for balances for an array of addresses', async () => {
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balances") assert.property(result, 'balances')
assert.isArray(result.balances) assert.isArray(result.balances)
assert.property(result.balances[0], "address") assert.property(result.balances[0], 'address')
assert.property(result.balances[0], "balance") assert.property(result.balances[0], 'balance')
assert.property(result.balances[0].balance, "confirmed") assert.property(result.balances[0].balance, 'confirmed')
assert.property(result.balances[0].balance, "unconfirmed") assert.property(result.balances[0].balance, 'unconfirmed')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf') }
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should GET transaction history for a single address`, async () => { it('should GET transaction history for a single address', async () => {
const addr = "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" const addr = 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "height") assert.property(result.transactions[0], 'height')
assert.property(result.transactions[0], "tx_hash") assert.property(result.transactions[0], 'tx_hash')
}) })
it(`should POST request for transaction history for an array of addresses`, async () => { it('should POST request for transaction history for an array of addresses', async () => {
const addr = [ const addr = [
"bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj", 'bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "address") assert.property(result.transactions[0], 'address')
assert.property(result.transactions[0], "transactions") assert.property(result.transactions[0], 'transactions')
assert.isArray(result.transactions[0].transactions) assert.isArray(result.transactions[0].transactions)
assert.property(result.transactions[0].transactions[0], "height") assert.property(result.transactions[0].transactions[0], 'height')
assert.property(result.transactions[0].transactions[0], "tx_hash") assert.property(result.transactions[0].transactions[0], 'tx_hash')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0') }
addr.push("bitcoincash:qrehqueqhw629p6e57994436w730t4rzasnly00ht0")
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#unconfirmed`, () => { describe('#unconfirmed', () => {
// These tests won't work because unconfirmed transactions are transient in nature. // These tests won't work because unconfirmed transactions are transient in nature.
/* /*
it(`should GET unconfirmed UTXOs (mempool) for a single address`, async () => { it(`should GET unconfirmed UTXOs (mempool) for a single address`, async () => {
@@ -230,131 +227,130 @@ describe(`#ElectrumX`, () => {
}) })
*/ */
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const addr = [] const addr = []
for (let i = 0; i < 25; i++) for (let i = 0; i < 25; i++) { addr.push('bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf') }
addr.push("bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf")
await bchjs.Electrumx.unconfirmed(addr) await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#blockHeader`, () => { describe('#blockHeader', () => {
it(`should GET block headers for given height and count`, async () => { it('should GET block headers for given height and count', async () => {
const height = 42 const height = 42
const count = 2 const count = 2
const result = await bchjs.Electrumx.blockHeader(height, count) const result = await bchjs.Electrumx.blockHeader(height, count)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "headers") assert.property(result, 'headers')
assert.isArray(result.headers) assert.isArray(result.headers)
assert.equal(result.headers.length, 2) assert.equal(result.headers.length, 2)
}) })
it(`should GET block headers for given height with default count = 1`, async () => { it('should GET block headers for given height with default count = 1', async () => {
const height = 42 const height = 42
const result = await bchjs.Electrumx.blockHeader(height) const result = await bchjs.Electrumx.blockHeader(height)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "headers") assert.property(result, 'headers')
assert.isArray(result.headers) assert.isArray(result.headers)
assert.equal(result.headers.length, 1) assert.equal(result.headers.length, 1)
}) })
}) })
describe(`#txData`, () => { describe('#txData', () => {
it(`should GET details for a single transaction`, async () => { it('should GET details for a single transaction', async () => {
const txid = const txid =
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
const result = await bchjs.Electrumx.txData(txid) const result = await bchjs.Electrumx.txData(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "details") assert.property(result, 'details')
assert.isObject(result.details) assert.isObject(result.details)
assert.property(result.details, "blockhash") assert.property(result.details, 'blockhash')
assert.property(result.details, "hash") assert.property(result.details, 'hash')
assert.property(result.details, "hex") assert.property(result.details, 'hex')
assert.property(result.details, "vin") assert.property(result.details, 'vin')
assert.property(result.details, "vout") assert.property(result.details, 'vout')
assert.equal(result.details.hash, txid) assert.equal(result.details.hash, txid)
}) })
it(`should POST details for an array of transactions`, async () => { it('should POST details for an array of transactions', async () => {
const txids = [ const txids = [
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251", '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251',
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
] ]
const result = await bchjs.Electrumx.txData(txids) const result = await bchjs.Electrumx.txData(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "txid") assert.property(result.transactions[0], 'txid')
assert.property(result.transactions[0], "details") assert.property(result.transactions[0], 'details')
assert.property(result.transactions[0].details, "blockhash") assert.property(result.transactions[0].details, 'blockhash')
assert.property(result.transactions[0].details, "hash") assert.property(result.transactions[0].details, 'hash')
assert.property(result.transactions[0].details, "hex") assert.property(result.transactions[0].details, 'hex')
assert.property(result.transactions[0].details, "vin") assert.property(result.transactions[0].details, 'vin')
assert.property(result.transactions[0].details, "vout") assert.property(result.transactions[0].details, 'vout')
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const txids = [] const txids = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
txids.push( txids.push(
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
) )
} }
await bchjs.Electrumx.txData(txids) await bchjs.Electrumx.txData(txids)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe(`#broadcast`, () => { describe('#broadcast', () => {
it(`should broadcast a single transaction`, async () => { it('should broadcast a single transaction', async () => {
const txHex = const txHex =
"020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000" '020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000'
try { try {
await bchjs.Electrumx.broadcast(txHex) await bchjs.Electrumx.broadcast(txHex)
} catch (err) { } catch (err) {
assert.property(err, "success") assert.property(err, 'success')
assert.equal(err.success, false) assert.equal(err.success, false)
assert.include( assert.include(
err.error, err.error,
"the transaction was rejected by network rules" 'the transaction was rejected by network rules'
) )
} }
}) })
+13 -13
View File
@@ -1,35 +1,35 @@
const assert = require("chai").assert const assert = require('chai').assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe("#Encryption", () => { describe('#Encryption', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#getPubKey", () => { describe('#getPubKey', () => {
it("should get a public key", async () => { it('should get a public key', async () => {
const addr = "bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq" const addr = 'bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq'
const result = await bchjs.encryption.getPubKey(addr) const result = await bchjs.encryption.getPubKey(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "publicKey") assert.property(result, 'publicKey')
}) })
it("should report when public key can not be found", async () => { it('should report when public key can not be found', async () => {
const addr = "bitcoincash:qrgqqkky28jdkv3w0ctrah0mz3jcsnsklc34gtukrh" const addr = 'bitcoincash:qrgqqkky28jdkv3w0ctrah0mz3jcsnsklc34gtukrh'
const result = await bchjs.encryption.getPubKey(addr) const result = await bchjs.encryption.getPubKey(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, false) assert.equal(result.success, false)
assert.property(result, "publicKey") assert.property(result, 'publicKey')
assert.equal(result.publicKey, "not found") assert.equal(result.publicKey, 'not found')
}) })
}) })
}) })
@@ -5,20 +5,20 @@
TODO TODO
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#rawtransaction", () => { describe('#rawtransaction', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
@@ -29,29 +29,29 @@ describe("#rawtransaction", () => {
below expect error messages returned from the server, but at least test below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently. that the server is responding on those endpoints, and responds consistently.
*/ */
describe("sendRawTransaction", () => { describe('sendRawTransaction', () => {
it("should send a single transaction hex", async () => { it('should send a single transaction hex', async () => {
try { try {
const hex = const hex =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
await bchjs.RawTransactions.sendRawTransaction(hex) await bchjs.RawTransactions.sendRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
it("should send an array of tx hexes", async () => { it('should send an array of tx hexes', async () => {
try { try {
const hexes = [ const hexes = [
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000", '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000',
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
] ]
const result = await bchjs.RawTransactions.sendRawTransaction(hexes) const result = await bchjs.RawTransactions.sendRawTransaction(hexes)
@@ -59,8 +59,8 @@ describe("#rawtransaction", () => {
} catch (err) { } catch (err) {
// console.log(`err: ${util.inspect(err)}`) // console.log(`err: ${util.inspect(err)}`)
assert.hasAllKeys(err, ["error"]) assert.hasAllKeys(err, ['error'])
assert.include(err.error, "Missing inputs") assert.include(err.error, 'Missing inputs')
} }
}) })
}) })
+44 -44
View File
@@ -3,21 +3,21 @@
These tests are specific to the ABC chain. These tests are specific to the ABC chain.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../../../src/bch-js") const BCHJS = require('../../../../src/bch-js')
let bchjs let bchjs
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 1 depth: 1
} }
describe(`#SLP`, () => { describe('#SLP', () => {
// before(() => { // before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`) // console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`) // console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
@@ -30,63 +30,63 @@ describe(`#SLP`, () => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#util", () => { describe('#util', () => {
describe("#tokenUtxoDetails", () => { describe('#tokenUtxoDetails', () => {
it("should handle a range of UTXO types", async () => { it('should handle a range of UTXO types', async () => {
const utxos = [ const utxos = [
// Malformed SLP tx // Malformed SLP tx
{ {
note: "Malformed SLP tx", note: 'Malformed SLP tx',
tx_hash: tx_hash:
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Normal TX (non-SLP) // Normal TX (non-SLP)
{ {
note: "Normal TX (non-SLP)", note: 'Normal TX (non-SLP)',
tx_hash: tx_hash:
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
tx_pos: 0, tx_pos: 0,
value: 400000 value: 400000
}, },
// Valid PSF SLP tx // Valid PSF SLP tx
{ {
note: "Valid PSF SLP tx", note: 'Valid PSF SLP tx',
tx_hash: tx_hash:
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
{ {
note: "Valid SLP token not in whitelist", note: 'Valid SLP token not in whitelist',
tx_hash: tx_hash:
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on BCHN network. // Token send on BCHN network.
{ {
note: "Token send on BCHN network", note: 'Token send on BCHN network',
tx_hash: tx_hash:
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Token send on ABC network. // Token send on ABC network.
{ {
note: "Token send on ABC network", note: 'Token send on ABC network',
tx_hash: tx_hash:
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d", '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
// Known invalid SLP token send of PSF tokens. // Known invalid SLP token send of PSF tokens.
{ {
note: "Known invalid SLP token send of PSF tokens", note: 'Known invalid SLP token send of PSF tokens',
tx_hash: tx_hash:
"2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74", '2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
} }
@@ -125,51 +125,51 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid3", () => { describe('#validateTxid3', () => {
it("should invalidate a known invalid TXID", async () => { it('should invalidate a known invalid TXID', async () => {
const txid = const txid =
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a" 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, null) assert.equal(result[0].valid, null)
}) })
it("should validate a known valid TXID", async () => { it('should validate a known valid TXID', async () => {
const txid = const txid =
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd" 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
const result = await bchjs.SLP.Utils.validateTxid3(txid) const result = await bchjs.SLP.Utils.validateTxid3(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.equal(result[0].txid, txid) assert.equal(result[0].txid, txid)
assert.property(result[0], "valid") assert.property(result[0], 'valid')
assert.equal(result[0].valid, true) assert.equal(result[0].valid, true)
}) })
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Unprocessed SLP TX // Unprocessed SLP TX
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019" '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019'
] ]
const result = await bchjs.SLP.Utils.validateTxid3(txids) const result = await bchjs.SLP.Utils.validateTxid3(txids)
@@ -195,21 +195,21 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid", () => { describe('#validateTxid', () => {
it("should handle a mix of valid, invalid, and non-SLP txs", async () => { it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [ const txids = [
// Malformed SLP tx // Malformed SLP tx
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP) // Normal TX (non-SLP)
"01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0", '01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx // Valid PSF SLP tx
"daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd", 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist // Valid SLP token not in whitelist
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network. // Token send on BCHN network.
"402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019", '402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network. // Token send on ABC network.
"336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d" '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
] ]
const result = await bchjs.SLP.Utils.validateTxid(txids) const result = await bchjs.SLP.Utils.validateTxid(txids)
+68 -68
View File
@@ -1,11 +1,11 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS({ ninsightURL: "https://rest.bitcoin.com/v2" }) const bchjs = new BCHJS({ ninsightURL: 'https://rest.bitcoin.com/v2' })
describe(`#Ninsight`, () => { describe('#Ninsight', () => {
let sandbox let sandbox
beforeEach(async () => { beforeEach(async () => {
@@ -16,34 +16,34 @@ describe(`#Ninsight`, () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
assert.property(result[0], "asm") assert.property(result[0], 'asm')
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0].utxos[0], "txid") assert.property(result[0].utxos[0], 'txid')
assert.property(result[0].utxos[0], "vout") assert.property(result[0].utxos[0], 'vout')
assert.property(result[0].utxos[0], "amount") assert.property(result[0].utxos[0], 'amount')
assert.property(result[0].utxos[0], "satoshis") assert.property(result[0].utxos[0], 'satoshis')
assert.property(result[0].utxos[0], "height") assert.property(result[0].utxos[0], 'height')
assert.property(result[0].utxos[0], "confirmations") assert.property(result[0].utxos[0], 'confirmations')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
const addr = [ const addr = [
"bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7", 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr" 'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
] ]
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
@@ -52,83 +52,83 @@ describe(`#Ninsight`, () => {
assert.isArray(result) assert.isArray(result)
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
assert.property(result[0], "asm") assert.property(result[0], 'asm')
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should POST transactions history for a single address`, async () => { it('should POST transactions history for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], "vin") assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], "vout") assert.property(result[0].txs[0], 'vout')
}) })
it(`should POST transactions history for an array of addresses`, async () => { it('should POST transactions history for an array of addresses', async () => {
const addr = [ const addr = [
"bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7", 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr" 'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
] ]
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], "vin") assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], "vout") assert.property(result[0].txs[0], 'vout')
}) })
}) })
describe(`#txDetails`, () => { describe('#txDetails', () => {
it(`should POST transactions details for a single address`, async () => { it('should POST transactions details for a single address', async () => {
const txid = "fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33" const txid = 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "version") assert.property(result[0], 'version')
assert.property(result[0], "locktime") assert.property(result[0], 'locktime')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
assert.property(result[0], "blockhash") assert.property(result[0], 'blockhash')
assert.property(result[0], "blockheight") assert.property(result[0], 'blockheight')
assert.property(result[0], "confirmations") assert.property(result[0], 'confirmations')
assert.property(result[0], "time") assert.property(result[0], 'time')
assert.property(result[0], "blocktime") assert.property(result[0], 'blocktime')
assert.property(result[0], "valueOut") assert.property(result[0], 'valueOut')
assert.property(result[0], "size") assert.property(result[0], 'size')
}) })
it(`should POST transactions details for an array of addresses`, async () => { it('should POST transactions details for an array of addresses', async () => {
const txid = [ const txid = [
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33", 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
] ]
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
}) })
}) })
}) })
+42 -42
View File
@@ -2,81 +2,81 @@
tests for OpenBazaar library. tests for OpenBazaar library.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe(`#OpenBazaar`, () => { describe('#OpenBazaar', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#Balance`, () => { describe('#Balance', () => {
it(`should GET balance for a single address`, async () => { it('should GET balance for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.OpenBazaar.balance(addr) const result = await bchjs.OpenBazaar.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"page", 'page',
"totalPages", 'totalPages',
"itemsOnPage", 'itemsOnPage',
"addrStr", 'addrStr',
"balance", 'balance',
"totalReceived", 'totalReceived',
"totalSent", 'totalSent',
"unconfirmedBalance", 'unconfirmedBalance',
"unconfirmedTxApperances", 'unconfirmedTxApperances',
"txApperances", 'txApperances',
"transactions" 'transactions'
]) ])
assert.isArray(result.transactions) assert.isArray(result.transactions)
}) })
}) })
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.OpenBazaar.utxo(addr) const result = await bchjs.OpenBazaar.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.hasAllKeys(result[0], [ assert.hasAllKeys(result[0], [
"txid", 'txid',
"vout", 'vout',
"amount", 'amount',
"height", 'height',
"confirmations", 'confirmations',
"satoshis" 'satoshis'
]) ])
}) })
}) })
describe(`#tx`, () => { describe('#tx', () => {
it(`should GET transactions for a single address`, async () => { it('should GET transactions for a single address', async () => {
const addr = const addr =
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7" '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
const result = await bchjs.OpenBazaar.tx(addr) const result = await bchjs.OpenBazaar.tx(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"txid", 'txid',
"version", 'version',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"blockheight", 'blockheight',
"confirmations", 'confirmations',
"blocktime", 'blocktime',
"valueOut", 'valueOut',
"valueIn", 'valueIn',
"fees", 'fees',
"hex", 'hex',
"time" 'time'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
+15 -15
View File
@@ -1,23 +1,23 @@
const assert = require("chai").assert const assert = require('chai').assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe("#price", () => { describe('#price', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#current", () => { describe('#current', () => {
describe("#single currency", () => { describe('#single currency', () => {
it("should get current price for single currency", async () => { it('should get current price for single currency', async () => {
const result = await bchjs.Price.current("usd") const result = await bchjs.Price.current('usd')
assert.notEqual(0, result) assert.notEqual(0, result)
}) })
}) })
}) })
describe("#getUsd", () => { describe('#getUsd', () => {
it("should get the USD price of BCH", async () => { it('should get the USD price of BCH', async () => {
const result = await bchjs.Price.getUsd() const result = await bchjs.Price.getUsd()
// console.log(result) // console.log(result)
@@ -25,8 +25,8 @@ describe("#price", () => {
}) })
}) })
describe("#getBchaUsd", () => { describe('#getBchaUsd', () => {
it("should get the USD price of BCHA", async () => { it('should get the USD price of BCHA', async () => {
const result = await bchjs.Price.getBchaUsd() const result = await bchjs.Price.getBchaUsd()
console.log(result) console.log(result)
@@ -34,13 +34,13 @@ describe("#price", () => {
}) })
}) })
describe("#rates", () => { describe('#rates', () => {
it("should get the price of BCH in several currencies", async () => { it('should get the price of BCH in several currencies', async () => {
const result = await bchjs.Price.rates() const result = await bchjs.Price.rates()
// console.log(result) // console.log(result)
assert.property(result, "USD") assert.property(result, 'USD')
assert.property(result, "CAD") assert.property(result, 'CAD')
}) })
}) })
}) })
+79 -79
View File
@@ -5,49 +5,49 @@
TODO TODO
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe("#rawtransaction", () => { describe('#rawtransaction', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe("#decodeRawTransaction", () => { describe('#decodeRawTransaction', () => {
it("should decode tx for a single hex", async () => { it('should decode tx for a single hex', async () => {
const hex = const hex =
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
const result = await bchjs.RawTransactions.decodeRawTransaction(hex) const result = await bchjs.RawTransactions.decodeRawTransaction(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout" 'vout'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
}) })
it("should decode an array of tx hexes", async () => { it('should decode an array of tx hexes', async () => {
const hexes = [ const hexes = [
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000", '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000',
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
] ]
const result = await bchjs.RawTransactions.decodeRawTransaction(hexes) const result = await bchjs.RawTransactions.decodeRawTransaction(hexes)
@@ -55,42 +55,42 @@ describe("#rawtransaction", () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout" 'vout'
]) ])
assert.isArray(result[0].vin) assert.isArray(result[0].vin)
assert.isArray(result[0].vout) assert.isArray(result[0].vout)
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const data = [] const data = []
for (let i = 0; i < 25; i++) { for (let i = 0; i < 25; i++) {
data.push( data.push(
"0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000" '0200000001b9b598d7d6d72fc486b2b3a3c03c79b5bade6ec9a77ced850515ab5e64edcc21010000006b483045022100a7b1b08956abb8d6f322aa709d8583c8ea492ba0585f1a6f4f9983520af74a5a0220411aee4a9a54effab617b0508c504c31681b15f9b187179b4874257badd4139041210360cfc66fdacb650bc4c83b4e351805181ee696b7d5ab4667c57b2786f51c413dffffffff0210270000000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac786e9800000000001976a914eb4b180def88e3f5625b2d8ae2c098ff7d85f66488ac00000000'
) )
} }
const result = await bchjs.RawTransactions.decodeRawTransaction(data) const result = await bchjs.RawTransactions.decodeRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#getRawTransaction", () => { describe('#getRawTransaction', () => {
it("should decode a single txid, with concise output", async () => { it('should decode a single txid, with concise output', async () => {
const txid = const txid =
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1" '23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1'
const verbose = false const verbose = false
const result = await bchjs.RawTransactions.getRawTransaction( const result = await bchjs.RawTransactions.getRawTransaction(
@@ -102,9 +102,9 @@ describe("#rawtransaction", () => {
assert.isString(result) assert.isString(result)
}) })
it("should decode a single txid, with verbose output", async () => { it('should decode a single txid, with verbose output', async () => {
const txid = const txid =
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1" '23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1'
const verbose = true const verbose = true
const result = await bchjs.RawTransactions.getRawTransaction( const result = await bchjs.RawTransactions.getRawTransaction(
@@ -114,27 +114,27 @@ describe("#rawtransaction", () => {
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"hex", 'hex',
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"confirmations", 'confirmations',
"time", 'time',
"blocktime" 'blocktime'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
}) })
it("should decode an array of txids, with a concise output", async () => { it('should decode an array of txids, with a concise output', async () => {
const txid = [ const txid = [
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1", '23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1',
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f" 'b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f'
] ]
const verbose = false const verbose = false
@@ -148,10 +148,10 @@ describe("#rawtransaction", () => {
assert.isString(result[0]) assert.isString(result[0])
}) })
it("should decode an array of txids, with a verbose output", async () => { it('should decode an array of txids, with a verbose output', async () => {
const txid = [ const txid = [
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1", '23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1',
"b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f" 'b25d24fbb42d84812ed2cb55797f10fdec41afc7906ab563d1ec8c8676a2037f'
] ]
const verbose = true const verbose = true
@@ -163,50 +163,50 @@ describe("#rawtransaction", () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"hex", 'hex',
"txid", 'txid',
"hash", 'hash',
"size", 'size',
"version", 'version',
"locktime", 'locktime',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"confirmations", 'confirmations',
"time", 'time',
"blocktime" 'blocktime'
]) ])
assert.isArray(result[0].vin) assert.isArray(result[0].vin)
assert.isArray(result[0].vout) assert.isArray(result[0].vout)
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const dataMock = const dataMock =
"23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1" '23213453b4642a73b4fc30d3112d72549ca153a8707255b14373b59e43558de1'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.getRawTransaction(data) const result = await bchjs.RawTransactions.getRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
describe("#decodeScript", () => { describe('#decodeScript', () => {
it("should decode script for a single hex", async () => { it('should decode script for a single hex', async () => {
const hex = const hex =
"4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16" '4830450221009a51e00ec3524a7389592bc27bea4af5104a59510f5f0cfafa64bbd5c164ca2e02206c2a8bbb47eabdeed52f17d7df668d521600286406930426e3a9415fe10ed592012102e6e1423f7abde8b70bca3e78a7d030e5efabd3eb35c19302542b5fe7879c1a16'
const result = await bchjs.RawTransactions.decodeScript(hex) const result = await bchjs.RawTransactions.decodeScript(hex)
// console.log(`result ${JSON.stringify(result, null, 2)}`) // console.log(`result ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["asm", "type", "p2sh"]) assert.hasAllKeys(result, ['asm', 'type', 'p2sh'])
}) })
// CT 2/20/19 - Waiting for this PR to be merged complete the test: // CT 2/20/19 - Waiting for this PR to be merged complete the test:
@@ -230,21 +230,21 @@ describe("#rawtransaction", () => {
below expect error messages returned from the server, but at least test below expect error messages returned from the server, but at least test
that the server is responding on those endpoints, and responds consistently. that the server is responding on those endpoints, and responds consistently.
*/ */
describe("sendRawTransaction", () => { describe('sendRawTransaction', () => {
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const dataMock = const dataMock =
"01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000" '01000000013ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a000000006a4730440220540986d1c58d6e76f8f05501c520c38ce55393d0ed7ed3c3a82c69af04221232022058ea43ed6c05fec0eccce749a63332ed4525460105346f11108b9c26df93cd72012103083dfc5a0254613941ddc91af39ff90cd711cdcde03a87b144b883b524660c39ffffffff01807c814a000000001976a914d7e7c4e0b70eaa67ceff9d2823d1bbb9f6df9a5188ac00000000'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.RawTransactions.sendRawTransaction(data) const result = await bchjs.RawTransactions.sendRawTransaction(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
+222 -222
View File
@@ -2,21 +2,21 @@
Integration tests for the bchjs covering SLP tokens. Integration tests for the bchjs covering SLP tokens.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 1 depth: 1
} }
describe(`#SLP`, () => { describe('#SLP', () => {
// before(() => { // before(() => {
// console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`) // console.log(`bchjs.SLP.restURL: ${bchjs.SLP.restURL}`)
// console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`) // console.log(`bchjs.SLP.apiToken: ${bchjs.SLP.apiToken}`)
@@ -29,35 +29,35 @@ describe(`#SLP`, () => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#util", () => { describe('#util', () => {
describe("#list", () => { describe('#list', () => {
it(`should get information on the Spice token`, async () => { it('should get information on the Spice token', async () => {
const tokenId = `4de69e374a8ed21cbddd47f2338cc0f479dc58daa2bbe11cd604ca488eca0ddf` const tokenId = '4de69e374a8ed21cbddd47f2338cc0f479dc58daa2bbe11cd604ca488eca0ddf'
const result = await bchjs.SLP.Utils.list(tokenId) const result = await bchjs.SLP.Utils.list(tokenId)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"decimals", 'decimals',
"timestamp", 'timestamp',
"timestamp_unix", 'timestamp_unix',
"versionType", 'versionType',
"documentUri", 'documentUri',
"symbol", 'symbol',
"name", 'name',
"containsBaton", 'containsBaton',
"id", 'id',
"documentHash", 'documentHash',
"initialTokenQty", 'initialTokenQty',
"blockCreated", 'blockCreated',
"blockLastActiveSend", 'blockLastActiveSend',
"blockLastActiveMint", 'blockLastActiveMint',
"txnsSinceGenesis", 'txnsSinceGenesis',
"validAddress", 'validAddress',
"totalMinted", 'totalMinted',
"totalBurned", 'totalBurned',
"circulatingSupply", 'circulatingSupply',
"mintingBatonStatus" 'mintingBatonStatus'
]) ])
}) })
}) })
@@ -134,109 +134,109 @@ describe(`#SLP`, () => {
// }) // })
// }) // })
describe("#decodeOpReturn", () => { describe('#decodeOpReturn', () => {
it("should decode the OP_RETURN for a SEND txid", async () => { it('should decode the OP_RETURN for a SEND txid', async () => {
const txid = const txid =
"266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1" '266844d53e46bbd7dd37134688dffea6e54d944edff27a0add63dd0908839bc1'
const result = await bchjs.SLP.Utils.decodeOpReturn(txid) const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["tokenType", "txType", "tokenId", "amounts"]) assert.hasAllKeys(result, ['tokenType', 'txType', 'tokenId', 'amounts'])
assert.equal( assert.equal(
result.tokenId, result.tokenId,
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7" '497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7'
) )
// Verify outputs // Verify outputs
assert.equal(result.amounts.length, 2) assert.equal(result.amounts.length, 2)
assert.equal(result.amounts[0], "100000000") assert.equal(result.amounts[0], '100000000')
assert.equal(result.amounts[1], "99883300000000") assert.equal(result.amounts[1], '99883300000000')
}) })
it("should decode the OP_RETURN for a GENESIS txid", async () => { it('should decode the OP_RETURN for a GENESIS txid', async () => {
const txid = const txid =
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7" '497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7'
const result = await bchjs.SLP.Utils.decodeOpReturn(txid) const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"tokenType", 'tokenType',
"txType", 'txType',
"tokenId", 'tokenId',
"ticker", 'ticker',
"name", 'name',
"documentUri", 'documentUri',
"documentHash", 'documentHash',
"decimals", 'decimals',
"mintBatonVout", 'mintBatonVout',
"qty" 'qty'
]) ])
assert.equal( assert.equal(
result.tokenId, result.tokenId,
"497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7" '497291b8a1dfe69c8daea50677a3d31a5ef0e9484d8bebb610dac64bbc202fb7'
) )
assert.equal(result.txType, "GENESIS") assert.equal(result.txType, 'GENESIS')
assert.equal(result.ticker, "TOK-CH") assert.equal(result.ticker, 'TOK-CH')
assert.equal(result.name, "TokyoCash") assert.equal(result.name, 'TokyoCash')
}) })
it("should decode the OP_RETURN for a MINT txid", async () => { it('should decode the OP_RETURN for a MINT txid', async () => {
const txid = const txid =
"65f21bbfcd545e5eb515e38e861a9dfe2378aaa2c4e458eb9e59e4d40e38f3a4" '65f21bbfcd545e5eb515e38e861a9dfe2378aaa2c4e458eb9e59e4d40e38f3a4'
const result = await bchjs.SLP.Utils.decodeOpReturn(txid) const result = await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"tokenType", 'tokenType',
"txType", 'txType',
"tokenId", 'tokenId',
"mintBatonVout", 'mintBatonVout',
"qty" 'qty'
]) ])
}) })
it("should throw an error for a non-SLP transaction", async () => { it('should throw an error for a non-SLP transaction', async () => {
try { try {
const txid = const txid =
"3793d4906654f648e659f384c0f40b19c8f10c1e9fb72232a9b8edd61abaa1ec" '3793d4906654f648e659f384c0f40b19c8f10c1e9fb72232a9b8edd61abaa1ec'
await bchjs.SLP.Utils.decodeOpReturn(txid) await bchjs.SLP.Utils.decodeOpReturn(txid)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, "scriptpubkey not op_return") assert.include(err.message, 'scriptpubkey not op_return')
} }
}) })
// Note: This TX is interpreted as valid by the original decodeOpReturn(). // Note: This TX is interpreted as valid by the original decodeOpReturn().
// Fixing this issue and related issues was the reason for creating the // Fixing this issue and related issues was the reason for creating the
// decodeOpReturn2() method using the slp-parser library. // decodeOpReturn2() method using the slp-parser library.
it("should throw error for invalid SLP transaction", async () => { it('should throw error for invalid SLP transaction', async () => {
try { try {
const txid = const txid =
"a60a522cc11ad7011b74e57fbabbd99296e4b9346bcb175dcf84efb737030415" 'a60a522cc11ad7011b74e57fbabbd99296e4b9346bcb175dcf84efb737030415'
await bchjs.SLP.Utils.decodeOpReturn(txid) await bchjs.SLP.Utils.decodeOpReturn(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, "amount string size not 8 bytes") assert.include(err.message, 'amount string size not 8 bytes')
} }
}) })
}) })
describe("#tokenUtxoDetails", () => { describe('#tokenUtxoDetails', () => {
// // This captures an important corner-case. When an SLP token is created, the // // This captures an important corner-case. When an SLP token is created, the
// // change UTXO will contain the same SLP txid, but it is not an SLP UTXO. // // change UTXO will contain the same SLP txid, but it is not an SLP UTXO.
it("should return details on minting baton from genesis transaction", async () => { it('should return details on minting baton from genesis transaction', async () => {
const utxos = [ const utxos = [
{ {
txid: txid:
"bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90", 'bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90',
vout: 3, vout: 3,
amount: 0.00002015, amount: 0.00002015,
satoshis: 2015, satoshis: 2015,
@@ -245,7 +245,7 @@ describe(`#SLP`, () => {
}, },
{ {
txid: txid:
"bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90", 'bd158c564dd4ef54305b14f44f8e94c44b649f246dab14bcb42fb0d0078b8a90',
vout: 2, vout: 2,
amount: 0.00000546, amount: 0.00000546,
satoshis: 546, satoshis: 546,
@@ -257,32 +257,32 @@ describe(`#SLP`, () => {
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos) const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`data: ${JSON.stringify(data, null, 2)}`) // console.log(`data: ${JSON.stringify(data, null, 2)}`)
assert.equal(data[0].isValid, false, "Change UTXO marked as false.") assert.equal(data[0].isValid, false, 'Change UTXO marked as false.')
assert.property(data[1], "txid") assert.property(data[1], 'txid')
assert.property(data[1], "vout") assert.property(data[1], 'vout')
assert.property(data[1], "amount") assert.property(data[1], 'amount')
assert.property(data[1], "satoshis") assert.property(data[1], 'satoshis')
assert.property(data[1], "height") assert.property(data[1], 'height')
assert.property(data[1], "confirmations") assert.property(data[1], 'confirmations')
assert.property(data[1], "utxoType") assert.property(data[1], 'utxoType')
assert.property(data[1], "tokenId") assert.property(data[1], 'tokenId')
assert.property(data[1], "tokenTicker") assert.property(data[1], 'tokenTicker')
assert.property(data[1], "tokenName") assert.property(data[1], 'tokenName')
assert.property(data[1], "tokenDocumentUrl") assert.property(data[1], 'tokenDocumentUrl')
assert.property(data[1], "tokenDocumentHash") assert.property(data[1], 'tokenDocumentHash')
assert.property(data[1], "decimals") assert.property(data[1], 'decimals')
assert.property(data[1], "isValid") assert.property(data[1], 'isValid')
assert.equal(data[1].isValid, true) assert.equal(data[1].isValid, true)
}) })
it("should return details for a MINT token utxo", async () => { it('should return details for a MINT token utxo', async () => {
// Mock the call to REST API // Mock the call to REST API
const utxos = [ const utxos = [
{ {
txid: txid:
"cf4b922d1e1aa56b52d752d4206e1448ea76c3ebe69b3b97d8f8f65413bd5c76", 'cf4b922d1e1aa56b52d752d4206e1448ea76c3ebe69b3b97d8f8f65413bd5c76',
vout: 1, vout: 1,
amount: 0.00000546, amount: 0.00000546,
satoshis: 546, satoshis: 546,
@@ -294,31 +294,31 @@ describe(`#SLP`, () => {
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos) const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`data: ${JSON.stringify(data, null, 2)}`) // console.log(`data: ${JSON.stringify(data, null, 2)}`)
assert.property(data[0], "txid") assert.property(data[0], 'txid')
assert.property(data[0], "vout") assert.property(data[0], 'vout')
assert.property(data[0], "amount") assert.property(data[0], 'amount')
assert.property(data[0], "satoshis") assert.property(data[0], 'satoshis')
assert.property(data[0], "height") assert.property(data[0], 'height')
assert.property(data[0], "confirmations") assert.property(data[0], 'confirmations')
assert.property(data[0], "utxoType") assert.property(data[0], 'utxoType')
assert.property(data[0], "transactionType") assert.property(data[0], 'transactionType')
assert.property(data[0], "tokenId") assert.property(data[0], 'tokenId')
assert.property(data[0], "tokenTicker") assert.property(data[0], 'tokenTicker')
assert.property(data[0], "tokenName") assert.property(data[0], 'tokenName')
assert.property(data[0], "tokenDocumentUrl") assert.property(data[0], 'tokenDocumentUrl')
assert.property(data[0], "tokenDocumentHash") assert.property(data[0], 'tokenDocumentHash')
assert.property(data[0], "decimals") assert.property(data[0], 'decimals')
assert.property(data[0], "mintBatonVout") assert.property(data[0], 'mintBatonVout')
assert.property(data[0], "tokenQty") assert.property(data[0], 'tokenQty')
assert.property(data[0], "isValid") assert.property(data[0], 'isValid')
assert.equal(data[0].isValid, true) assert.equal(data[0].isValid, true)
}) })
it("should return details for a simple SEND SLP token utxo", async () => { it('should return details for a simple SEND SLP token utxo', async () => {
const utxos = [ const utxos = [
{ {
txid: txid:
"fde117b1f176b231e2fa9a6cb022e0f7c31c288221df6bcb05f8b7d040ca87cb", 'fde117b1f176b231e2fa9a6cb022e0f7c31c288221df6bcb05f8b7d040ca87cb',
vout: 1, vout: 1,
amount: 0.00000546, amount: 0.00000546,
satoshis: 546, satoshis: 546,
@@ -330,40 +330,40 @@ describe(`#SLP`, () => {
const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos) const data = await bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`data: ${JSON.stringify(data, null, 2)}`) // console.log(`data: ${JSON.stringify(data, null, 2)}`)
assert.property(data[0], "txid") assert.property(data[0], 'txid')
assert.property(data[0], "vout") assert.property(data[0], 'vout')
assert.property(data[0], "amount") assert.property(data[0], 'amount')
assert.property(data[0], "satoshis") assert.property(data[0], 'satoshis')
assert.property(data[0], "height") assert.property(data[0], 'height')
assert.property(data[0], "confirmations") assert.property(data[0], 'confirmations')
assert.property(data[0], "utxoType") assert.property(data[0], 'utxoType')
assert.property(data[0], "tokenId") assert.property(data[0], 'tokenId')
assert.property(data[0], "tokenTicker") assert.property(data[0], 'tokenTicker')
assert.property(data[0], "tokenName") assert.property(data[0], 'tokenName')
assert.property(data[0], "tokenDocumentUrl") assert.property(data[0], 'tokenDocumentUrl')
assert.property(data[0], "tokenDocumentHash") assert.property(data[0], 'tokenDocumentHash')
assert.property(data[0], "decimals") assert.property(data[0], 'decimals')
assert.property(data[0], "tokenQty") assert.property(data[0], 'tokenQty')
assert.property(data[0], "isValid") assert.property(data[0], 'isValid')
assert.equal(data[0].isValid, true) assert.equal(data[0].isValid, true)
}) })
it("should handle BCH and SLP utxos in the same TX", async () => { it('should handle BCH and SLP utxos in the same TX', async () => {
const utxos = [ const utxos = [
{ {
txid: txid:
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56", 'd56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56',
vout: 3, vout: 3,
value: "6816", value: '6816',
height: 606848, height: 606848,
confirmations: 13, confirmations: 13,
satoshis: 6816 satoshis: 6816
}, },
{ {
txid: txid:
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56", 'd56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56',
vout: 2, vout: 2,
value: "546", value: '546',
height: 606848, height: 606848,
confirmations: 13, confirmations: 13,
satoshis: 546 satoshis: 546
@@ -379,11 +379,11 @@ describe(`#SLP`, () => {
assert.equal(result[1].isValid, true) assert.equal(result[1].isValid, true)
}) })
it("should handle problematic utxos", async () => { it('should handle problematic utxos', async () => {
const utxos = [ const utxos = [
{ {
txid: txid:
"0e3a217fc22612002031d317b4cecd9b692b66b52951a67b23c43041aefa3959", '0e3a217fc22612002031d317b4cecd9b692b66b52951a67b23c43041aefa3959',
vout: 0, vout: 0,
amount: 0.00018362, amount: 0.00018362,
satoshis: 18362, satoshis: 18362,
@@ -392,7 +392,7 @@ describe(`#SLP`, () => {
}, },
{ {
txid: txid:
"67fd3c7c3a6eb0fea9ab311b91039545086220f7eeeefa367fa28e6e43009f19", '67fd3c7c3a6eb0fea9ab311b91039545086220f7eeeefa367fa28e6e43009f19',
vout: 1, vout: 1,
amount: 0.00000546, amount: 0.00000546,
satoshis: 546, satoshis: 546,
@@ -410,11 +410,11 @@ describe(`#SLP`, () => {
assert.equal(result[1].isValid, true) assert.equal(result[1].isValid, true)
}) })
it("should return false for BCH-only UTXOs", async () => { it('should return false for BCH-only UTXOs', async () => {
const utxos = [ const utxos = [
{ {
txid: txid:
"a937f792c7c9eb23b4f344ce5c233d1ac0909217d0a504d71e6b1e4efb864a3b", 'a937f792c7c9eb23b4f344ce5c233d1ac0909217d0a504d71e6b1e4efb864a3b',
vout: 0, vout: 0,
amount: 0.00001, amount: 0.00001,
satoshis: 1000, satoshis: 1000,
@@ -423,7 +423,7 @@ describe(`#SLP`, () => {
}, },
{ {
txid: txid:
"53fd141c2e999e080a5860887441a2c45e9cbe262027e2bd2ac998fc76e43c44", '53fd141c2e999e080a5860887441a2c45e9cbe262027e2bd2ac998fc76e43c44',
vout: 0, vout: 0,
amount: 0.00001, amount: 0.00001,
satoshis: 1000, satoshis: 1000,
@@ -440,20 +440,20 @@ describe(`#SLP`, () => {
assert.equal(data[1].isValid, false) assert.equal(data[1].isValid, false)
}) })
it("should handle a dust attack", async () => { it('should handle a dust attack', async () => {
// it("#dustattack", async () => { // it("#dustattack", async () => {
const utxos = [ const utxos = [
{ {
height: 655965, height: 655965,
tx_hash: tx_hash:
"a675af87dcd8d39be782737aa52e0076b52eb2f5ce355ffcb5567a64dd96b77e", 'a675af87dcd8d39be782737aa52e0076b52eb2f5ce355ffcb5567a64dd96b77e',
tx_pos: 151, tx_pos: 151,
value: 547, value: 547,
satoshis: 547, satoshis: 547,
txid: txid:
"a675af87dcd8d39be782737aa52e0076b52eb2f5ce355ffcb5567a64dd96b77e", 'a675af87dcd8d39be782737aa52e0076b52eb2f5ce355ffcb5567a64dd96b77e',
vout: 151, vout: 151,
address: "bitcoincash:qq4dw3sm8qvglspy6w2qg0u2ugsy9zcfcqrpeflwww", address: 'bitcoincash:qq4dw3sm8qvglspy6w2qg0u2ugsy9zcfcqrpeflwww',
hdIndex: 11 hdIndex: 11
} }
] ]
@@ -464,19 +464,19 @@ describe(`#SLP`, () => {
assert.equal(data[0].isValid, false) assert.equal(data[0].isValid, false)
}) })
it("should handle null SLPDB validations", async () => { it('should handle null SLPDB validations', async () => {
const utxos = [ const utxos = [
{ {
height: 665577, height: 665577,
tx_hash: tx_hash:
"4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419", '4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
{ {
height: 665577, height: 665577,
tx_hash: tx_hash:
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488", '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
} }
@@ -490,27 +490,27 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#balancesForAddress", () => { describe('#balancesForAddress', () => {
it(`should fetch all balances for address: simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9`, async () => { it('should fetch all balances for address: simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9', async () => {
const balances = await bchjs.SLP.Utils.balancesForAddress( const balances = await bchjs.SLP.Utils.balancesForAddress(
"simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9" 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9'
) )
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`) // console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
assert.isArray(balances) assert.isArray(balances)
assert.hasAllKeys(balances[0], [ assert.hasAllKeys(balances[0], [
"tokenId", 'tokenId',
"balanceString", 'balanceString',
"balance", 'balance',
"decimalCount", 'decimalCount',
"slpAddress" 'slpAddress'
]) ])
}) })
it(`should fetch balances for multiple addresses`, async () => { it('should fetch balances for multiple addresses', async () => {
const addresses = [ const addresses = [
"simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9", 'simpleledger:qzv3zz2trz0xgp6a96lu4m6vp2nkwag0kvyucjzqt9',
"simpleledger:qqss4zp80hn6szsa4jg2s9fupe7g5tcg5ucdyl3r57" 'simpleledger:qqss4zp80hn6szsa4jg2s9fupe7g5tcg5ucdyl3r57'
] ]
const balances = await bchjs.SLP.Utils.balancesForAddress(addresses) const balances = await bchjs.SLP.Utils.balancesForAddress(addresses)
@@ -519,34 +519,34 @@ describe(`#SLP`, () => {
assert.isArray(balances) assert.isArray(balances)
assert.isArray(balances[0]) assert.isArray(balances[0])
assert.hasAllKeys(balances[0][0], [ assert.hasAllKeys(balances[0][0], [
"tokenId", 'tokenId',
"balanceString", 'balanceString',
"balance", 'balance',
"decimalCount", 'decimalCount',
"slpAddress" 'slpAddress'
]) ])
}) })
}) })
describe("#hydrateUtxos", () => { describe('#hydrateUtxos', () => {
it("should hydrate UTXOs", async () => { it('should hydrate UTXOs', async () => {
const utxos = [ const utxos = [
{ {
utxos: [ utxos: [
{ {
txid: txid:
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56", 'd56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56',
vout: 3, vout: 3,
value: "6816", value: '6816',
height: 606848, height: 606848,
confirmations: 13, confirmations: 13,
satoshis: 6816 satoshis: 6816
}, },
{ {
txid: txid:
"d56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56", 'd56a2b446d8149c39ca7e06163fe8097168c3604915f631bc58777d669135a56',
vout: 2, vout: 2,
value: "546", value: '546',
height: 606848, height: 606848,
confirmations: 13, confirmations: 13,
satoshis: 546 satoshis: 546
@@ -564,40 +564,40 @@ describe(`#SLP`, () => {
assert.equal(result.slpUtxos[0].utxos.length, 2) assert.equal(result.slpUtxos[0].utxos.length, 2)
// Test the non-slp UTXO. // Test the non-slp UTXO.
assert.property(result.slpUtxos[0].utxos[0], "txid") assert.property(result.slpUtxos[0].utxos[0], 'txid')
assert.property(result.slpUtxos[0].utxos[0], "vout") assert.property(result.slpUtxos[0].utxos[0], 'vout')
assert.property(result.slpUtxos[0].utxos[0], "value") assert.property(result.slpUtxos[0].utxos[0], 'value')
assert.property(result.slpUtxos[0].utxos[0], "height") assert.property(result.slpUtxos[0].utxos[0], 'height')
assert.property(result.slpUtxos[0].utxos[0], "confirmations") assert.property(result.slpUtxos[0].utxos[0], 'confirmations')
assert.property(result.slpUtxos[0].utxos[0], "satoshis") assert.property(result.slpUtxos[0].utxos[0], 'satoshis')
assert.property(result.slpUtxos[0].utxos[0], "isValid") assert.property(result.slpUtxos[0].utxos[0], 'isValid')
assert.equal(result.slpUtxos[0].utxos[0].isValid, false) assert.equal(result.slpUtxos[0].utxos[0].isValid, false)
// Test the slp UTXO. // Test the slp UTXO.
assert.property(result.slpUtxos[0].utxos[1], "txid") assert.property(result.slpUtxos[0].utxos[1], 'txid')
assert.property(result.slpUtxos[0].utxos[1], "vout") assert.property(result.slpUtxos[0].utxos[1], 'vout')
assert.property(result.slpUtxos[0].utxos[1], "value") assert.property(result.slpUtxos[0].utxos[1], 'value')
assert.property(result.slpUtxos[0].utxos[1], "height") assert.property(result.slpUtxos[0].utxos[1], 'height')
assert.property(result.slpUtxos[0].utxos[1], "confirmations") assert.property(result.slpUtxos[0].utxos[1], 'confirmations')
assert.property(result.slpUtxos[0].utxos[1], "satoshis") assert.property(result.slpUtxos[0].utxos[1], 'satoshis')
assert.property(result.slpUtxos[0].utxos[1], "isValid") assert.property(result.slpUtxos[0].utxos[1], 'isValid')
assert.equal(result.slpUtxos[0].utxos[1].isValid, true) assert.equal(result.slpUtxos[0].utxos[1].isValid, true)
assert.property(result.slpUtxos[0].utxos[1], "transactionType") assert.property(result.slpUtxos[0].utxos[1], 'transactionType')
assert.property(result.slpUtxos[0].utxos[1], "tokenId") assert.property(result.slpUtxos[0].utxos[1], 'tokenId')
assert.property(result.slpUtxos[0].utxos[1], "tokenTicker") assert.property(result.slpUtxos[0].utxos[1], 'tokenTicker')
assert.property(result.slpUtxos[0].utxos[1], "tokenName") assert.property(result.slpUtxos[0].utxos[1], 'tokenName')
assert.property(result.slpUtxos[0].utxos[1], "tokenDocumentUrl") assert.property(result.slpUtxos[0].utxos[1], 'tokenDocumentUrl')
assert.property(result.slpUtxos[0].utxos[1], "tokenDocumentHash") assert.property(result.slpUtxos[0].utxos[1], 'tokenDocumentHash')
assert.property(result.slpUtxos[0].utxos[1], "decimals") assert.property(result.slpUtxos[0].utxos[1], 'decimals')
assert.property(result.slpUtxos[0].utxos[1], "tokenType") assert.property(result.slpUtxos[0].utxos[1], 'tokenType')
assert.property(result.slpUtxos[0].utxos[1], "tokenQty") assert.property(result.slpUtxos[0].utxos[1], 'tokenQty')
}) })
it("should process data directly from Electrumx", async () => { it('should process data directly from Electrumx', async () => {
const addrs = [ const addrs = [
"bitcoincash:qqnt53cfw990u6y38xgezm0lfa8hknw0wueezcpagp", 'bitcoincash:qqnt53cfw990u6y38xgezm0lfa8hknw0wueezcpagp',
"bitcoincash:qrh3qgtax6adegzc7zxm6m4sgrv9wq28yqnfn33ce5", 'bitcoincash:qrh3qgtax6adegzc7zxm6m4sgrv9wq28yqnfn33ce5',
"bitcoincash:qqcaee5w4ws77n8s2gzy6fwtma6uxd7ctq8553e495" 'bitcoincash:qqcaee5w4ws77n8s2gzy6fwtma6uxd7ctq8553e495'
] ]
const utxos = await bchjs.Electrumx.utxo(addrs) const utxos = await bchjs.Electrumx.utxo(addrs)
@@ -617,31 +617,31 @@ describe(`#SLP`, () => {
// Test the expected values. // Test the expected values.
assert.equal(result.slpUtxos[0].utxos[0].isValid, false) assert.equal(result.slpUtxos[0].utxos[0].isValid, false)
assert.equal(result.slpUtxos[1].utxos[0].isValid, true) assert.equal(result.slpUtxos[1].utxos[0].isValid, true)
assert.equal(result.slpUtxos[1].utxos[0].tokenTicker, "TROUT") assert.equal(result.slpUtxos[1].utxos[0].tokenTicker, 'TROUT')
assert.equal(result.slpUtxos[2].utxos[0].isValid, false) assert.equal(result.slpUtxos[2].utxos[0].isValid, false)
assert.equal(result.slpUtxos[2].utxos[1].isValid, true) assert.equal(result.slpUtxos[2].utxos[1].isValid, true)
assert.equal(result.slpUtxos[2].utxos[1].tokenTicker, "VALENTINE") assert.equal(result.slpUtxos[2].utxos[1].tokenTicker, 'VALENTINE')
} catch (err) { } catch (err) {
console.error( console.error(
'The hydrateUtxos call may hitting rate limits, or SLPDB may be having issues if "isValid" results are "null"' 'The hydrateUtxos call may hitting rate limits, or SLPDB may be having issues if "isValid" results are "null"'
) )
console.log("Error: ", err) console.log('Error: ', err)
} }
}) })
it("should handle null SLPDB validations", async () => { it('should handle null SLPDB validations', async () => {
const utxos = [ const utxos = [
{ {
height: 665577, height: 665577,
tx_hash: tx_hash:
"4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419", '4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
}, },
{ {
height: 665577, height: 665577,
tx_hash: tx_hash:
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a", 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
tx_pos: 1, tx_pos: 1,
value: 546 value: 546
} }
@@ -655,11 +655,11 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid", () => { describe('#validateTxid', () => {
// This test is not necessary. // This test is not necessary.
it("should handle a null response from SLPDB", async () => { it('should handle a null response from SLPDB', async () => {
const txid = const txid =
"4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419" '4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419'
const result = await bchjs.SLP.Utils.validateTxid(txid) const result = await bchjs.SLP.Utils.validateTxid(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
@@ -669,10 +669,10 @@ describe(`#SLP`, () => {
// assert.equal(result[0].valid, null) // assert.equal(result[0].valid, null)
}) })
it("should handle a null response from SLPDB", async () => { it('should handle a null response from SLPDB', async () => {
const txid = [ const txid = [
"4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419", '4b89405c54d1c0bde8aa476a47561a42a6e7a5e927daa2ec69d428810eae3419',
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488" '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488'
] ]
const result = await bchjs.SLP.Utils.validateTxid(txid) const result = await bchjs.SLP.Utils.validateTxid(txid)
@@ -684,66 +684,66 @@ describe(`#SLP`, () => {
}) })
}) })
describe("#validateTxid2", () => { describe('#validateTxid2', () => {
it("should invalidate a known invalid TXID", async () => { it('should invalidate a known invalid TXID', async () => {
const txid = const txid =
"f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a" 'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
const result = await bchjs.SLP.Utils.validateTxid2(txid) const result = await bchjs.SLP.Utils.validateTxid2(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "txid") assert.property(result, 'txid')
assert.equal(result.txid, txid) assert.equal(result.txid, txid)
assert.property(result, "isValid") assert.property(result, 'isValid')
assert.equal(result.isValid, false) assert.equal(result.isValid, false)
}) })
it("should validate a known valid TXID", async () => { it('should validate a known valid TXID', async () => {
const txid = const txid =
"3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488" '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488'
const result = await bchjs.SLP.Utils.validateTxid2(txid) const result = await bchjs.SLP.Utils.validateTxid2(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "txid") assert.property(result, 'txid')
assert.equal(result.txid, txid) assert.equal(result.txid, txid)
assert.property(result, "isValid") assert.property(result, 'isValid')
assert.equal(result.isValid, true) assert.equal(result.isValid, true)
}) })
}) })
describe("#getWhitelist", () => { describe('#getWhitelist', () => {
it("should get the whitelist", async () => { it('should get the whitelist', async () => {
const result = await bchjs.SLP.Utils.getWhitelist() const result = await bchjs.SLP.Utils.getWhitelist()
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "name") assert.property(result[0], 'name')
assert.property(result[1], "tokenId") assert.property(result[1], 'tokenId')
}) })
}) })
describe("#getStatus", () => { describe('#getStatus', () => {
it("should return the current block height of the SLPDB indexer", async () => { it('should return the current block height of the SLPDB indexer', async () => {
const result = await bchjs.SLP.Utils.getStatus() const result = await bchjs.SLP.Utils.getStatus()
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "bchBlockHeight") assert.property(result, 'bchBlockHeight')
assert.property(result, "slpProcessedBlockHeight") assert.property(result, 'slpProcessedBlockHeight')
}) })
}) })
}) })
describe("#tokentype1", () => { describe('#tokentype1', () => {
describe("#getHexOpReturn", () => { describe('#getHexOpReturn', () => {
it("should return OP_RETURN object ", async () => { it('should return OP_RETURN object ', async () => {
const tokenUtxos = [ const tokenUtxos = [
{ {
tokenId: tokenId:
"0a321bff9761f28e06a268b14711274bb77617410a16807bd0437ef234a072b1", '0a321bff9761f28e06a268b14711274bb77617410a16807bd0437ef234a072b1',
decimals: 0, decimals: 0,
tokenQty: 2 tokenQty: 2
} }
@@ -756,10 +756,10 @@ describe(`#SLP`, () => {
) )
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "script") assert.property(result, 'script')
assert.isString(result.script) assert.isString(result.script)
assert.property(result, "outputs") assert.property(result, 'outputs')
assert.isNumber(result.outputs) assert.isNumber(result.outputs)
}) })
}) })
+29 -29
View File
@@ -3,66 +3,66 @@
rest.bitcoin.com. rest.bitcoin.com.
*/ */
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Inspect utility used for debugging. // Inspect utility used for debugging.
const util = require("util") const util = require('util')
util.inspect.defaultOptions = { util.inspect.defaultOptions = {
showHidden: true, showHidden: true,
colors: true, colors: true,
depth: 3 depth: 3
} }
describe(`#util`, () => { describe('#util', () => {
beforeEach(async () => { beforeEach(async () => {
if (process.env.IS_USING_FREE_TIER) await sleep(1000) if (process.env.IS_USING_FREE_TIER) await sleep(1000)
}) })
describe(`#validateAddress`, () => { describe('#validateAddress', () => {
it(`should return false for testnet addr on mainnet`, async () => { it('should return false for testnet addr on mainnet', async () => {
const address = `bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y` const address = 'bchtest:qqqk4y6lsl5da64sg5qc3xezmplyu5kmpyz2ysaa5y'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["isvalid"]) assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false) assert.equal(result.isvalid, false)
}) })
it(`should return false for bad address`, async () => { it('should return false for bad address', async () => {
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peu` const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peu'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["isvalid"]) assert.hasAllKeys(result, ['isvalid'])
assert.equal(result.isvalid, false) assert.equal(result.isvalid, false)
}) })
it(`should validate valid address`, async () => { it('should validate valid address', async () => {
const address = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z` const address = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [ assert.hasAnyKeys(result, [
"isvalid", 'isvalid',
"address", 'address',
"scriptPubKey", 'scriptPubKey',
// "ismine", // "ismine",
// "iswatchonly", // "iswatchonly",
"isscript" 'isscript'
]) ])
assert.equal(result.isvalid, true) assert.equal(result.isvalid, true)
}) })
it(`should validate an array of addresses`, async () => { it('should validate an array of addresses', async () => {
const address = [ const address = [
`bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z`, 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z',
`bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z` 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
] ]
const result = await bchjs.Util.validateAddress(address) const result = await bchjs.Util.validateAddress(address)
@@ -70,28 +70,28 @@ describe(`#util`, () => {
assert.isArray(result) assert.isArray(result)
assert.hasAnyKeys(result[0], [ assert.hasAnyKeys(result[0], [
"isvalid", 'isvalid',
"address", 'address',
"scriptPubKey", 'scriptPubKey',
// "ismine", // "ismine",
// "iswatchonly", // "iswatchonly",
"isscript" 'isscript'
]) ])
}) })
it(`should throw error on array size rate limit`, async () => { it('should throw error on array size rate limit', async () => {
try { try {
const dataMock = `bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z` const dataMock = 'bitcoincash:qp4k8fjtgunhdr7yq30ha4peuwupzan2vcnwrmpy0z'
const data = [] const data = []
for (let i = 0; i < 25; i++) data.push(dataMock) for (let i = 0; i < 25; i++) data.push(dataMock)
const result = await bchjs.Util.validateAddress(data) const result = await bchjs.Util.validateAddress(data)
console.log(`result: ${util.inspect(result)}`) console.log(`result: ${util.inspect(result)}`)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.hasAnyKeys(err, ["error"]) assert.hasAnyKeys(err, ['error'])
assert.include(err.error, "Array too large") assert.include(err.error, 'Array too large')
} }
}) })
}) })
+135 -135
View File
@@ -1,12 +1,12 @@
// Public npm libraries. // Public npm libraries.
const assert = require("assert") const assert = require('assert')
const Bitcoin = require("@psf/bitcoincashjs-lib") const Bitcoin = require('@psf/bitcoincashjs-lib')
// Mocks // Mocks
const fixtures = require("./fixtures/address.json") const fixtures = require('./fixtures/address.json')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
function flatten (arrays) { function flatten (arrays) {
@@ -49,14 +49,14 @@ const CASHADDR_ADDRESSES = flatten([
]) ])
const CASHADDR_ADDRESSES_NO_PREFIX = CASHADDR_ADDRESSES.map(address => { const CASHADDR_ADDRESSES_NO_PREFIX = CASHADDR_ADDRESSES.map(address => {
const parts = address.split(":") const parts = address.split(':')
return parts[1] return parts[1]
}) })
const REGTEST_ADDRESSES = fixtures.cashaddrRegTestP2PKH const REGTEST_ADDRESSES = fixtures.cashaddrRegTestP2PKH
const REGTEST_ADDRESSES_NO_PREFIX = REGTEST_ADDRESSES.map(address => { const REGTEST_ADDRESSES_NO_PREFIX = REGTEST_ADDRESSES.map(address => {
const parts = address.split(":") const parts = address.split(':')
return parts[1] return parts[1]
}) })
@@ -79,14 +79,14 @@ const P2SH_ADDRESSES = flatten([
fixtures.cashaddrMainnetP2SH fixtures.cashaddrMainnetP2SH
]) ])
describe("#address.js", () => { describe('#address.js', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#addressConversion", () => { describe('#addressConversion', () => {
describe("#toLegacyAddress", () => { describe('#toLegacyAddress', () => {
it("should translate legacy address format to itself correctly", () => { it('should translate legacy address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
LEGACY_ADDRESSES.map(address => LEGACY_ADDRESSES.map(address =>
bchjs.Address.toLegacyAddress(address) bchjs.Address.toLegacyAddress(address)
@@ -95,7 +95,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert cashaddr address to legacy base58Check", () => { it('should convert cashaddr address to legacy base58Check', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES.map(address => CASHADDR_ADDRESSES.map(address =>
bchjs.Address.toLegacyAddress(address) bchjs.Address.toLegacyAddress(address)
@@ -104,7 +104,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert cashaddr regtest address to legacy base58Check", () => { it('should convert cashaddr regtest address to legacy base58Check', () => {
assert.deepEqual( assert.deepEqual(
REGTEST_ADDRESSES.map(address => REGTEST_ADDRESSES.map(address =>
bchjs.Address.toLegacyAddress(address) bchjs.Address.toLegacyAddress(address)
@@ -113,20 +113,20 @@ describe("#address.js", () => {
) )
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.toLegacyAddress() bchjs.Address.toLegacyAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.toLegacyAddress("some invalid address") bchjs.Address.toLegacyAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#toCashAddress", () => { describe('#toCashAddress', () => {
it("should convert legacy base58Check address to cashaddr", () => { it('should convert legacy base58Check address to cashaddr', () => {
assert.deepEqual( assert.deepEqual(
LEGACY_ADDRESSES.map(address => LEGACY_ADDRESSES.map(address =>
bchjs.Address.toCashAddress(address, true) bchjs.Address.toCashAddress(address, true)
@@ -135,7 +135,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert legacy base58Check address to regtest cashaddr", () => { it('should convert legacy base58Check address to regtest cashaddr', () => {
assert.deepEqual( assert.deepEqual(
fixtures.legacyTestnetP2PKH.map(address => fixtures.legacyTestnetP2PKH.map(address =>
bchjs.Address.toCashAddress(address, true, true) bchjs.Address.toCashAddress(address, true, true)
@@ -144,7 +144,7 @@ describe("#address.js", () => {
) )
}) })
it("should translate cashaddr address format to itself correctly", () => { it('should translate cashaddr address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES.map(address => CASHADDR_ADDRESSES.map(address =>
bchjs.Address.toCashAddress(address, true) bchjs.Address.toCashAddress(address, true)
@@ -153,7 +153,7 @@ describe("#address.js", () => {
) )
}) })
it("should translate regtest cashaddr address format to itself correctly", () => { it('should translate regtest cashaddr address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
REGTEST_ADDRESSES.map(address => REGTEST_ADDRESSES.map(address =>
bchjs.Address.toCashAddress(address, true, true) bchjs.Address.toCashAddress(address, true, true)
@@ -162,7 +162,7 @@ describe("#address.js", () => {
) )
}) })
it("should translate no-prefix cashaddr address format to itself correctly", () => { it('should translate no-prefix cashaddr address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.toCashAddress(address, true) bchjs.Address.toCashAddress(address, true)
@@ -171,7 +171,7 @@ describe("#address.js", () => {
) )
}) })
it("should translate no-prefix regtest cashaddr address format to itself correctly", () => { it('should translate no-prefix regtest cashaddr address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
REGTEST_ADDRESSES_NO_PREFIX.map(address => REGTEST_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.toCashAddress(address, true, true) bchjs.Address.toCashAddress(address, true, true)
@@ -180,68 +180,68 @@ describe("#address.js", () => {
) )
}) })
it("should translate cashaddr address format to itself of no-prefix correctly", () => { it('should translate cashaddr address format to itself of no-prefix correctly', () => {
CASHADDR_ADDRESSES.forEach(address => { CASHADDR_ADDRESSES.forEach(address => {
const noPrefix = bchjs.Address.toCashAddress(address, false) const noPrefix = bchjs.Address.toCashAddress(address, false)
assert.equal(address.split(":")[1], noPrefix) assert.equal(address.split(':')[1], noPrefix)
}) })
}) })
it("should translate regtest cashaddr address format to itself of no-prefix correctly", () => { it('should translate regtest cashaddr address format to itself of no-prefix correctly', () => {
REGTEST_ADDRESSES.forEach(address => { REGTEST_ADDRESSES.forEach(address => {
const noPrefix = bchjs.Address.toCashAddress(address, false, true) const noPrefix = bchjs.Address.toCashAddress(address, false, true)
assert.equal(address.split(":")[1], noPrefix) assert.equal(address.split(':')[1], noPrefix)
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.BitcoinCash.Address.toCashAddress() bchjs.BitcoinCash.Address.toCashAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.BitcoinCash.Address.toCashAddress("some invalid address") bchjs.BitcoinCash.Address.toCashAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#toHash160", () => { describe('#toHash160', () => {
it("should convert legacy base58check address to hash160", () => { it('should convert legacy base58check address to hash160', () => {
assert.deepEqual( assert.deepEqual(
LEGACY_ADDRESSES.map(address => bchjs.Address.toHash160(address)), LEGACY_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
HASH160_HASHES HASH160_HASHES
) )
}) })
it("should convert cashaddr address to hash160", () => { it('should convert cashaddr address to hash160', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES.map(address => bchjs.Address.toHash160(address)), CASHADDR_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
HASH160_HASHES HASH160_HASHES
) )
}) })
it("should convert regtest cashaddr address to hash160", () => { it('should convert regtest cashaddr address to hash160', () => {
assert.deepEqual( assert.deepEqual(
REGTEST_ADDRESSES.map(address => bchjs.Address.toHash160(address)), REGTEST_ADDRESSES.map(address => bchjs.Address.toHash160(address)),
fixtures.hash160TestnetP2PKH fixtures.hash160TestnetP2PKH
) )
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.toHash160() bchjs.Address.toHash160()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.toHash160("some invalid address") bchjs.Address.toHash160('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#fromHash160", () => { describe('#fromHash160', () => {
it("should convert hash160 to mainnet P2PKH legacy base58check address", () => { it('should convert hash160 to mainnet P2PKH legacy base58check address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160MainnetP2PKH.map(hash160 => fixtures.hash160MainnetP2PKH.map(hash160 =>
bchjs.Address.hash160ToLegacy(hash160) bchjs.Address.hash160ToLegacy(hash160)
@@ -250,7 +250,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to mainnet P2SH legacy base58check address", () => { it('should convert hash160 to mainnet P2SH legacy base58check address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160MainnetP2SH.map(hash160 => fixtures.hash160MainnetP2SH.map(hash160 =>
bchjs.Address.hash160ToLegacy( bchjs.Address.hash160ToLegacy(
@@ -262,7 +262,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to testnet P2PKH legacy base58check address", () => { it('should convert hash160 to testnet P2PKH legacy base58check address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160TestnetP2PKH.map(hash160 => fixtures.hash160TestnetP2PKH.map(hash160 =>
bchjs.Address.hash160ToLegacy( bchjs.Address.hash160ToLegacy(
@@ -274,7 +274,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to mainnet P2PKH cash address", () => { it('should convert hash160 to mainnet P2PKH cash address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160MainnetP2PKH.map(hash160 => fixtures.hash160MainnetP2PKH.map(hash160 =>
bchjs.Address.hash160ToCash(hash160) bchjs.Address.hash160ToCash(hash160)
@@ -283,7 +283,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to mainnet P2SH cash address", () => { it('should convert hash160 to mainnet P2SH cash address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160MainnetP2SH.map(hash160 => fixtures.hash160MainnetP2SH.map(hash160 =>
bchjs.Address.hash160ToCash( bchjs.Address.hash160ToCash(
@@ -295,7 +295,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to testnet P2PKH cash address", () => { it('should convert hash160 to testnet P2PKH cash address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160TestnetP2PKH.map(hash160 => fixtures.hash160TestnetP2PKH.map(hash160 =>
bchjs.Address.hash160ToCash( bchjs.Address.hash160ToCash(
@@ -307,7 +307,7 @@ describe("#address.js", () => {
) )
}) })
it("should convert hash160 to regtest P2PKH cash address", () => { it('should convert hash160 to regtest P2PKH cash address', () => {
assert.deepEqual( assert.deepEqual(
fixtures.hash160TestnetP2PKH.map(hash160 => fixtures.hash160TestnetP2PKH.map(hash160 =>
bchjs.Address.hash160ToCash( bchjs.Address.hash160ToCash(
@@ -320,28 +320,28 @@ describe("#address.js", () => {
) )
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.hash160ToLegacy() bchjs.Address.hash160ToLegacy()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.hash160ToLegacy("some invalid address") bchjs.Address.hash160ToLegacy('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.hash160ToCash() bchjs.Address.hash160ToCash()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.hash160ToCash("some invalid address") bchjs.Address.hash160ToCash('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
}) })
describe("address format detection", () => { describe('address format detection', () => {
describe("#isLegacyAddress", () => { describe('#isLegacyAddress', () => {
describe("is legacy", () => { describe('is legacy', () => {
LEGACY_ADDRESSES.forEach(address => { LEGACY_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy base58Check address`, () => { it(`should detect ${address} is a legacy base58Check address`, () => {
const isBase58Check = bchjs.Address.isLegacyAddress(address) const isBase58Check = bchjs.Address.isLegacyAddress(address)
@@ -349,7 +349,7 @@ describe("#address.js", () => {
}) })
}) })
}) })
describe("is not legacy", () => { describe('is not legacy', () => {
CASHADDR_ADDRESSES.forEach(address => { CASHADDR_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a legacy address`, () => { it(`should detect ${address} is not a legacy address`, () => {
const isBase58Check = bchjs.Address.isLegacyAddress(address) const isBase58Check = bchjs.Address.isLegacyAddress(address)
@@ -365,20 +365,20 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isLegacyAddress() bchjs.Address.isLegacyAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isLegacyAddress("some invalid address") bchjs.Address.isLegacyAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#isCashAddress", () => { describe('#isCashAddress', () => {
describe("is cashaddr", () => { describe('is cashaddr', () => {
CASHADDR_ADDRESSES.forEach(address => { CASHADDR_ADDRESSES.forEach(address => {
it(`should detect ${address} is a cashaddr address`, () => { it(`should detect ${address} is a cashaddr address`, () => {
const isCashaddr = bchjs.Address.isCashAddress(address) const isCashaddr = bchjs.Address.isCashAddress(address)
@@ -394,7 +394,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not cashaddr", () => { describe('is not cashaddr', () => {
LEGACY_ADDRESSES.forEach(address => { LEGACY_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a cashaddr address`, () => { it(`should detect ${address} is not a cashaddr address`, () => {
const isCashaddr = bchjs.Address.isCashAddress(address) const isCashaddr = bchjs.Address.isCashAddress(address)
@@ -403,19 +403,19 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isCashAddress() bchjs.Address.isCashAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isCashAddress("some invalid address") bchjs.Address.isCashAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#isHash160", () => { describe('#isHash160', () => {
describe("is hash160", () => { describe('is hash160', () => {
HASH160_HASHES.forEach(address => { HASH160_HASHES.forEach(address => {
it(`should detect ${address} is a hash160 hash`, () => { it(`should detect ${address} is a hash160 hash`, () => {
const isHash160 = bchjs.Address.isHash160(address) const isHash160 = bchjs.Address.isHash160(address)
@@ -423,7 +423,7 @@ describe("#address.js", () => {
}) })
}) })
}) })
describe("is not hash160", () => { describe('is not hash160', () => {
LEGACY_ADDRESSES.forEach(address => { LEGACY_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a hash160 hash`, () => { it(`should detect ${address} is not a hash160 hash`, () => {
const isHash160 = bchjs.Address.isHash160(address) const isHash160 = bchjs.Address.isHash160(address)
@@ -446,22 +446,22 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isHash160() bchjs.Address.isHash160()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isHash160("some invalid address") bchjs.Address.isHash160('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
}) })
describe("network detection", () => { describe('network detection', () => {
describe("#isMainnetAddress", () => { describe('#isMainnetAddress', () => {
describe("is mainnet", () => { describe('is mainnet', () => {
MAINNET_ADDRESSES.forEach(address => { MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnet = bchjs.Address.isMainnetAddress(address) const isMainnet = bchjs.Address.isMainnetAddress(address)
@@ -470,7 +470,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not mainnet", () => { describe('is not mainnet', () => {
TESTNET_ADDRESSES.forEach(address => { TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a mainnet address`, () => { it(`should detect ${address} is not a mainnet address`, () => {
const isMainnet = bchjs.Address.isMainnetAddress(address) const isMainnet = bchjs.Address.isMainnetAddress(address)
@@ -486,20 +486,20 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isMainnetAddress() bchjs.Address.isMainnetAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isMainnetAddress("some invalid address") bchjs.Address.isMainnetAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#isTestnetAddress", () => { describe('#isTestnetAddress', () => {
describe("is testnet", () => { describe('is testnet', () => {
TESTNET_ADDRESSES.forEach(address => { TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = bchjs.Address.isTestnetAddress(address) const isTestnet = bchjs.Address.isTestnetAddress(address)
@@ -508,7 +508,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not testnet", () => { describe('is not testnet', () => {
MAINNET_ADDRESSES.forEach(address => { MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a testnet address`, () => { it(`should detect ${address} is not a testnet address`, () => {
const isTestnet = bchjs.Address.isTestnetAddress(address) const isTestnet = bchjs.Address.isTestnetAddress(address)
@@ -524,20 +524,20 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isTestnetAddress() bchjs.Address.isTestnetAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isTestnetAddress("some invalid address") bchjs.Address.isTestnetAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#isRegTestAddress", () => { describe('#isRegTestAddress', () => {
describe("is testnet", () => { describe('is testnet', () => {
REGTEST_ADDRESSES.forEach(address => { REGTEST_ADDRESSES.forEach(address => {
it(`should detect ${address} is a regtest address`, () => { it(`should detect ${address} is a regtest address`, () => {
const isRegTest = bchjs.Address.isRegTestAddress(address) const isRegTest = bchjs.Address.isRegTestAddress(address)
@@ -546,7 +546,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not testnet", () => { describe('is not testnet', () => {
MAINNET_ADDRESSES.forEach(address => { MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a regtest address`, () => { it(`should detect ${address} is not a regtest address`, () => {
const isRegTest = bchjs.Address.isRegTestAddress(address) const isRegTest = bchjs.Address.isRegTestAddress(address)
@@ -562,22 +562,22 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isRegTestAddress() bchjs.Address.isRegTestAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isRegTestAddress("some invalid address") bchjs.Address.isRegTestAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
}) })
describe("address type detection", () => { describe('address type detection', () => {
describe("#isP2PKHAddress", () => { describe('#isP2PKHAddress', () => {
describe("is P2PKH", () => { describe('is P2PKH', () => {
P2PKH_ADDRESSES.forEach(address => { P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2PKH address`, () => { it(`should detect ${address} is a P2PKH address`, () => {
const isP2PKH = bchjs.Address.isP2PKHAddress(address) const isP2PKH = bchjs.Address.isP2PKHAddress(address)
@@ -586,7 +586,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not P2PKH", () => { describe('is not P2PKH', () => {
P2SH_ADDRESSES.forEach(address => { P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a P2PKH address`, () => { it(`should detect ${address} is not a P2PKH address`, () => {
const isP2PKH = bchjs.Address.isP2PKHAddress(address) const isP2PKH = bchjs.Address.isP2PKHAddress(address)
@@ -595,20 +595,20 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isP2PKHAddress() bchjs.Address.isP2PKHAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isP2PKHAddress("some invalid address") bchjs.Address.isP2PKHAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#isP2SHAddress", () => { describe('#isP2SHAddress', () => {
describe("is P2SH", () => { describe('is P2SH', () => {
P2SH_ADDRESSES.forEach(address => { P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2SH address`, () => { it(`should detect ${address} is a P2SH address`, () => {
const isP2SH = bchjs.Address.isP2SHAddress(address) const isP2SH = bchjs.Address.isP2SHAddress(address)
@@ -617,7 +617,7 @@ describe("#address.js", () => {
}) })
}) })
describe("is not P2SH", () => { describe('is not P2SH', () => {
P2PKH_ADDRESSES.forEach(address => { P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a P2SH address`, () => { it(`should detect ${address} is not a P2SH address`, () => {
const isP2SH = bchjs.Address.isP2SHAddress(address) const isP2SH = bchjs.Address.isP2SHAddress(address)
@@ -626,21 +626,21 @@ describe("#address.js", () => {
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.isP2SHAddress() bchjs.Address.isP2SHAddress()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.isP2SHAddress("some invalid address") bchjs.Address.isP2SHAddress('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
}) })
describe("cashaddr prefix detection", () => { describe('cashaddr prefix detection', () => {
it("should return the same result for detectAddressFormat", () => { it('should return the same result for detectAddressFormat', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.detectAddressFormat(address) bchjs.Address.detectAddressFormat(address)
@@ -658,7 +658,7 @@ describe("#address.js", () => {
) )
) )
}) })
it("should return the same result for detectAddressNetwork", () => { it('should return the same result for detectAddressNetwork', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.detectAddressNetwork(address) bchjs.Address.detectAddressNetwork(address)
@@ -676,7 +676,7 @@ describe("#address.js", () => {
) )
) )
}) })
it("should return the same result for detectAddressType", () => { it('should return the same result for detectAddressType', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.detectAddressType(address) bchjs.Address.detectAddressType(address)
@@ -694,7 +694,7 @@ describe("#address.js", () => {
) )
) )
}) })
it("should return the same result for toLegacyAddress", () => { it('should return the same result for toLegacyAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.toLegacyAddress(address) bchjs.Address.toLegacyAddress(address)
@@ -710,7 +710,7 @@ describe("#address.js", () => {
REGTEST_ADDRESSES.map(address => bchjs.Address.toLegacyAddress(address)) REGTEST_ADDRESSES.map(address => bchjs.Address.toLegacyAddress(address))
) )
}) })
it("should return the same result for isLegacyAddress", () => { it('should return the same result for isLegacyAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isLegacyAddress(address) bchjs.Address.isLegacyAddress(address)
@@ -726,7 +726,7 @@ describe("#address.js", () => {
REGTEST_ADDRESSES.map(address => bchjs.Address.isLegacyAddress(address)) REGTEST_ADDRESSES.map(address => bchjs.Address.isLegacyAddress(address))
) )
}) })
it("should return the same result for isCashAddress", () => { it('should return the same result for isCashAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isCashAddress(address) bchjs.Address.isCashAddress(address)
@@ -740,7 +740,7 @@ describe("#address.js", () => {
REGTEST_ADDRESSES.map(address => bchjs.Address.isCashAddress(address)) REGTEST_ADDRESSES.map(address => bchjs.Address.isCashAddress(address))
) )
}) })
it("should return the same result for isMainnetAddress", () => { it('should return the same result for isMainnetAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isMainnetAddress(address) bchjs.Address.isMainnetAddress(address)
@@ -758,7 +758,7 @@ describe("#address.js", () => {
) )
) )
}) })
it("should return the same result for isTestnetAddress", () => { it('should return the same result for isTestnetAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isTestnetAddress(address) bchjs.Address.isTestnetAddress(address)
@@ -776,7 +776,7 @@ describe("#address.js", () => {
) )
) )
}) })
it("should return the same result for isP2PKHAddress", () => { it('should return the same result for isP2PKHAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isP2PKHAddress(address) bchjs.Address.isP2PKHAddress(address)
@@ -790,7 +790,7 @@ describe("#address.js", () => {
REGTEST_ADDRESSES.map(address => bchjs.Address.isP2PKHAddress(address)) REGTEST_ADDRESSES.map(address => bchjs.Address.isP2PKHAddress(address))
) )
}) })
it("should return the same result for isP2SHAddress", () => { it('should return the same result for isP2SHAddress', () => {
assert.deepEqual( assert.deepEqual(
CASHADDR_ADDRESSES_NO_PREFIX.map(address => CASHADDR_ADDRESSES_NO_PREFIX.map(address =>
bchjs.Address.isP2SHAddress(address) bchjs.Address.isP2SHAddress(address)
@@ -806,102 +806,102 @@ describe("#address.js", () => {
}) })
}) })
describe("#detectAddressFormat", () => { describe('#detectAddressFormat', () => {
LEGACY_ADDRESSES.forEach(address => { LEGACY_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy base58Check address`, () => { it(`should detect ${address} is a legacy base58Check address`, () => {
const isBase58Check = bchjs.Address.detectAddressFormat(address) const isBase58Check = bchjs.Address.detectAddressFormat(address)
assert.equal(isBase58Check, "legacy") assert.equal(isBase58Check, 'legacy')
}) })
}) })
CASHADDR_ADDRESSES.forEach(address => { CASHADDR_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy cashaddr address`, () => { it(`should detect ${address} is a legacy cashaddr address`, () => {
const isCashaddr = bchjs.Address.detectAddressFormat(address) const isCashaddr = bchjs.Address.detectAddressFormat(address)
assert.equal(isCashaddr, "cashaddr") assert.equal(isCashaddr, 'cashaddr')
}) })
}) })
REGTEST_ADDRESSES.forEach(address => { REGTEST_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy cashaddr address`, () => { it(`should detect ${address} is a legacy cashaddr address`, () => {
const isCashaddr = bchjs.Address.detectAddressFormat(address) const isCashaddr = bchjs.Address.detectAddressFormat(address)
assert.equal(isCashaddr, "cashaddr") assert.equal(isCashaddr, 'cashaddr')
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressFormat() bchjs.Address.detectAddressFormat()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressFormat("some invalid address") bchjs.Address.detectAddressFormat('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#detectAddressNetwork", () => { describe('#detectAddressNetwork', () => {
MAINNET_ADDRESSES.forEach(address => { MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnet = bchjs.Address.detectAddressNetwork(address) const isMainnet = bchjs.Address.detectAddressNetwork(address)
assert.equal(isMainnet, "mainnet") assert.equal(isMainnet, 'mainnet')
}) })
}) })
TESTNET_ADDRESSES.forEach(address => { TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = bchjs.Address.detectAddressNetwork(address) const isTestnet = bchjs.Address.detectAddressNetwork(address)
assert.equal(isTestnet, "testnet") assert.equal(isTestnet, 'testnet')
}) })
}) })
REGTEST_ADDRESSES.forEach(address => { REGTEST_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = bchjs.Address.detectAddressNetwork(address) const isTestnet = bchjs.Address.detectAddressNetwork(address)
assert.equal(isTestnet, "regtest") assert.equal(isTestnet, 'regtest')
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressNetwork() bchjs.Address.detectAddressNetwork()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressNetwork("some invalid address") bchjs.Address.detectAddressNetwork('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#detectAddressType", () => { describe('#detectAddressType', () => {
P2PKH_ADDRESSES.forEach(address => { P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2PKH address`, () => { it(`should detect ${address} is a P2PKH address`, () => {
const isP2PKH = bchjs.Address.detectAddressType(address) const isP2PKH = bchjs.Address.detectAddressType(address)
assert.equal(isP2PKH, "p2pkh") assert.equal(isP2PKH, 'p2pkh')
}) })
}) })
P2SH_ADDRESSES.forEach(address => { P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2SH address`, () => { it(`should detect ${address} is a P2SH address`, () => {
const isP2SH = bchjs.Address.detectAddressType(address) const isP2SH = bchjs.Address.detectAddressType(address)
assert.equal(isP2SH, "p2sh") assert.equal(isP2SH, 'p2sh')
}) })
}) })
describe("errors", () => { describe('errors', () => {
it("should fail when called with an invalid address", () => { it('should fail when called with an invalid address', () => {
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressType() bchjs.Address.detectAddressType()
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
assert.throws(() => { assert.throws(() => {
bchjs.Address.detectAddressType("some invalid address") bchjs.Address.detectAddressType('some invalid address')
}, bchjs.BitcoinCash.InvalidAddressError) }, bchjs.BitcoinCash.InvalidAddressError)
}) })
}) })
}) })
describe("#fromXPub", () => { describe('#fromXPub', () => {
XPUBS.forEach((xpub, i) => { XPUBS.forEach((xpub, i) => {
xpub.addresses.forEach((address, j) => { xpub.addresses.forEach((address, j) => {
it(`generate public external change address ${j} for ${xpub.xpub}`, () => { it(`generate public external change address ${j} for ${xpub.xpub}`, () => {
@@ -911,12 +911,12 @@ describe("#address.js", () => {
}) })
}) })
describe("#fromOutputScript", () => { describe('#fromOutputScript', () => {
it("generate address from output script", () => { it('generate address from output script', () => {
const script = bchjs.Script.encode([ const script = bchjs.Script.encode([
Buffer.from("BOX", "ascii"), Buffer.from('BOX', 'ascii'),
bchjs.Script.opcodes.OP_CAT, bchjs.Script.opcodes.OP_CAT,
Buffer.from("BITBOX", "ascii"), Buffer.from('BITBOX', 'ascii'),
bchjs.Script.opcodes.OP_EQUAL bchjs.Script.opcodes.OP_EQUAL
]) ])
+26 -26
View File
@@ -1,11 +1,11 @@
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
// Mocks // Mocks
const fixtures = require("./fixtures/bitcoincash.json") const fixtures = require('./fixtures/bitcoincash.json')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
let bchjs let bchjs
@@ -25,13 +25,13 @@ let bchjs
// * confirm xpriv generates WIF // * confirm xpriv generates WIF
// 6. More error test cases. // 6. More error test cases.
describe("#BitcoinCash", () => { describe('#BitcoinCash', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("price conversion", () => { describe('price conversion', () => {
it("should exercise toBitcoinCash", () => { it('should exercise toBitcoinCash', () => {
fixtures.conversion.toBCH.satoshis.forEach(satoshi => { fixtures.conversion.toBCH.satoshis.forEach(satoshi => {
it(`should convert ${satoshi[0]} Satoshis to ${satoshi[1]} $BCH`, () => { it(`should convert ${satoshi[0]} Satoshis to ${satoshi[1]} $BCH`, () => {
assert.equal(bchjs.BitcoinCash.toBitcoinCash(satoshi[0]), satoshi[1]) assert.equal(bchjs.BitcoinCash.toBitcoinCash(satoshi[0]), satoshi[1])
@@ -57,7 +57,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
it("should exercise toSatoshi", () => { it('should exercise toSatoshi', () => {
fixtures.conversion.toSatoshi.bch.forEach(bch => { fixtures.conversion.toSatoshi.bch.forEach(bch => {
it(`should convert ${bch[0]} $BCH to ${bch[1]} Satoshis`, () => { it(`should convert ${bch[0]} $BCH to ${bch[1]} Satoshis`, () => {
assert.equal(bchjs.BitcoinCash.toSatoshi(bch[0]), bch[1]) assert.equal(bchjs.BitcoinCash.toSatoshi(bch[0]), bch[1])
@@ -83,7 +83,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
it("should exercise satsToBits", () => { it('should exercise satsToBits', () => {
fixtures.conversion.satsToBits.bch.forEach(bch => { fixtures.conversion.satsToBits.bch.forEach(bch => {
it(`should convert ${bch[0]} BCH to ${bch[1]} bits`, () => { it(`should convert ${bch[0]} BCH to ${bch[1]} bits`, () => {
assert.equal( assert.equal(
@@ -118,8 +118,8 @@ describe("#BitcoinCash", () => {
// }); // });
}) })
describe("sign and verify messages", () => { describe('sign and verify messages', () => {
it("should exercise signMessageWithPrivKey", () => { it('should exercise signMessageWithPrivKey', () => {
fixtures.signatures.sign.forEach(sign => { fixtures.signatures.sign.forEach(sign => {
it(`should sign a message w/ ${sign.network} ${sign.privateKeyWIF}`, () => { it(`should sign a message w/ ${sign.network} ${sign.privateKeyWIF}`, () => {
const privateKeyWIF = sign.privateKeyWIF const privateKeyWIF = sign.privateKeyWIF
@@ -133,7 +133,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
it("shoudl exercise verifyMessage", () => { it('shoudl exercise verifyMessage', () => {
fixtures.signatures.verify.forEach(sign => { fixtures.signatures.verify.forEach(sign => {
it(`should verify a valid signed message from ${sign.network} cashaddr address ${sign.address}`, () => { it(`should verify a valid signed message from ${sign.network} cashaddr address ${sign.address}`, () => {
assert.equal( assert.equal(
@@ -147,7 +147,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
it("should verify legacy addresses", () => { it('should verify legacy addresses', () => {
fixtures.signatures.verify.forEach(sign => { fixtures.signatures.verify.forEach(sign => {
const legacyAddress = bchjs.Address.toLegacyAddress(sign.address) const legacyAddress = bchjs.Address.toLegacyAddress(sign.address)
it(`should verify a valid signed message from ${sign.network} legacy address ${legacyAddress}`, () => { it(`should verify a valid signed message from ${sign.network} legacy address ${legacyAddress}`, () => {
@@ -170,7 +170,7 @@ describe("#BitcoinCash", () => {
bchjs.BitcoinCash.verifyMessage( bchjs.BitcoinCash.verifyMessage(
sign.address, sign.address,
sign.signature, sign.signature,
"nope" 'nope'
), ),
false false
) )
@@ -179,8 +179,8 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("encode and decode to base58Check", () => { describe('encode and decode to base58Check', () => {
describe("#encodeBase58Check", () => { describe('#encodeBase58Check', () => {
fixtures.encodeBase58Check.forEach((base58Check, i) => { fixtures.encodeBase58Check.forEach((base58Check, i) => {
it(`encode ${base58Check.hex} as base58Check ${base58Check.base58Check}`, () => { it(`encode ${base58Check.hex} as base58Check ${base58Check.base58Check}`, () => {
assert.equal( assert.equal(
@@ -191,7 +191,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("#decodeBase58Check", () => { describe('#decodeBase58Check', () => {
fixtures.encodeBase58Check.forEach((base58Check, i) => { fixtures.encodeBase58Check.forEach((base58Check, i) => {
it(`decode ${base58Check.base58Check} as ${base58Check.hex}`, () => { it(`decode ${base58Check.base58Check} as ${base58Check.hex}`, () => {
assert.equal( assert.equal(
@@ -203,8 +203,8 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("encode and decode BIP21 urls", () => { describe('encode and decode BIP21 urls', () => {
describe("#encodeBIP21", () => { describe('#encodeBIP21', () => {
fixtures.bip21.valid.forEach((bip21, i) => { fixtures.bip21.valid.forEach((bip21, i) => {
it(`encode ${bip21.address} as url`, () => { it(`encode ${bip21.address} as url`, () => {
const url = bchjs.BitcoinCash.encodeBIP21( const url = bchjs.BitcoinCash.encodeBIP21(
@@ -226,7 +226,7 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("#decodeBIP21", () => { describe('#decodeBIP21', () => {
fixtures.bip21.valid.forEach((bip21, i) => { fixtures.bip21.valid.forEach((bip21, i) => {
it(`decodes ${bip21.url}`, () => { it(`decodes ${bip21.url}`, () => {
const decoded = bchjs.BitcoinCash.decodeBIP21(bip21.url) const decoded = bchjs.BitcoinCash.decodeBIP21(bip21.url)
@@ -252,9 +252,9 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("#getByteCount", () => { describe('#getByteCount', () => {
fixtures.getByteCount.forEach(fixture => { fixtures.getByteCount.forEach(fixture => {
it(`get byte count`, () => { it('get byte count', () => {
const byteCount = bchjs.BitcoinCash.getByteCount( const byteCount = bchjs.BitcoinCash.getByteCount(
fixture.inputs, fixture.inputs,
fixture.outputs fixture.outputs
@@ -264,8 +264,8 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("#bip38", () => { describe('#bip38', () => {
describe("#encryptBIP38", () => { describe('#encryptBIP38', () => {
fixtures.bip38.encrypt.mainnet.forEach(fixture => { fixtures.bip38.encrypt.mainnet.forEach(fixture => {
it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on mainnet`, () => { it(`BIP 38 encrypt wif ${fixture.wif} with password ${fixture.password} on mainnet`, () => {
const encryptedKey = bchjs.BitcoinCash.encryptBIP38( const encryptedKey = bchjs.BitcoinCash.encryptBIP38(
@@ -287,13 +287,13 @@ describe("#BitcoinCash", () => {
}) })
}) })
describe("#decryptBIP38", () => { describe('#decryptBIP38', () => {
fixtures.bip38.decrypt.mainnet.forEach(fixture => { fixtures.bip38.decrypt.mainnet.forEach(fixture => {
it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on mainnet`, () => { it(`BIP 38 decrypt encrypted key ${fixture.encryptedKey} on mainnet`, () => {
const wif = bchjs.BitcoinCash.decryptBIP38( const wif = bchjs.BitcoinCash.decryptBIP38(
fixture.encryptedKey, fixture.encryptedKey,
fixture.password, fixture.password,
"mainnet" 'mainnet'
) )
assert.equal(wif, fixture.wif) assert.equal(wif, fixture.wif)
}) })
@@ -304,7 +304,7 @@ describe("#BitcoinCash", () => {
const wif = bchjs.BitcoinCash.decryptBIP38( const wif = bchjs.BitcoinCash.decryptBIP38(
fixture.encryptedKey, fixture.encryptedKey,
fixture.password, fixture.password,
"testnet" 'testnet'
) )
assert.equal(wif, fixture.wif) assert.equal(wif, fixture.wif)
}) })
+119 -116
View File
@@ -1,70 +1,70 @@
const assert = require("assert") const assert = require('assert')
const assert2 = require("chai").assert const assert2 = require('chai').assert
const axios = require("axios") const axios = require('axios')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const sinon = require("sinon") const sinon = require('sinon')
const mockData = require("./fixtures/blockchain-mock") const mockData = require('./fixtures/blockchain-mock')
describe("#Blockchain", () => { describe('#Blockchain', () => {
describe("#getBestBlockHash", () => { describe('#getBestBlockHash', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get best block hash", done => { it('should get best block hash', done => {
const resolved = new Promise(r => const resolved = new Promise(resolve =>
r({ resolve({
data: data:
"0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d" '0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d'
}) })
) )
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBestBlockHash() bchjs.Blockchain.getBestBlockHash()
.then(result => { .then(result => {
const hash = const hash =
"0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d" '0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d'
assert.equal(hash, result) assert.strictEqual(hash, result)
}) })
.then(done, done) .then(done, done)
}) })
}) })
describe("#getBlock", () => { describe('#getBlock', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = { const data = {
hash: "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
confirmations: 526807, confirmations: 526807,
size: 216, size: 216,
height: 1000, height: 1000,
version: 1, version: 1,
versionHex: "00000001", versionHex: '00000001',
merkleroot: merkleroot:
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33", 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
tx: ["fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33"], tx: ['fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'],
time: 1232346882, time: 1232346882,
mediantime: 1232344831, mediantime: 1232344831,
nonce: 2595206198, nonce: 2595206198,
bits: "1d00ffff", bits: '1d00ffff',
difficulty: 1, difficulty: 1,
chainwork: chainwork:
"000000000000000000000000000000000000000000000000000003e903e903e9", '000000000000000000000000000000000000000000000000000003e903e903e9',
previousblockhash: previousblockhash:
"0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d", '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',
nextblockhash: nextblockhash:
"00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6" '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6'
} }
it("should get block by hash", done => { it('should get block by hash', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlock( bchjs.Blockchain.getBlock(
"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09" '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09'
) )
.then(result => { .then(result => {
assert.deepEqual(data, result) assert.deepEqual(data, result)
@@ -73,30 +73,30 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getBlockchainInfo", () => { describe('#getBlockchainInfo', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = { const data = {
chain: "main", chain: 'main',
blocks: 527810, blocks: 527810,
headers: 527810, headers: 527810,
bestblockhash: bestblockhash:
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0", '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',
difficulty: 576023394804.6666, difficulty: 576023394804.6666,
mediantime: 1524878499, mediantime: 1524878499,
verificationprogress: 0.9999990106793685, verificationprogress: 0.9999990106793685,
chainwork: chainwork:
"00000000000000000000000000000000000000000096da5b040913fa09249b4e", '00000000000000000000000000000000000000000096da5b040913fa09249b4e',
pruned: false, pruned: false,
softforks: [ softforks: [
{ id: "bip34", version: 2, reject: [Object] }, { id: 'bip34', version: 2, reject: [Object] },
{ id: "bip66", version: 3, reject: [Object] }, { id: 'bip66', version: 3, reject: [Object] },
{ id: "bip65", version: 4, reject: [Object] } { id: 'bip65', version: 4, reject: [Object] }
], ],
bip9_softforks: { bip9_softforks: {
csv: { csv: {
status: "active", status: 'active',
startTime: 1462060800, startTime: 1462060800,
timeout: 1493596800, timeout: 1493596800,
since: 419328 since: 419328
@@ -104,9 +104,9 @@ describe("#Blockchain", () => {
} }
} }
it("should get blockchain info", done => { it('should get blockchain info', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockchainInfo() bchjs.Blockchain.getBlockchainInfo()
.then(result => { .then(result => {
@@ -116,15 +116,15 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getBlockCount", () => { describe('#getBlockCount', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = 527810 const data = 527810
it("should get block count", done => { it('should get block count', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockCount() bchjs.Blockchain.getBlockCount()
.then(result => { .then(result => {
@@ -134,16 +134,16 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getBlockHash", () => { describe('#getBlockHash', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = const data =
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0" '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0'
it("should get block hash by height", done => { it('should get block hash by height', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockHash(527810) bchjs.Blockchain.getBlockHash(527810)
.then(result => { .then(result => {
@@ -153,35 +153,35 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getBlockHeader", () => { describe('#getBlockHeader', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = { const data = {
hash: "000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0", hash: '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',
confirmations: 1, confirmations: 1,
height: 527810, height: 527810,
version: 536870912, version: 536870912,
versionHex: "20000000", versionHex: '20000000',
merkleroot: merkleroot:
"9298432bbebe4638456aa19cb7ef91639da87668a285d88d0ecd6080424d223b", '9298432bbebe4638456aa19cb7ef91639da87668a285d88d0ecd6080424d223b',
time: 1524881438, time: 1524881438,
mediantime: 1524878499, mediantime: 1524878499,
nonce: 3326843941, nonce: 3326843941,
bits: "1801e8a5", bits: '1801e8a5',
difficulty: 576023394804.6666, difficulty: 576023394804.6666,
chainwork: chainwork:
"00000000000000000000000000000000000000000096da5b040913fa09249b4e", '00000000000000000000000000000000000000000096da5b040913fa09249b4e',
previousblockhash: previousblockhash:
"000000000000000000b33251708bc7a7b4540e61880d8c376e8e2db6a19a4789" '000000000000000000b33251708bc7a7b4540e61880d8c376e8e2db6a19a4789'
} }
it("should get block header by hash", done => { it('should get block header by hash', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getBlockHeader( bchjs.Blockchain.getBlockHeader(
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0", '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',
true true
) )
.then(result => { .then(result => {
@@ -191,15 +191,15 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getDifficulty", () => { describe('#getDifficulty', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = "577528469277.1339" const data = '577528469277.1339'
it("should get difficulty", done => { it('should get difficulty', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getDifficulty() bchjs.Blockchain.getDifficulty()
.then(result => { .then(result => {
@@ -209,18 +209,18 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getMempoolAncestors", () => { describe('#getMempoolAncestors', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = "Transaction not in mempool" const data = 'Transaction not in mempool'
it("should get mempool ancestors", done => { it('should get mempool ancestors', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolAncestors( bchjs.Blockchain.getMempoolAncestors(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88", 'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',
true true
) )
.then(result => { .then(result => {
@@ -230,20 +230,20 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getMempoolDescendants", () => { describe('#getMempoolDescendants', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = { const data = {
result: "Transaction not in mempool" result: 'Transaction not in mempool'
} }
it("should get mempool descendants", done => { it('should get mempool descendants', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolDescendants( bchjs.Blockchain.getMempoolDescendants(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88", 'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',
true true
) )
.then(result => { .then(result => {
@@ -253,20 +253,20 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getMempoolEntry", () => { describe('#getMempoolEntry', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = { const data = {
result: "Transaction not in mempool" result: 'Transaction not in mempool'
} }
it("should get mempool entry", done => { it('should get mempool entry', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolEntry( bchjs.Blockchain.getMempoolEntry(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88" 'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88'
) )
.then(result => { .then(result => {
assert.deepEqual(data, result) assert.deepEqual(data, result)
@@ -275,7 +275,7 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getMempoolInfo", () => { describe('#getMempoolInfo', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
@@ -289,9 +289,9 @@ describe("#Blockchain", () => {
} }
} }
it("should get mempool info", done => { it('should get mempool info', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getMempoolInfo() bchjs.Blockchain.getMempoolInfo()
.then(result => { .then(result => {
@@ -301,7 +301,7 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getRawMempool", () => { describe('#getRawMempool', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
@@ -310,7 +310,7 @@ describe("#Blockchain", () => {
transactions: [ transactions: [
{ {
txid: txid:
"ab36d68dd0a618592fe34e4a898e8beeeb4049133547dbb16f9338384084af96", 'ab36d68dd0a618592fe34e4a898e8beeeb4049133547dbb16f9338384084af96',
size: 191, size: 191,
fee: 0.00047703, fee: 0.00047703,
modifiedfee: 0.00047703, modifiedfee: 0.00047703,
@@ -330,9 +330,9 @@ describe("#Blockchain", () => {
} }
} }
it("should get mempool info", done => { it('should get mempool info', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.getRawMempool() bchjs.Blockchain.getRawMempool()
.then(result => { .then(result => {
@@ -342,7 +342,7 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#getTxOut", () => { describe('#getTxOut', () => {
// TODO finish this test // TODO finish this test
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
@@ -351,63 +351,66 @@ describe("#Blockchain", () => {
// result: {} // result: {}
// } // }
it("should throw an error for improper txid.", async () => { it('should throw an error for improper txid.', async () => {
try { try {
await bchjs.Blockchain.getTxOut("badtxid") await bchjs.Blockchain.getTxOut('badtxid')
} catch (err) { } catch (err) {
assert2.include(err.message, "txid needs to be a proper transaction ID") assert2.include(
err.message,
'txid needs to be a proper transaction ID'
)
} }
}) })
it("should throw an error if no vout value is provided.", async () => { it('should throw an error if no vout value is provided.', async () => {
try { try {
await bchjs.Blockchain.getTxOut( await bchjs.Blockchain.getTxOut(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88" 'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88'
) )
} catch (err) { } catch (err) {
assert2.include(err.message, "n must be an integer") assert2.include(err.message, 'n must be an integer')
} }
}) })
it("should throw an error if include_mempool is not a boolean", async () => { it('should throw an error if include_mempool is not a boolean', async () => {
try { try {
await bchjs.Blockchain.getTxOut( await bchjs.Blockchain.getTxOut(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88", 'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',
0, 0,
"bad value" 'bad value'
) )
} catch (err) { } catch (err) {
assert2.include( assert2.include(
err.message, err.message,
"include_mempool input must be of type boolean" 'includeMempool input must be of type boolean'
) )
} }
}) })
it("should get information on an unspent tx", async () => { it('should get information on an unspent tx', async () => {
sandbox.stub(axios, "post").resolves({ data: mockData.txOutUnspent }) sandbox.stub(axios, 'post').resolves({ data: mockData.txOutUnspent })
const result = await bchjs.Blockchain.getTxOut( const result = await bchjs.Blockchain.getTxOut(
"62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8", '62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8',
0, 0,
true true
) )
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert2.hasAllKeys(result, [ assert2.hasAllKeys(result, [
"bestblock", 'bestblock',
"confirmations", 'confirmations',
"value", 'value',
"scriptPubKey", 'scriptPubKey',
"coinbase" 'coinbase'
]) ])
}) })
it("should get information on a spent tx", async () => { it('should get information on a spent tx', async () => {
sandbox.stub(axios, "post").resolves({ data: null }) sandbox.stub(axios, 'post').resolves({ data: null })
const result = await bchjs.Blockchain.getTxOut( const result = await bchjs.Blockchain.getTxOut(
"87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871", '87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871',
0, 0,
true true
) )
@@ -417,7 +420,7 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#preciousBlock", () => { describe('#preciousBlock', () => {
// TODO finish this test // TODO finish this test
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
@@ -426,9 +429,9 @@ describe("#Blockchain", () => {
result: {} result: {}
} }
it("should get TODO", done => { it('should get TODO', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.preciousBlock() bchjs.Blockchain.preciousBlock()
.then(result => { .then(result => {
@@ -438,15 +441,15 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#pruneBlockchain", () => { describe('#pruneBlockchain', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = "Cannot prune blocks because node is not in prune mode." const data = 'Cannot prune blocks because node is not in prune mode.'
it("should prune blockchain", done => { it('should prune blockchain', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved) sandbox.stub(axios, 'post').returns(resolved)
bchjs.Blockchain.pruneBlockchain(507) bchjs.Blockchain.pruneBlockchain(507)
.then(result => { .then(result => {
@@ -456,15 +459,15 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#verifyChain", () => { describe('#verifyChain', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = true const data = true
it("should verify blockchain", done => { it('should verify blockchain', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.verifyChain(3, 6) bchjs.Blockchain.verifyChain(3, 6)
.then(result => { .then(result => {
@@ -474,17 +477,17 @@ describe("#Blockchain", () => {
}) })
}) })
describe("#verifyTxOutProof", () => { describe('#verifyTxOutProof', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
const data = "proof must be hexadecimal string (not '')" const data = "proof must be hexadecimal string (not '')"
it("should verify utxo proof", done => { it('should verify utxo proof', done => {
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Blockchain.verifyTxOutProof("3") bchjs.Blockchain.verifyTxOutProof('3')
.then(result => { .then(result => {
assert.deepEqual(data, result) assert.deepEqual(data, result)
}) })
+13 -13
View File
@@ -1,31 +1,31 @@
const assert = require("assert") const assert = require('assert')
const axios = require("axios") const axios = require('axios')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const sinon = require("sinon") const sinon = require('sinon')
describe("#Control", () => { describe('#Control', () => {
describe("#getNetworkInfo", () => { describe('#getNetworkInfo', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get info", done => { it('should get info', done => {
const data = { const data = {
version: 170000, version: 170000,
protocolversion: 70015, protocolversion: 70015,
blocks: 527813, blocks: 527813,
timeoffset: 0, timeoffset: 0,
connections: 21, connections: 21,
proxy: "", proxy: '',
difficulty: 581086703759.5878, difficulty: 581086703759.5878,
testnet: false, testnet: false,
paytxfee: 0, paytxfee: 0,
relayfee: 0.00001, relayfee: 0.00001,
errors: "" errors: ''
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Control.getNetworkInfo() bchjs.Control.getNetworkInfo()
.then(result => { .then(result => {
@@ -35,12 +35,12 @@ describe("#Control", () => {
}) })
}) })
describe("#getMemoryInfo", () => { describe('#getMemoryInfo', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get memory info", done => { it('should get memory info', done => {
const data = { const data = {
locked: { locked: {
used: 0, used: 0,
@@ -52,7 +52,7 @@ describe("#Control", () => {
} }
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Control.getMemoryInfo() bchjs.Control.getMemoryInfo()
.then(result => { .then(result => {
+35 -35
View File
@@ -1,97 +1,97 @@
const fixtures = require("./fixtures/crypto.json") const fixtures = require('./fixtures/crypto.json')
const assert = require("assert") const assert = require('assert')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const Buffer = require("safe-buffer").Buffer const Buffer = require('safe-buffer').Buffer
describe("#Crypto", () => { describe('#Crypto', () => {
describe("#sha256", () => { describe('#sha256', () => {
fixtures.sha256.forEach(fixture => { fixtures.sha256.forEach(fixture => {
it(`should create SHA256Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => { it(`should create SHA256Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const sha256Hash = bchjs.Crypto.sha256(data).toString("hex") const sha256Hash = bchjs.Crypto.sha256(data).toString('hex')
assert.equal(sha256Hash, fixture.hash) assert.equal(sha256Hash, fixture.hash)
}) })
it(`should create 64 character SHA256Hash hex encoded`, () => { it('should create 64 character SHA256Hash hex encoded', () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const sha256Hash = bchjs.Crypto.sha256(data).toString("hex") const sha256Hash = bchjs.Crypto.sha256(data).toString('hex')
assert.equal(sha256Hash.length, 64) assert.equal(sha256Hash.length, 64)
}) })
}) })
}) })
describe("#ripemd160", () => { describe('#ripemd160', () => {
fixtures.ripemd160.forEach(fixture => { fixtures.ripemd160.forEach(fixture => {
it(`should create RIPEMD160Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => { it(`should create RIPEMD160Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const ripemd160 = bchjs.Crypto.ripemd160(data).toString("hex") const ripemd160 = bchjs.Crypto.ripemd160(data).toString('hex')
assert.equal(ripemd160, fixture.hash) assert.equal(ripemd160, fixture.hash)
}) })
it(`should create 64 character RIPEMD160Hash hex encoded`, () => { it('should create 64 character RIPEMD160Hash hex encoded', () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const ripemd160 = bchjs.Crypto.ripemd160(data).toString("hex") const ripemd160 = bchjs.Crypto.ripemd160(data).toString('hex')
assert.equal(ripemd160.length, 40) assert.equal(ripemd160.length, 40)
}) })
}) })
}) })
describe("#hash256", () => { describe('#hash256', () => {
fixtures.hash256.forEach(fixture => { fixtures.hash256.forEach(fixture => {
it(`should create double SHA256 Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => { it(`should create double SHA256 Hash hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const hash256 = bchjs.Crypto.hash256(data).toString("hex") const hash256 = bchjs.Crypto.hash256(data).toString('hex')
assert.equal(hash256, fixture.hash) assert.equal(hash256, fixture.hash)
}) })
it(`should create 64 character SHA256 Hash hex encoded`, () => { it('should create 64 character SHA256 Hash hex encoded', () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const hash256 = bchjs.Crypto.hash256(data).toString("hex") const hash256 = bchjs.Crypto.hash256(data).toString('hex')
assert.equal(hash256.length, 64) assert.equal(hash256.length, 64)
}) })
}) })
}) })
describe("#hash160", () => { describe('#hash160', () => {
fixtures.hash160.forEach(fixture => { fixtures.hash160.forEach(fixture => {
it(`should create RIPEMD160(SHA256()) hex encoded ${fixture.hash} from ${fixture.hex}`, () => { it(`should create RIPEMD160(SHA256()) hex encoded ${fixture.hash} from ${fixture.hex}`, () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const hash160 = bchjs.Crypto.hash160(data).toString("hex") const hash160 = bchjs.Crypto.hash160(data).toString('hex')
assert.equal(hash160, fixture.hash) assert.equal(hash160, fixture.hash)
}) })
it(`should create 64 character SHA256Hash hex encoded`, () => { it('should create 64 character SHA256Hash hex encoded', () => {
const data = Buffer.from(fixture.hex, "hex") const data = Buffer.from(fixture.hex, 'hex')
const hash160 = bchjs.Crypto.hash160(data).toString("hex") const hash160 = bchjs.Crypto.hash160(data).toString('hex')
assert.equal(hash160.length, 40) assert.equal(hash160.length, 40)
}) })
}) })
}) })
describe("#randomBytes", () => { describe('#randomBytes', () => {
for (let i = 0; i < 6; i++) { for (let i = 0; i < 6; i++) {
it("should return 16 bytes of entropy hex encoded", () => { it('should return 16 bytes of entropy hex encoded', () => {
const entropy = bchjs.Crypto.randomBytes(16) const entropy = bchjs.Crypto.randomBytes(16)
assert.equal(Buffer.byteLength(entropy), 16) assert.equal(Buffer.byteLength(entropy), 16)
}) })
it("should return 20 bytes of entropy hex encoded", () => { it('should return 20 bytes of entropy hex encoded', () => {
const entropy = bchjs.Crypto.randomBytes(20) const entropy = bchjs.Crypto.randomBytes(20)
assert.equal(Buffer.byteLength(entropy), 20) assert.equal(Buffer.byteLength(entropy), 20)
}) })
it("should return 24 bytes of entropy hex encoded", () => { it('should return 24 bytes of entropy hex encoded', () => {
const entropy = bchjs.Crypto.randomBytes(24) const entropy = bchjs.Crypto.randomBytes(24)
assert.equal(Buffer.byteLength(entropy), 24) assert.equal(Buffer.byteLength(entropy), 24)
}) })
it("should return 28 bytes of entropy hex encoded", () => { it('should return 28 bytes of entropy hex encoded', () => {
const entropy = bchjs.Crypto.randomBytes(28) const entropy = bchjs.Crypto.randomBytes(28)
assert.equal(Buffer.byteLength(entropy), 28) assert.equal(Buffer.byteLength(entropy), 28)
}) })
it("should return 32 bytes of entropy hex encoded", () => { it('should return 32 bytes of entropy hex encoded', () => {
const entropy = bchjs.Crypto.randomBytes(32) const entropy = bchjs.Crypto.randomBytes(32)
assert.equal(Buffer.byteLength(entropy), 32) assert.equal(Buffer.byteLength(entropy), 32)
}) })
+28 -28
View File
@@ -1,25 +1,25 @@
// Public npm libraries. // Public npm libraries.
const assert = require("assert") const assert = require('assert')
const Buffer = require("safe-buffer").Buffer const Buffer = require('safe-buffer').Buffer
// Mocks // Mocks
const fixtures = require("./fixtures/ecpair.json") const fixtures = require('./fixtures/ecpair.json')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
let bchjs let bchjs
describe("#ECPair", () => { describe('#ECPair', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#fromWIF", () => { describe('#fromWIF', () => {
fixtures.fromWIF.forEach(fixture => { fixtures.fromWIF.forEach(fixture => {
it(`should create ECPair from WIF ${fixture.privateKeyWIF}`, () => { it(`should create ECPair from WIF ${fixture.privateKeyWIF}`, () => {
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF) const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
assert.equal(typeof ecpair, "object") assert.equal(typeof ecpair, 'object')
}) })
it(`should get ${fixture.legacy} legacy address`, () => { it(`should get ${fixture.legacy} legacy address`, () => {
@@ -42,7 +42,7 @@ describe("#ECPair", () => {
}) })
}) })
describe("#toWIF", () => { describe('#toWIF', () => {
fixtures.toWIF.forEach(fixture => { fixtures.toWIF.forEach(fixture => {
it(`should get WIF ${fixture.privateKeyWIF} from ECPair`, () => { it(`should get WIF ${fixture.privateKeyWIF} from ECPair`, () => {
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF) const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
@@ -52,32 +52,32 @@ describe("#ECPair", () => {
}) })
}) })
describe("#fromPublicKey", () => { describe('#fromPublicKey', () => {
fixtures.fromPublicKey.forEach(fixture => { fixtures.fromPublicKey.forEach(fixture => {
it(`should create ECPair from public key buffer`, () => { it('should create ECPair from public key buffer', () => {
const ecpair = bchjs.ECPair.fromPublicKey( const ecpair = bchjs.ECPair.fromPublicKey(
Buffer.from(fixture.pubkeyHex, "hex") Buffer.from(fixture.pubkeyHex, 'hex')
) )
assert.equal(typeof ecpair, "object") assert.equal(typeof ecpair, 'object')
}) })
it(`should get ${fixture.legacy} legacy address`, () => { it(`should get ${fixture.legacy} legacy address`, () => {
const ecpair = bchjs.ECPair.fromPublicKey( const ecpair = bchjs.ECPair.fromPublicKey(
Buffer.from(fixture.pubkeyHex, "hex") Buffer.from(fixture.pubkeyHex, 'hex')
) )
assert.equal(bchjs.HDNode.toLegacyAddress(ecpair), fixture.legacy) assert.equal(bchjs.HDNode.toLegacyAddress(ecpair), fixture.legacy)
}) })
it(`should get ${fixture.cashAddr} cash address`, () => { it(`should get ${fixture.cashAddr} cash address`, () => {
const ecpair = bchjs.ECPair.fromPublicKey( const ecpair = bchjs.ECPair.fromPublicKey(
Buffer.from(fixture.pubkeyHex, "hex") Buffer.from(fixture.pubkeyHex, 'hex')
) )
assert.equal(bchjs.HDNode.toCashAddress(ecpair), fixture.cashAddr) assert.equal(bchjs.HDNode.toCashAddress(ecpair), fixture.cashAddr)
}) })
it(`should get ${fixture.regtestAddr} cash address`, () => { it(`should get ${fixture.regtestAddr} cash address`, () => {
const ecpair = bchjs.ECPair.fromPublicKey( const ecpair = bchjs.ECPair.fromPublicKey(
Buffer.from(fixture.pubkeyHex, "hex") Buffer.from(fixture.pubkeyHex, 'hex')
) )
assert.equal( assert.equal(
bchjs.HDNode.toCashAddress(ecpair, true), bchjs.HDNode.toCashAddress(ecpair, true),
@@ -87,19 +87,19 @@ describe("#ECPair", () => {
}) })
}) })
describe("#toPublicKey", () => { describe('#toPublicKey', () => {
fixtures.toPublicKey.forEach(fixture => { fixtures.toPublicKey.forEach(fixture => {
it(`should create a public key buffer from an ECPair`, () => { it('should create a public key buffer from an ECPair', () => {
const ecpair = bchjs.ECPair.fromPublicKey( const ecpair = bchjs.ECPair.fromPublicKey(
Buffer.from(fixture.pubkeyHex, "hex") Buffer.from(fixture.pubkeyHex, 'hex')
) )
const pubkeyBuffer = bchjs.ECPair.toPublicKey(ecpair) const pubkeyBuffer = bchjs.ECPair.toPublicKey(ecpair)
assert.equal(typeof pubkeyBuffer, "object") assert.equal(typeof pubkeyBuffer, 'object')
}) })
}) })
}) })
describe("#toLegacyAddress", () => { describe('#toLegacyAddress', () => {
fixtures.toLegacyAddress.forEach(fixture => { fixtures.toLegacyAddress.forEach(fixture => {
it(`should create legacy address ${fixture.legacy} from an ECPair`, () => { it(`should create legacy address ${fixture.legacy} from an ECPair`, () => {
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF) const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
@@ -109,7 +109,7 @@ describe("#ECPair", () => {
}) })
}) })
describe("#toCashAddress", () => { describe('#toCashAddress', () => {
fixtures.toCashAddress.forEach(fixture => { fixtures.toCashAddress.forEach(fixture => {
it(`should create cash address ${fixture.cashAddr} from an ECPair`, () => { it(`should create cash address ${fixture.cashAddr} from an ECPair`, () => {
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF) const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
@@ -127,23 +127,23 @@ describe("#ECPair", () => {
}) })
}) })
describe("#sign", () => { describe('#sign', () => {
fixtures.sign.forEach(fixture => { fixtures.sign.forEach(fixture => {
it(`should sign 32 byte hash buffer`, () => { it('should sign 32 byte hash buffer', () => {
const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF) const ecpair = bchjs.ECPair.fromWIF(fixture.privateKeyWIF)
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex") const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), 'hex')
const signatureBuf = bchjs.ECPair.sign(ecpair, buf) const signatureBuf = bchjs.ECPair.sign(ecpair, buf)
assert.equal(typeof signatureBuf, "object") assert.equal(typeof signatureBuf, 'object')
}) })
}) })
}) })
describe("#verify", () => { describe('#verify', () => {
fixtures.verify.forEach(fixture => { fixtures.verify.forEach(fixture => {
it(`should verify signed 32 byte hash buffer`, () => { it('should verify signed 32 byte hash buffer', () => {
const ecpair1 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF1) const ecpair1 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF1)
// const ecpair2 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF2) // const ecpair2 = bchjs.ECPair.fromWIF(fixture.privateKeyWIF2)
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex") const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), 'hex')
const signature = bchjs.ECPair.sign(ecpair1, buf) const signature = bchjs.ECPair.sign(ecpair1, buf)
const verify = bchjs.ECPair.verify(ecpair1, buf, signature) const verify = bchjs.ECPair.verify(ecpair1, buf, signature)
assert.equal(verify, true) assert.equal(verify, true)
+145 -145
View File
@@ -1,275 +1,275 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const mockData = require("./fixtures/electrumx-mock") const mockData = require('./fixtures/electrumx-mock')
describe(`#ElectrumX`, () => { describe('#ElectrumX', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Electrumx.utxo(addr) await bchjs.Electrumx.utxo(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings` 'Input address must be a string or array of strings'
) )
} }
}) })
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.utxo }) sandbox.stub(axios, 'get').resolves({ data: mockData.utxo })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "height") assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], "tx_hash") assert.property(result.utxos[0], 'tx_hash')
assert.property(result.utxos[0], "tx_pos") assert.property(result.utxos[0], 'tx_pos')
assert.property(result.utxos[0], "value") assert.property(result.utxos[0], 'value')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.utxos }) sandbox.stub(axios, 'post').resolves({ data: mockData.utxos })
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.utxo(addr) const result = await bchjs.Electrumx.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "utxos") assert.property(result.utxos[0], 'utxos')
assert.isArray(result.utxos[0].utxos) assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], "address") assert.property(result.utxos[0], 'address')
assert.property(result.utxos[0].utxos[0], "height") assert.property(result.utxos[0].utxos[0], 'height')
assert.property(result.utxos[0].utxos[0], "tx_hash") assert.property(result.utxos[0].utxos[0], 'tx_hash')
assert.property(result.utxos[0].utxos[0], "tx_pos") assert.property(result.utxos[0].utxos[0], 'tx_pos')
assert.property(result.utxos[0].utxos[0], "value") assert.property(result.utxos[0].utxos[0], 'value')
}) })
}) })
describe(`#balance`, () => { describe('#balance', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Electrumx.balance(addr) await bchjs.Electrumx.balance(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings` 'Input address must be a string or array of strings'
) )
} }
}) })
it(`should GET balance for a single address`, async () => { it('should GET balance for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.balance }) sandbox.stub(axios, 'get').resolves({ data: mockData.balance })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balance") assert.property(result, 'balance')
assert.property(result.balance, "confirmed") assert.property(result.balance, 'confirmed')
assert.property(result.balance, "unconfirmed") assert.property(result.balance, 'unconfirmed')
}) })
it(`should POST balance for an array of addresses`, async () => { it('should POST balance for an array of addresses', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.balances }) sandbox.stub(axios, 'post').resolves({ data: mockData.balances })
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.balance(addr) const result = await bchjs.Electrumx.balance(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "balances") assert.property(result, 'balances')
assert.isArray(result.balances) assert.isArray(result.balances)
assert.property(result.balances[0], "address") assert.property(result.balances[0], 'address')
assert.property(result.balances[0], "balance") assert.property(result.balances[0], 'balance')
assert.property(result.balances[0].balance, "confirmed") assert.property(result.balances[0].balance, 'confirmed')
assert.property(result.balances[0].balance, "unconfirmed") assert.property(result.balances[0].balance, 'unconfirmed')
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Electrumx.transactions(addr) await bchjs.Electrumx.transactions(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings` 'Input address must be a string or array of strings'
) )
} }
}) })
it(`should GET transactions for a single address`, async () => { it('should GET transactions for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.transaction }) sandbox.stub(axios, 'get').resolves({ data: mockData.transaction })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "height") assert.property(result.transactions[0], 'height')
assert.property(result.transactions[0], "tx_hash") assert.property(result.transactions[0], 'tx_hash')
}) })
it(`should POST transaction history for an array of addresses`, async () => { it('should POST transaction history for an array of addresses', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.transactions }) sandbox.stub(axios, 'post').resolves({ data: mockData.transactions })
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.transactions(addr) const result = await bchjs.Electrumx.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "address") assert.property(result.transactions[0], 'address')
assert.property(result.transactions[0], "transactions") assert.property(result.transactions[0], 'transactions')
assert.isArray(result.transactions[0].transactions) assert.isArray(result.transactions[0].transactions)
assert.property(result.transactions[0].transactions[0], "height") assert.property(result.transactions[0].transactions[0], 'height')
assert.property(result.transactions[0].transactions[0], "tx_hash") assert.property(result.transactions[0].transactions[0], 'tx_hash')
}) })
}) })
describe(`#unconfirmed`, () => { describe('#unconfirmed', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Electrumx.unconfirmed(addr) await bchjs.Electrumx.unconfirmed(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings` 'Input address must be a string or array of strings'
) )
} }
}) })
it(`should GET unconfirmed utxos for a single address`, async () => { it('should GET unconfirmed utxos for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.unconfirmed }) sandbox.stub(axios, 'get').resolves({ data: mockData.unconfirmed })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Electrumx.unconfirmed(addr) const result = await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "height") assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], "tx_hash") assert.property(result.utxos[0], 'tx_hash')
assert.property(result.utxos[0], "fee") assert.property(result.utxos[0], 'fee')
}) })
it(`should POST unconfirmed utxo details for an array of addresses`, async () => { it('should POST unconfirmed utxo details for an array of addresses', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.unconfirmedArray }) sandbox.stub(axios, 'post').resolves({ data: mockData.unconfirmedArray })
const addr = [ const addr = [
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
"bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
] ]
const result = await bchjs.Electrumx.unconfirmed(addr) const result = await bchjs.Electrumx.unconfirmed(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "utxos") assert.property(result.utxos[0], 'utxos')
assert.isArray(result.utxos[0].utxos) assert.isArray(result.utxos[0].utxos)
assert.property(result.utxos[0], "address") assert.property(result.utxos[0], 'address')
assert.property(result.utxos[0].utxos[0], "height") assert.property(result.utxos[0].utxos[0], 'height')
assert.property(result.utxos[0].utxos[0], "tx_hash") assert.property(result.utxos[0].utxos[0], 'tx_hash')
assert.property(result.utxos[0].utxos[0], "fee") assert.property(result.utxos[0].utxos[0], 'fee')
}) })
}) })
describe(`#blockHeader`, () => { describe('#blockHeader', () => {
it(`should throw an error for improper height input`, async () => { it('should throw an error for improper height input', async () => {
try { try {
// Mock network calls. // Mock network calls.
sandbox.stub(axios, "get").rejects({ sandbox.stub(axios, 'get').rejects({
response: { response: {
data: { data: {
success: false, success: false,
error: "height must be a positive number" error: 'height must be a positive number'
} }
} }
}) })
@@ -277,21 +277,21 @@ describe(`#ElectrumX`, () => {
const height = -10 const height = -10
await bchjs.Electrumx.blockHeader(height) await bchjs.Electrumx.blockHeader(height)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `height must be a positive number`) assert.include(err.message, 'height must be a positive number')
} }
}) })
it(`should throw an error for improper count input`, async () => { it('should throw an error for improper count input', async () => {
try { try {
// Mock network calls. // Mock network calls.
sandbox.stub(axios, "get").rejects({ sandbox.stub(axios, 'get').rejects({
response: { response: {
data: { data: {
success: false, success: false,
error: "count must be a positive number" error: 'count must be a positive number'
} }
} }
}) })
@@ -300,16 +300,16 @@ describe(`#ElectrumX`, () => {
const count = -10 const count = -10
await bchjs.Electrumx.blockHeader(height, count) await bchjs.Electrumx.blockHeader(height, count)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `count must be a positive number`) assert.include(err.message, 'count must be a positive number')
} }
}) })
it(`should GET block headers for a given height`, async () => { it('should GET block headers for a given height', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.blockHeaders }) sandbox.stub(axios, 'get').resolves({ data: mockData.blockHeaders })
const height = 42 const height = 42
@@ -320,101 +320,101 @@ describe(`#ElectrumX`, () => {
}) })
}) })
describe(`#txData`, () => { describe('#txData', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const txid = 12345 const txid = 12345
await bchjs.Electrumx.txData(txid) await bchjs.Electrumx.txData(txid)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input txId must be a string or array of strings` 'Input txId must be a string or array of strings'
) )
} }
}) })
it(`should GET details data for a single transaction`, async () => { it('should GET details data for a single transaction', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.details }) sandbox.stub(axios, 'get').resolves({ data: mockData.details })
const txid = const txid =
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
const result = await bchjs.Electrumx.txData(txid) const result = await bchjs.Electrumx.txData(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "details") assert.property(result, 'details')
assert.isObject(result.details) assert.isObject(result.details)
assert.property(result.details, "blockhash") assert.property(result.details, 'blockhash')
assert.property(result.details, "hash") assert.property(result.details, 'hash')
assert.property(result.details, "hex") assert.property(result.details, 'hex')
assert.property(result.details, "vin") assert.property(result.details, 'vin')
assert.property(result.details, "vout") assert.property(result.details, 'vout')
assert.equal(result.details.hash, txid) assert.equal(result.details.hash, txid)
}) })
it(`should POST details for an array of transactions`, async () => { it('should POST details for an array of transactions', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.detailsArray }) sandbox.stub(axios, 'post').resolves({ data: mockData.detailsArray })
const txids = [ const txids = [
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251", '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251',
"4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251" '4db095f34d632a4daf942142c291f1f2abb5ba2e1ccac919d85bdc2f671fb251'
] ]
const result = await bchjs.Electrumx.txData(txids) const result = await bchjs.Electrumx.txData(txids)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "transactions") assert.property(result, 'transactions')
assert.isArray(result.transactions) assert.isArray(result.transactions)
assert.property(result.transactions[0], "txid") assert.property(result.transactions[0], 'txid')
assert.property(result.transactions[0], "details") assert.property(result.transactions[0], 'details')
assert.property(result.transactions[0].details, "blockhash") assert.property(result.transactions[0].details, 'blockhash')
assert.property(result.transactions[0].details, "hash") assert.property(result.transactions[0].details, 'hash')
assert.property(result.transactions[0].details, "hex") assert.property(result.transactions[0].details, 'hex')
assert.property(result.transactions[0].details, "vin") assert.property(result.transactions[0].details, 'vin')
assert.property(result.transactions[0].details, "vout") assert.property(result.transactions[0].details, 'vout')
assert.equal(result.transactions.length, 2, "2 outputs for 2 inputs") assert.equal(result.transactions.length, 2, '2 outputs for 2 inputs')
}) })
}) })
describe(`#broadcast`, () => { describe('#broadcast', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const txHex = 12345 const txHex = 12345
await bchjs.Electrumx.broadcast(txHex) await bchjs.Electrumx.broadcast(txHex)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `Input txHex must be a string.`) assert.include(err.message, 'Input txHex must be a string.')
} }
}) })
it(`should broadcast a single transaction`, async () => { it('should broadcast a single transaction', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.broadcast }) sandbox.stub(axios, 'post').resolves({ data: mockData.broadcast })
const tx = mockData.details const tx = mockData.details
const txid = tx.details.txid const txid = tx.details.txid
const result = await bchjs.Electrumx.broadcast(tx.details.hex) const result = await bchjs.Electrumx.broadcast(tx.details.hex)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "txid") assert.property(result, 'txid')
assert.equal(result.txid, txid) assert.equal(result.txid, txid)
}) })
}) })
+20 -20
View File
@@ -1,13 +1,13 @@
const assert = require("chai").assert const assert = require('chai').assert
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
let bchjs let bchjs
const mockData = require("./fixtures/encryption-mock") const mockData = require('./fixtures/encryption-mock')
describe("#Encryption", () => { describe('#Encryption', () => {
let sandbox let sandbox
beforeEach(() => { beforeEach(() => {
@@ -17,52 +17,52 @@ describe("#Encryption", () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe("#getPubKey", () => { describe('#getPubKey', () => {
it("should throw error if BCH address is not provided.", async () => { it('should throw error if BCH address is not provided.', async () => {
try { try {
await bchjs.encryption.getPubKey() await bchjs.encryption.getPubKey()
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
"Input must be a valid Bitcoin Cash address" 'Input must be a valid Bitcoin Cash address'
) )
} }
}) })
it("should report when public key can not be found", async () => { it('should report when public key can not be found', async () => {
// Stub the network call. // Stub the network call.
sandbox sandbox
.stub(bchjs.encryption.axios, "get") .stub(bchjs.encryption.axios, 'get')
.resolves({ data: mockData.failureMock }) .resolves({ data: mockData.failureMock })
const addr = "bitcoincash:qpxqr2pmcverj4vukgjqssvk2zju8tp9xsgz2nqagx" const addr = 'bitcoincash:qpxqr2pmcverj4vukgjqssvk2zju8tp9xsgz2nqagx'
const result = await bchjs.encryption.getPubKey(addr) const result = await bchjs.encryption.getPubKey(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, false) assert.equal(result.success, false)
assert.property(result, "publicKey") assert.property(result, 'publicKey')
assert.equal(result.publicKey, "not found") assert.equal(result.publicKey, 'not found')
}) })
it("should get a public key", async () => { it('should get a public key', async () => {
// Stub the network call. // Stub the network call.
sandbox sandbox
.stub(bchjs.encryption.axios, "get") .stub(bchjs.encryption.axios, 'get')
.resolves({ data: mockData.successMock }) .resolves({ data: mockData.successMock })
const addr = "bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq" const addr = 'bitcoincash:qpf8jv9hmqcda0502gjp7nm3g24y5h5s4unutghsxq'
const result = await bchjs.encryption.getPubKey(addr) const result = await bchjs.encryption.getPubKey(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "publicKey") assert.property(result, 'publicKey')
}) })
}) })
}) })
+14 -14
View File
@@ -6,34 +6,34 @@ const balance = { confirmed: 230000, unconfirmed: 0, balance: 230000 }
const utxo = [ const utxo = [
{ {
_id: "5cecdd39a9f1235e2a3d409a", _id: '5cecdd39a9f1235e2a3d409a',
chain: "BCH", chain: 'BCH',
network: "mainnet", network: 'mainnet',
coinbase: false, coinbase: false,
mintIndex: 0, mintIndex: 0,
spentTxid: "", spentTxid: '',
mintTxid: mintTxid:
"27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c", '27ec8512c1a9ee9e9ae9b98eb60375f1d2bd60e2e76a1eff5a45afdbc517cf9c',
mintHeight: 560430, mintHeight: 560430,
spentHeight: -2, spentHeight: -2,
address: "qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", address: 'qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
script: "76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac", script: '76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac',
value: 100000, value: 100000,
confirmations: -1 confirmations: -1
}, },
{ {
_id: "5cecdd1ca9f1235e2a3b6349", _id: '5cecdd1ca9f1235e2a3b6349',
chain: "BCH", chain: 'BCH',
network: "mainnet", network: 'mainnet',
coinbase: false, coinbase: false,
mintIndex: 0, mintIndex: 0,
spentTxid: "", spentTxid: '',
mintTxid: mintTxid:
"6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d", '6e1ae1bf7db6de799ec1c05ab2816ac65549bd80141567af088e6f291385b07d',
mintHeight: 560039, mintHeight: 560039,
spentHeight: -2, spentHeight: -2,
address: "qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf", address: 'qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
script: "76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac", script: '76a914db6ea94fa26b7272dc5e1487c35f258391e0f38788ac',
value: 130000, value: 130000,
confirmations: -1 confirmations: -1
} }
+7 -7
View File
@@ -4,24 +4,24 @@
module.exports = { module.exports = {
details: { details: {
hash: "000000001c6aeec19265e9cc3ded8ba5ef5e63fae7747f30bf9c02c7bc8883f0", hash: '000000001c6aeec19265e9cc3ded8ba5ef5e63fae7747f30bf9c02c7bc8883f0',
size: 216, size: 216,
height: 507, height: 507,
version: 1, version: 1,
merkleroot: merkleroot:
"a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8", 'a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8',
tx: ["a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8"], tx: ['a85fa3d831ab6b0305e7ff88d2d4941e25a810d4461635df51490653822071a8'],
time: 1231973656, time: 1231973656,
nonce: 330467862, nonce: 330467862,
bits: "1d00ffff", bits: '1d00ffff',
difficulty: 1, difficulty: 1,
chainwork: chainwork:
"000000000000000000000000000000000000000000000000000001fc01fc01fc", '000000000000000000000000000000000000000000000000000001fc01fc01fc',
confirmations: 585104, confirmations: 585104,
previousblockhash: previousblockhash:
"00000000a99525c043fd7e323414b60add43c254c44860094048f9c01e9a5fdd", '00000000a99525c043fd7e323414b60add43c254c44860094048f9c01e9a5fdd',
nextblockhash: nextblockhash:
"000000000d550f4161f2702165fdd782ec72ff9c541f864ebb8256b662b7e51a", '000000000d550f4161f2702165fdd782ec72ff9c541f864ebb8256b662b7e51a',
reward: 50, reward: 50,
isMainChain: true, isMainChain: true,
poolInfo: {} poolInfo: {}
+15 -15
View File
@@ -4,47 +4,47 @@
module.exports = { module.exports = {
bestBlockHash: bestBlockHash:
"0000000000000000008e1f65f875703872544aa888c7ca6587f055f8f5fbd4bf", '0000000000000000008e1f65f875703872544aa888c7ca6587f055f8f5fbd4bf',
blockHeader: { blockHeader: {
hash: "000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201", hash: '000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201',
confirmations: 85727, confirmations: 85727,
height: 500000, height: 500000,
version: 536870912, version: 536870912,
versionHex: "20000000", versionHex: '20000000',
merkleroot: merkleroot:
"4af279645e1b337e655ae3286fc2ca09f58eb01efa6ab27adedd1e9e6ec19091", '4af279645e1b337e655ae3286fc2ca09f58eb01efa6ab27adedd1e9e6ec19091',
time: 1509343584, time: 1509343584,
mediantime: 1509336533, mediantime: 1509336533,
nonce: 3604508752, nonce: 3604508752,
bits: "1809b91a", bits: '1809b91a',
difficulty: 113081236211.4533, difficulty: 113081236211.4533,
chainwork: chainwork:
"0000000000000000000000000000000000000000007ae48aca46e3b449ad9714", '0000000000000000000000000000000000000000007ae48aca46e3b449ad9714',
previousblockhash: previousblockhash:
"0000000000000000043831d6ebb013716f0580287ee5e5687e27d0ed72e6e523", '0000000000000000043831d6ebb013716f0580287ee5e5687e27d0ed72e6e523',
nextblockhash: nextblockhash:
"00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3" '00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3'
}, },
txOutProof: txOutProof:
"0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01", '0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01',
verifiedProof: verifiedProof:
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7", '03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7',
txOutUnspent: { txOutUnspent: {
bestblock: bestblock:
"000000000000000000b441e02f5b1b9f5b3def961047afcc6f2f5636c952705e", '000000000000000000b441e02f5b1b9f5b3def961047afcc6f2f5636c952705e',
confirmations: 2, confirmations: 2,
value: 0.00006, value: 0.00006,
scriptPubKey: { scriptPubKey: {
asm: asm:
"OP_DUP OP_HASH160 d19fae66b685f5c3633c0db0600313918347225f OP_EQUALVERIFY OP_CHECKSIG", 'OP_DUP OP_HASH160 d19fae66b685f5c3633c0db0600313918347225f OP_EQUALVERIFY OP_CHECKSIG',
hex: "76a914d19fae66b685f5c3633c0db0600313918347225f88ac", hex: '76a914d19fae66b685f5c3633c0db0600313918347225f88ac',
reqSigs: 1, reqSigs: 1,
type: "pubkeyhash", type: 'pubkeyhash',
addresses: ["bitcoincash:qrgeltnxk6zltsmr8sxmqcqrzwgcx3eztusrwgf0x3"] addresses: ['bitcoincash:qrgeltnxk6zltsmr8sxmqcqrzwgcx3eztusrwgf0x3']
}, },
coinbase: false coinbase: false
} }
+19 -19
View File
@@ -8,7 +8,7 @@ const utxo = {
{ {
height: 602405, height: 602405,
tx_hash: tx_hash:
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7", '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
tx_pos: 0, tx_pos: 0,
value: 1000 value: 1000
} }
@@ -23,23 +23,23 @@ const utxos = {
{ {
height: 604392, height: 604392,
tx_hash: tx_hash:
"7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41", '7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41',
tx_pos: 0, tx_pos: 0,
value: 1000 value: 1000
}, },
{ {
height: 630834, height: 630834,
tx_hash: tx_hash:
"4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53", '4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53',
tx_pos: 0, tx_pos: 0,
value: 6000 value: 6000
} }
], ],
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
}, },
{ {
utxos: [], utxos: [],
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" address: 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
} }
] ]
} }
@@ -60,14 +60,14 @@ const balances = {
confirmed: 7000, confirmed: 7000,
unconfirmed: 0 unconfirmed: 0
}, },
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
}, },
{ {
balance: { balance: {
confirmed: 0, confirmed: 0,
unconfirmed: 0 unconfirmed: 0
}, },
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" address: 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
} }
] ]
} }
@@ -78,12 +78,12 @@ const transaction = {
{ {
height: 560430, height: 560430,
tx_hash: tx_hash:
"3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851" '3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851'
}, },
{ {
height: 560534, height: 560534,
tx_hash: tx_hash:
"4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280" '4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280'
} }
] ]
} }
@@ -96,25 +96,25 @@ const transactions = {
{ {
height: 631219, height: 631219,
tx_hash: tx_hash:
"ae2daa01c8172545b5edd205ea438706bcb74e63d4084a26b9ff2a46d46dc97f" 'ae2daa01c8172545b5edd205ea438706bcb74e63d4084a26b9ff2a46d46dc97f'
} }
], ],
address: "bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj" address: 'bitcoincash:qrl2nlsaayk6ekxn80pq0ks32dya8xfclyktem2mqj'
}, },
{ {
transactions: [ transactions: [
{ {
height: 560430, height: 560430,
tx_hash: tx_hash:
"3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851" '3e1f3e882be9c03897eeb197224bf87f312be556a89f4308fabeeeabcf9bc851'
}, },
{ {
height: 560534, height: 560534,
tx_hash: tx_hash:
"4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280" '4ebbeaac51ce141e262964e3a0ce11b96ca72c0dffe9b4127ce80135f503a280'
} }
], ],
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" address: 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
} }
] ]
} }
@@ -125,7 +125,7 @@ const unconfirmed = {
{ {
height: 602405, height: 602405,
tx_hash: tx_hash:
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7", '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
fee: 34100 fee: 34100
} }
] ]
@@ -139,21 +139,21 @@ const unconfirmedArray = {
{ {
height: 604392, height: 604392,
tx_hash: tx_hash:
"7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41", '7774e449c5a3065144cefbc4c0c21e6b69c987f095856778ef9f45ddd8ae1a41',
fee: 34210 fee: 34210
}, },
{ {
height: 630834, height: 630834,
tx_hash: tx_hash:
"4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53", '4fe60a51e0d8f5134bfd8e5f872d6e502d7f01b28a6afebb27f4438a4f638d53',
value: 3000 value: 3000
} }
], ],
address: "bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" address: 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
}, },
{ {
utxos: [], utxos: [],
address: "bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v" address: 'bitcoincash:qpdh9s677ya8tnx7zdhfrn8qfyvy22wj4qa7nwqa5v'
} }
] ]
} }
+2 -2
View File
@@ -5,12 +5,12 @@
const successMock = { const successMock = {
success: true, success: true,
publicKey: publicKey:
"03fcc37586d93af1e146238217989924e0ab1f011c34e1a23aec529354d5b28eb4" '03fcc37586d93af1e146238217989924e0ab1f011c34e1a23aec529354d5b28eb4'
} }
const failureMock = { const failureMock = {
success: false, success: false,
publicKey: "not found" publicKey: 'not found'
} }
module.exports = { module.exports = {
+39 -39
View File
@@ -5,17 +5,17 @@
const uploadData = { const uploadData = {
successful: [ successful: [
{ {
source: "Local", source: 'Local',
id: "uppy-ipfs/js-1e-application/octet-stream", id: 'uppy-ipfs/js-1e-application/octet-stream',
name: "ipfs.js", name: 'ipfs.js',
extension: "js", extension: 'js',
meta: { meta: {
test: "avatar", test: 'avatar',
name: "ipfs.js", name: 'ipfs.js',
type: "application/octet-stream", type: 'application/octet-stream',
fileModelId: "5ec562319bfacc745e8d8a52" fileModelId: '5ec562319bfacc745e8d8a52'
}, },
type: "application/octet-stream", type: 'application/octet-stream',
progress: { progress: {
uploadStarted: 1589596706524, uploadStarted: 1589596706524,
uploadComplete: true, uploadComplete: true,
@@ -25,22 +25,22 @@ const uploadData = {
}, },
size: null, size: null,
isRemote: false, isRemote: false,
remote: "", remote: '',
tus: { tus: {
uploadUrl: uploadUrl:
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33" 'http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33'
}, },
response: { response: {
uploadURL: uploadURL:
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33" 'http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33'
}, },
uploadURL: uploadURL:
"http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33", 'http://localhost:5001/uppy-files/6acd261f494c3375dc522e27880efe33',
isPaused: false isPaused: false
} }
], ],
failed: [], failed: [],
uploadID: "cka90u4m300000fi0cldg6lrf" uploadID: 'cka90u4m300000fi0cldg6lrf'
} }
const paymentInfo = { const paymentInfo = {
@@ -48,18 +48,18 @@ const paymentInfo = {
hostingCostBCH: 0.00004201, hostingCostBCH: 0.00004201,
hostingCostUSD: 0.01, hostingCostUSD: 0.01,
file: { file: {
payloadLink: "", payloadLink: '',
hasBeenPaid: false, hasBeenPaid: false,
_id: "5ebf5d04cba8b038394e0d62", _id: '5ebf5d04cba8b038394e0d62',
schemaVersion: 1, schemaVersion: 1,
size: 2374, size: 2374,
fileId: "uppy-ipfs/js-1e-application/octet-stream", fileId: 'uppy-ipfs/js-1e-application/octet-stream',
fileName: "ipfs.js", fileName: 'ipfs.js',
fileExtension: "js", fileExtension: 'js',
createdTimestamp: "1589599492.952", createdTimestamp: '1589599492.952',
hostingCost: 4201, hostingCost: 4201,
walletIndex: 36, walletIndex: 36,
bchAddr: "bchtest:qqymyk4zfvnw8rh6hcvl922ewudkyrn9jvk6gtuae6", bchAddr: 'bchtest:qqymyk4zfvnw8rh6hcvl922ewudkyrn9jvk6gtuae6',
__v: 0 __v: 0
} }
} }
@@ -69,51 +69,51 @@ mockNewFileModel = {
hostingCostBCH: 0.00004197, hostingCostBCH: 0.00004197,
hostingCostUSD: 0.01, hostingCostUSD: 0.01,
file: { file: {
payloadLink: "", payloadLink: '',
hasBeenPaid: false, hasBeenPaid: false,
_id: "5ec562319bfacc745e8d8a52", _id: '5ec562319bfacc745e8d8a52',
schemaVersion: 1, schemaVersion: 1,
size: 4458, size: 4458,
fileName: "ipfs.js", fileName: 'ipfs.js',
fileExtension: "js", fileExtension: 'js',
createdTimestamp: "1589994033.655", createdTimestamp: '1589994033.655',
hostingCost: 4196, hostingCost: 4196,
walletIndex: 49, walletIndex: 49,
bchAddr: "bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c", bchAddr: 'bchtest:qzrpkevu7h2ayfa4rjx08r5elvpfu72dg567x3mh3c',
__v: 0 __v: 0
} }
} }
const unpaidFileData = { const unpaidFileData = {
file: { file: {
payloadLink: "", payloadLink: '',
hasBeenPaid: false, hasBeenPaid: false,
_id: "5ec7392c2acfe57aa62e945a", _id: '5ec7392c2acfe57aa62e945a',
schemaVersion: 1, schemaVersion: 1,
size: 726, size: 726,
fileName: "ipfs-e2e.js", fileName: 'ipfs-e2e.js',
fileExtension: "js", fileExtension: 'js',
createdTimestamp: "1590114604.986", createdTimestamp: '1590114604.986',
hostingCost: 4403, hostingCost: 4403,
walletIndex: 56, walletIndex: 56,
bchAddr: "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk", bchAddr: 'bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk',
__v: 0 __v: 0
} }
} }
const paidFileData = { const paidFileData = {
file: { file: {
payloadLink: "QmRDHPhY5hCNVRMVQvS2H9uty8P1skdwgLaHpUAkEvsjcE", payloadLink: 'QmRDHPhY5hCNVRMVQvS2H9uty8P1skdwgLaHpUAkEvsjcE',
hasBeenPaid: true, hasBeenPaid: true,
_id: "5ec7392c2acfe57aa62e945a", _id: '5ec7392c2acfe57aa62e945a',
schemaVersion: 1, schemaVersion: 1,
size: 726, size: 726,
fileName: "ipfs-e2e.js", fileName: 'ipfs-e2e.js',
fileExtension: "js", fileExtension: 'js',
createdTimestamp: "1590114604.986", createdTimestamp: '1590114604.986',
hostingCost: 4403, hostingCost: 4403,
walletIndex: 56, walletIndex: 56,
bchAddr: "bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk", bchAddr: 'bchtest:qz5z82u0suqh80x5tfx4ht8kdrkkw664vcy44uz0wk',
__v: 0 __v: 0
} }
} }
+36 -36
View File
@@ -5,7 +5,7 @@
const utxo = { const utxo = {
utxos: [ utxos: [
{ {
txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7", txid: '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
vout: 0, vout: 0,
amount: 0.00001, amount: 0.00001,
satoshis: 1000, satoshis: 1000,
@@ -13,18 +13,18 @@ const utxo = {
confirmations: 36459 confirmations: 36459
} }
], ],
legacyAddress: "15NCRBJsHaJy8As5bX1oh2YauRejnZ1MKF", legacyAddress: '15NCRBJsHaJy8As5bX1oh2YauRejnZ1MKF',
cashAddress: "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9", cashAddress: 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9',
slpAddress: "simpleledger:qqh793x9au6ehvh7r2zflzguanlme760wuwzunhjfm", slpAddress: 'simpleledger:qqh793x9au6ehvh7r2zflzguanlme760wuwzunhjfm',
scriptPubKey: "76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac", scriptPubKey: '76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac',
asm: asm:
"OP_DUP OP_HASH160 2fe2c4c5ef359bb2fe1a849f891cecffbcfb4f77 OP_EQUALVERIFY OP_CHECKSIG" 'OP_DUP OP_HASH160 2fe2c4c5ef359bb2fe1a849f891cecffbcfb4f77 OP_EQUALVERIFY OP_CHECKSIG'
} }
const unconfirmed = { const unconfirmed = {
utxos: [ utxos: [
{ {
txid: "3904ffe6f8fba4ceda5e887130f60fcb18bdc7dcee10392a57f89475c5c108f1", txid: '3904ffe6f8fba4ceda5e887130f60fcb18bdc7dcee10392a57f89475c5c108f1',
vout: 0, vout: 0,
amount: 0.03608203, amount: 0.03608203,
satoshis: 3608203, satoshis: 3608203,
@@ -32,10 +32,10 @@ const unconfirmed = {
ts: 1559670801 ts: 1559670801
} }
], ],
legacyAddress: "1AyWs8U4HUnTLmxxFiGoJbsXauRsvBrcKW", legacyAddress: '1AyWs8U4HUnTLmxxFiGoJbsXauRsvBrcKW',
cashAddress: "bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5", cashAddress: 'bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5',
slpAddress: "simpleledger:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rkuk8mdxlf2", slpAddress: 'simpleledger:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rkuk8mdxlf2',
scriptPubKey: "76a9146d695af951760b837c8e58b045b098f9c17e23b788ac" scriptPubKey: '76a9146d695af951760b837c8e58b045b098f9c17e23b788ac'
} }
const utxoPost = [utxo, utxo] const utxoPost = [utxo, utxo]
@@ -45,40 +45,40 @@ const transactions = {
pagesTotal: 1, pagesTotal: 1,
txs: [ txs: [
{ {
txid: "ec7bc8349386e3e1939bbdc4f8092fdbdd6a380734e68486b558cd594c451d5b", txid: 'ec7bc8349386e3e1939bbdc4f8092fdbdd6a380734e68486b558cd594c451d5b',
version: 2, version: 2,
locktime: 0, locktime: 0,
vin: [ vin: [
{ {
txid: txid:
"4f1fc57c33659628938db740449bf92fb75799e1d5750a4aeef80eb52d6df1e0", '4f1fc57c33659628938db740449bf92fb75799e1d5750a4aeef80eb52d6df1e0',
vout: 0, vout: 0,
sequence: 4294967295, sequence: 4294967295,
n: 0, n: 0,
scriptSig: { scriptSig: {
hex: hex:
"483045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f", '483045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f',
asm: asm:
"3045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f" '3045022100a3662a19ae384a1ceddea57765e425e61b04823e976d574da3911ac6b55d7f9b02200e571d985bce987675a2d58587a346fa40c39f4df13dc88548a92c52d5b24422[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f'
}, },
addr: "17HPz8RQ4XM6mjre6aspvqyj1j648CZidM", addr: '17HPz8RQ4XM6mjre6aspvqyj1j648CZidM',
valueSat: 1111, valueSat: 1111,
value: 0.00001111, value: 0.00001111,
doubleSpentTxID: null doubleSpentTxID: null
}, },
{ {
txid: txid:
"126d62c299e7e14c66fe0b485d13082c23641f003690462046bc24ad2d1180c1", '126d62c299e7e14c66fe0b485d13082c23641f003690462046bc24ad2d1180c1',
vout: 0, vout: 0,
sequence: 4294967295, sequence: 4294967295,
n: 1, n: 1,
scriptSig: { scriptSig: {
hex: hex:
"47304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f", '47304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda412103f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f',
asm: asm:
"304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f" '304402203e3f923207111ff9bbd2fb5ab1a49a9145ad809ee0cad0e0ddaed64bfe38dc16022012ee288fb413bd500c63f8bb95e46b6b57d34762decd46b7188478a1c398eeda[ALL|FORKID] 03f953f7630acc15bd3f5078c698f3af777286ae955b57e4857c158f75d87adb5f'
}, },
addr: "17HPz8RQ4XM6mjre6aspvqyj1j648CZidM", addr: '17HPz8RQ4XM6mjre6aspvqyj1j648CZidM',
valueSat: 1000, valueSat: 1000,
value: 0.00001, value: 0.00001,
doubleSpentTxID: null doubleSpentTxID: null
@@ -86,14 +86,14 @@ const transactions = {
], ],
vout: [ vout: [
{ {
value: "0.00001736", value: '0.00001736',
n: 0, n: 0,
scriptPubKey: { scriptPubKey: {
hex: "76a914d96ac75ca8df9729d278da50ccd7355c5785444e88ac", hex: '76a914d96ac75ca8df9729d278da50ccd7355c5785444e88ac',
asm: asm:
"OP_DUP OP_HASH160 d96ac75ca8df9729d278da50ccd7355c5785444e OP_EQUALVERIFY OP_CHECKSIG", 'OP_DUP OP_HASH160 d96ac75ca8df9729d278da50ccd7355c5785444e OP_EQUALVERIFY OP_CHECKSIG',
addresses: ["1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP"], addresses: ['1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP'],
type: "pubkeyhash" type: 'pubkeyhash'
}, },
spentTxId: null, spentTxId: null,
spentIndex: null, spentIndex: null,
@@ -109,36 +109,36 @@ const transactions = {
fees: 0.00000375 fees: 0.00000375
} }
], ],
legacyAddress: "1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP", legacyAddress: '1LpbYkEM5cryfhs58tH8c93p4SGzit7UrP',
cashAddress: "bitcoincash:qrvk436u4r0ew2wj0rd9pnxhx4w90p2yfc29ta0d2n", cashAddress: 'bitcoincash:qrvk436u4r0ew2wj0rd9pnxhx4w90p2yfc29ta0d2n',
currentPage: 0 currentPage: 0
} }
const transactionsPost = [transactions, transactions] const transactionsPost = [transactions, transactions]
const details = { const details = {
txid: "fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33", txid: 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
version: 1, version: 1,
locktime: 0, locktime: 0,
vin: [ vin: [
{ {
coinbase: "04ffff001d02fd04", coinbase: '04ffff001d02fd04',
sequence: 4294967295, sequence: 4294967295,
n: 0 n: 0
} }
], ],
vout: [ vout: [
{ {
value: "50.00000000", value: '50.00000000',
n: 0, n: 0,
scriptPubKey: { scriptPubKey: {
hex: hex:
"4104f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446aac", '4104f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446aac',
asm: asm:
"04f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446a OP_CHECKSIG", '04f5eeb2b10c944c6b9fbcfff94c35bdeecd93df977882babc7f3a2cf7f5c81d3b09a68db7f0e04f21de5d4230e75e6dbe7ad16eefe0d4325a62067dc6f369446a OP_CHECKSIG',
addresses: ["1BW18n7MfpU35q4MTBSk8pse3XzQF8XvzT"], addresses: ['1BW18n7MfpU35q4MTBSk8pse3XzQF8XvzT'],
type: "pubkeyhash", type: 'pubkeyhash',
cashAddrs: ["bitcoincash:qpej6mkrwca4tvy2snq4crhrf88v4ljspysx0ueetk"] cashAddrs: ['bitcoincash:qpej6mkrwca4tvy2snq4crhrf88v4ljspysx0ueetk']
}, },
spentTxId: null, spentTxId: null,
spentIndex: null, spentIndex: null,
@@ -146,7 +146,7 @@ const details = {
} }
], ],
blockhash: blockhash:
"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09", '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',
blockheight: 1000, blockheight: 1000,
confirmations: 585610, confirmations: 585610,
time: 1232346882, time: 1232346882,
+24 -24
View File
@@ -6,23 +6,23 @@ const balance = {
page: 1, page: 1,
totalPages: 1, totalPages: 1,
itemsOnPage: 1000, itemsOnPage: 1000,
addrStr: "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9", addrStr: 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9',
balance: "0.00001", balance: '0.00001',
totalReceived: "0.00001", totalReceived: '0.00001',
totalSent: "0", totalSent: '0',
unconfirmedBalance: "0", unconfirmedBalance: '0',
unconfirmedTxApperances: 0, unconfirmedTxApperances: 0,
txApperances: 1, txApperances: 1,
transactions: [ transactions: [
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7" '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
] ]
} }
const utxo = [ const utxo = [
{ {
txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7", txid: '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
vout: 0, vout: 0,
amount: "0.00001", amount: '0.00001',
satoshis: 1000, satoshis: 1000,
height: 602405, height: 602405,
confirmations: 11 confirmations: 11
@@ -30,51 +30,51 @@ const utxo = [
] ]
const tx = { const tx = {
txid: "2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7", txid: '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7',
version: 2, version: 2,
vin: [ vin: [
{ {
txid: "5f09d317e24c5d376f737a2711f3bd1d381abdb41743fff3819b4f76382e1eac", txid: '5f09d317e24c5d376f737a2711f3bd1d381abdb41743fff3819b4f76382e1eac',
vout: 1, vout: 1,
sequence: 4294967295, sequence: 4294967295,
n: 0, n: 0,
scriptSig: { scriptSig: {
hex: hex:
"473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9" '473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9'
}, },
addresses: ["bitcoincash:qqxy8hycqe89j7wa79gnggq6z3gaqu2uvqy26xehfe"], addresses: ['bitcoincash:qqxy8hycqe89j7wa79gnggq6z3gaqu2uvqy26xehfe'],
value: "0.00047504" value: '0.00047504'
} }
], ],
vout: [ vout: [
{ {
value: "0.00001", value: '0.00001',
n: 0, n: 0,
scriptPubKey: { scriptPubKey: {
hex: "76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac", hex: '76a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788ac',
addresses: ["bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9"] addresses: ['bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9']
}, },
spent: false spent: false
}, },
{ {
value: "0.00046256", value: '0.00046256',
n: 1, n: 1,
scriptPubKey: { scriptPubKey: {
hex: "76a9142dbf5e1804c39a497b908c876097d63210c8490288ac", hex: '76a9142dbf5e1804c39a497b908c876097d63210c8490288ac',
addresses: ["bitcoincash:qqkm7hscqnpe5jtmjzxgwcyh6ceppjzfqg3jdn422e"] addresses: ['bitcoincash:qqkm7hscqnpe5jtmjzxgwcyh6ceppjzfqg3jdn422e']
}, },
spent: false spent: false
} }
], ],
blockhash: "0000000000000000010903a1fc4274499037c9339be9ec7338ee980331c20ce5", blockhash: '0000000000000000010903a1fc4274499037c9339be9ec7338ee980331c20ce5',
blockheight: 602405, blockheight: 602405,
confirmations: 11, confirmations: 11,
blocktime: 1569792892, blocktime: 1569792892,
valueOut: "0.00047256", valueOut: '0.00047256',
valueIn: "0.00047504", valueIn: '0.00047504',
fees: "0.00000248", fees: '0.00000248',
hex: hex:
"0200000001ac1e2e38764f9b81f3ff4317b4bd1a381dbdf311277a736f375d4ce217d3095f010000006a473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9ffffffff02e8030000000000001976a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788acb0b40000000000001976a9142dbf5e1804c39a497b908c876097d63210c8490288ac00000000" '0200000001ac1e2e38764f9b81f3ff4317b4bd1a381dbdf311277a736f375d4ce217d3095f010000006a473044022000dd11c41a472f2e54348db996e60864d489429f12d1e044d49ff600b880c9590220715a926404bb0e2731a3795afb341ec1dad3f84ead7d27cd31fcc59abb14738c4121038476128287ac37c7a3cf7e8625fd5f024db1bc3d8e37395abe7bf42fda78d0d9ffffffff02e8030000000000001976a9142fe2c4c5ef359bb2fe1a849f891cecffbcfb4f7788acb0b40000000000001976a9142dbf5e1804c39a497b908c876097d63210c8490288ac00000000'
} }
module.exports = { module.exports = {
+204 -204
View File
@@ -3,210 +3,210 @@
*/ */
const mockRates = { const mockRates = {
AED: "915.049218", AED: '915.049218',
AFN: "19144.48874646", AFN: '19144.48874646',
ALGO: "826.6633482661356600405", ALGO: '826.6633482661356600405',
ALL: "26221.96098759", ALL: '26221.96098759',
AMD: "119977.82663822", AMD: '119977.82663822',
ANG: "446.841810455", ANG: '446.841810455',
AOA: "162269.774275", AOA: '162269.774275',
ARS: "19322.704621", ARS: '19322.704621',
ATOM: "45.5920571010248851205", ATOM: '45.5920571010248851205',
AUD: "353.78913716", AUD: '353.78913716',
AWG: "448.407", AWG: '448.407',
AZN: "424.1182875", AZN: '424.1182875',
BAL: "18.9361216125975755781", BAL: '18.9361216125975755781',
BAM: "413.75759465", BAM: '413.75759465',
BAND: "40.84187228461349099275", BAND: '40.84187228461349099275',
BAT: "1169.75444148879972951", BAT: '1169.75444148879972951',
BBD: "498.23", BBD: '498.23',
BCH: "1.0", BCH: '1.0',
BDT: "21107.92000745", BDT: '21107.92000745',
BGN: "413.93197515", BGN: '413.93197515',
BHD: "93.93578597", BHD: '93.93578597',
BIF: "481540.76228735", BIF: '481540.76228735',
BMD: "249.115", BMD: '249.115',
BND: "337.84677362", BND: '337.84677362',
BOB: "1718.851399565", BOB: '1718.851399565',
BRL: "1396.737982", BRL: '1396.737982',
BSD: "249.115", BSD: '249.115',
BSV: "1.555324933590611026515", BSV: '1.555324933590611026515',
BTC: "0.021265", BTC: '0.021265',
BTN: "18249.513962505", BTN: '18249.513962505',
BWP: "2848.17713393", BWP: '2848.17713393',
BYN: "637.963336685", BYN: '637.963336685',
BYR: "6379633.36685000049823", BYR: '6379633.36685000049823',
BZD: "501.752236985", BZD: '501.752236985',
CAD: "328.80838319", CAD: '328.80838319',
CDF: "488848.679106575", CDF: '488848.679106575',
CGLD: "121.0412516398620018305", CGLD: '121.0412516398620018305',
CHF: "226.8989243", CHF: '226.8989243',
CLF: "7.110489445", CLF: '7.110489445',
CLP: "196202.978234955", CLP: '196202.978234955',
CNH: "1664.25510705", CNH: '1664.25510705',
CNY: "1666.429881", CNY: '1666.429881',
COMP: "2.4706436576415750709", COMP: '2.4706436576415750709',
COP: "958730.858397465", COP: '958730.858397465',
CRC: "150173.845981", CRC: '150173.845981',
CUC: "248.997666835", CUC: '248.997666835',
CVE: "23541.3675", CVE: '23541.3675',
CZK: "5770.848621", CZK: '5770.848621',
DAI: "247.0463573269230002455", DAI: '247.0463573269230002455',
DASH: "3.327367317363110236645", DASH: '3.327367317363110236645',
DJF: "44315.31795969", DJF: '44315.31795969',
DKK: "1575.7370741", DKK: '1575.7370741',
DOP: "14529.76988648", DOP: '14529.76988648',
DZD: "32107.28592277", DZD: '32107.28592277',
EEK: "3640.489633465", EEK: '3640.489633465',
EGP: "3911.404438", EGP: '3911.404438',
EOS: "96.6873665825732601419", EOS: '96.6873665825732601419',
ERN: "3736.727740265", ERN: '3736.727740265',
ETB: "9302.454572035", ETB: '9302.454572035',
ETC: "44.91795888928957612395", ETC: '44.91795888928957612395',
ETH: "0.6574429621419051422355", ETH: '0.6574429621419051422355',
EUR: "211.595", EUR: '211.595',
FJD: "533.11855575", FJD: '533.11855575',
FKP: "192.55642863", FKP: '192.55642863',
GBP: "192.87", GBP: '192.87',
GEL: "804.64145", GEL: '804.64145',
GGP: "192.55642863", GGP: '192.55642863',
GHS: "1448.776859925", GHS: '1448.776859925',
GIP: "192.55642863", GIP: '192.55642863',
GMD: "12891.70125", GMD: '12891.70125',
GNF: "2438630.43574976", GNF: '2438630.43574976',
GTQ: "1936.689014855", GTQ: '1936.689014855',
GYD: "52047.88891278", GYD: '52047.88891278',
HKD: "1930.67861725", HKD: '1930.67861725',
HNL: "6126.43736492", HNL: '6126.43736492',
HRK: "1605.40119007", HRK: '1605.40119007',
HTG: "15682.48428085", HTG: '15682.48428085',
HUF: "77261.419177275", HUF: '77261.419177275',
IDR: "3666848.2425", IDR: '3666848.2425',
ILS: "843.29662455", ILS: '843.29662455',
IMP: "192.55642863", IMP: '192.55642863',
INR: "18275.43761675", INR: '18275.43761675',
IQD: "297176.65680577", IQD: '297176.65680577',
ISK: "34639.44075", ISK: '34639.44075',
JEP: "192.55642863", JEP: '192.55642863',
JMD: "36261.061070375", JMD: '36261.061070375',
JOD: "176.622535", JOD: '176.622535',
JPY: "26304.9247525", JPY: '26304.9247525',
KES: "27093.7474", KES: '27093.7474',
KGS: "20240.23303148", KGS: '20240.23303148',
KHR: "1021526.66327067", KHR: '1021526.66327067',
KMF: "104678.164103975", KMF: '104678.164103975',
KNC: "275.5392102643512742545", KNC: '275.5392102643512742545',
KRW: "284115.6575", KRW: '284115.6575',
KWD: "76.196555935", KWD: '76.196555935',
KYD: "207.44852333", KYD: '207.44852333',
KZT: "106578.169689505", KZT: '106578.169689505',
LAK: "2300372.70137523", LAK: '2300372.70137523',
LBP: "376426.60931701", LBP: '376426.60931701',
LINK: "22.8704181013371177476", LINK: '22.8704181013371177476',
LKR: "45903.840861165", LKR: '45903.840861165',
LRC: "1428.4116972477063306", LRC: '1428.4116972477063306',
LRD: "48689.521020355", LRD: '48689.521020355',
LSL: "4093.68786226", LSL: '4093.68786226',
LTC: "5.182877353583689269445", LTC: '5.182877353583689269445',
LTL: "803.357262175", LTL: '803.357262175',
LVL: "163.484459015", LVL: '163.484459015',
LYD: "340.470203685", LYD: '340.470203685',
MAD: "2290.86403115", MAD: '2290.86403115',
MDL: "4231.74490411", MDL: '4231.74490411',
MGA: "978918.42727237", MGA: '978918.42727237',
MKD: "13034.71219274", MKD: '13034.71219274',
MKR: "0.43727565410331105846", MKR: '0.43727565410331105846',
MMK: "321367.16219401", MMK: '321367.16219401',
MNT: "706980.17312004", MNT: '706980.17312004',
MOP: "1987.157222705", MOP: '1987.157222705',
MRO: "88934.055", MRO: '88934.055',
MTL: "170.32939187", MTL: '170.32939187',
MUR: "9942.18014823", MUR: '9942.18014823',
MVR: "3836.371", MVR: '3836.371',
MWK: "187533.350248305", MWK: '187533.350248305',
MXN: "5285.574344805", MXN: '5285.574344805',
MYR: "1033.2044625", MYR: '1033.2044625',
MZN: "18168.45667469", MZN: '18168.45667469',
NAD: "4120.3621", NAD: '4120.3621',
NGN: "95465.8503", NGN: '95465.8503',
NIO: "8675.07065117", NIO: '8675.07065117',
NMR: "8.6886689628111785348", NMR: '8.6886689628111785348',
NOK: "2328.95371465", NOK: '2328.95371465',
NPR: "29198.52701022", NPR: '29198.52701022',
NZD: "378.934057915", NZD: '378.934057915',
OMG: "74.27621574882972595255", OMG: '74.27621574882972595255',
OMR: "95.913509955", OMR: '95.913509955',
OXT: "1023.479868529169993565", OXT: '1023.479868529169993565',
PAB: "249.115", PAB: '249.115',
PEN: "892.41413087", PEN: '892.41413087',
PGK: "870.976539545", PGK: '870.976539545',
PHP: "12100.979598855", PHP: '12100.979598855',
PKR: "40413.26181118", PKR: '40413.26181118',
PLN: "968.71705891", PLN: '968.71705891',
PYG: "1750259.579863715", PYG: '1750259.579863715',
QAR: "907.08999375", QAR: '907.08999375',
REN: "758.802924154736515935", REN: '758.802924154736515935',
REP: "18.2168190127970744169", REP: '18.2168190127970744169',
REPV2: "18.225711080673967324", REPV2: '18.225711080673967324',
RON: "1032.33256", RON: '1032.33256',
RSD: "24895.307525", RSD: '24895.307525',
RUB: "19351.4774035", RUB: '19351.4774035',
RWF: "243426.179717085", RWF: '243426.179717085',
SAR: "934.309544225", SAR: '934.309544225',
SBD: "2013.0584566", SBD: '2013.0584566',
SCR: "4561.388071665", SCR: '4561.388071665',
SEK: "2201.10291435", SEK: '2201.10291435',
SGD: "338.356712025", SGD: '338.356712025',
SHP: "192.55642863", SHP: '192.55642863',
SLL: "2482430.971263275", SLL: '2482430.971263275',
SOS: "144000.839307095", SOS: '144000.839307095',
SRD: "3525.97371", SRD: '3525.97371',
SSP: "32449.7199", SSP: '32449.7199',
STD: "5232524.31108792", STD: '5232524.31108792',
SVC: "2178.147216215", SVC: '2178.147216215',
SZL: "4091.741526765", SZL: '4091.741526765',
THB: "7785.4665375", THB: '7785.4665375',
TJS: "2568.96954016", TJS: '2568.96954016',
TMT: "871.9025", TMT: '871.9025',
TND: "686.00043125", TND: '686.00043125',
TOP: "578.0165522", TOP: '578.0165522',
TRY: "1963.587954325", TRY: '1963.587954325',
TTD: "1689.460313635", TTD: '1689.460313635',
TWD: "7158.9423125", TWD: '7158.9423125',
TZS: "577510.41827928", TZS: '577510.41827928',
UAH: "7061.44019619", UAH: '7061.44019619',
UGX: "931508.2111739", UGX: '931508.2111739',
UMA: "30.09543944427665349095", UMA: '30.09543944427665349095',
UNI: "79.18593747516647884725", UNI: '79.18593747516647884725',
USD: "249.115", USD: '249.115',
USDC: "249.115", USDC: '249.115',
UYU: "10688.478117885", UYU: '10688.478117885',
UZS: "2582693.606121005", UZS: '2582693.606121005',
VEF: "61901998.996866715", VEF: '61901998.996866715',
VES: "112695476.713406465", VES: '112695476.713406465',
VND: "5773814.12282902", VND: '5773814.12282902',
VUV: "28486.73470656", VUV: '28486.73470656',
WST: "653.35042289", WST: '653.35042289',
XAF: "138884.3079243", XAF: '138884.3079243',
XAG: "10.22661168355", XAG: '10.22661168355',
XAU: "0.1312935696", XAU: '0.1312935696',
XCD: "673.24574325", XCD: '673.24574325',
XDR: "176.50246157", XDR: '176.50246157',
XLM: "2936.20532162536435083", XLM: '2936.20532162536435083',
XOF: "138884.3079243", XOF: '138884.3079243',
XPD: "0.1061030608", XPD: '0.1061030608',
XPF: "25265.84267069", XPF: '25265.84267069',
XPT: "0.2910211253", XPT: '0.2910211253',
XRP: "1014.931757995518373565", XRP: '1014.931757995518373565',
XTZ: "113.8135051169590628124", XTZ: '113.8135051169590628124',
YER: "62365.930534515", YER: '62365.930534515',
YFI: "0.0178703370267443543872", YFI: '0.0178703370267443543872',
ZAR: "4122.31765275", ZAR: '4122.31765275',
ZEC: "3.87305659203980154283", ZEC: '3.87305659203980154283',
ZMK: "1308619.842149325", ZMK: '1308619.842149325',
ZMW: "5027.95231667", ZMW: '5027.95231667',
ZRX: "644.844402797695193656", ZRX: '644.844402797695193656',
ZWL: "80215.03" ZWL: '80215.03'
} }
module.exports = { module.exports = {
File diff suppressed because it is too large Load Diff
+9 -9
View File
@@ -1,31 +1,31 @@
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
let bchjs let bchjs
describe("#Generating", () => { describe('#Generating', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#generateToAddress", () => { describe('#generateToAddress', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should generate", done => { it('should generate', done => {
const data = [] const data = []
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved) sandbox.stub(axios, 'post').returns(resolved)
bchjs.Generating.generateToAddress( bchjs.Generating.generateToAddress(
1, 1,
"bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" 'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
) )
.then(result => { .then(result => {
assert.deepEqual(data, result) assert.deepEqual(data, result)
+62 -62
View File
@@ -1,23 +1,23 @@
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
const Buffer = require("safe-buffer").Buffer const Buffer = require('safe-buffer').Buffer
// Mocks // Mocks
const fixtures = require("./fixtures/hdnode.json") const fixtures = require('./fixtures/hdnode.json')
const slpFixtures = require("./fixtures/slp/address.json") const slpFixtures = require('./fixtures/slp/address.json')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
describe("#HDNode", () => { describe('#HDNode', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#fromSeed", () => { describe('#fromSeed', () => {
fixtures.fromSeed.forEach(mnemonic => { fixtures.fromSeed.forEach(mnemonic => {
it(`should create an HDNode from root seed buffer`, async () => { it('should create an HDNode from root seed buffer', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
assert.notEqual(hdNode, null) assert.notEqual(hdNode, null)
@@ -25,9 +25,9 @@ describe("#HDNode", () => {
}) })
}) })
describe("#derive", () => { describe('#derive', () => {
fixtures.derive.forEach(derive => { fixtures.derive.forEach(derive => {
it(`should derive non hardened child HDNode`, async () => { it('should derive non hardened child HDNode', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derive(hdNode, 0) const childHDNode = bchjs.HDNode.derive(hdNode, 0)
@@ -37,9 +37,9 @@ describe("#HDNode", () => {
}) })
}) })
describe("#deriveHardened", () => { describe('#deriveHardened', () => {
fixtures.deriveHardened.forEach(derive => { fixtures.deriveHardened.forEach(derive => {
it(`should derive hardened child HDNode`, async () => { it('should derive hardened child HDNode', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.deriveHardened(hdNode, 0) const childHDNode = bchjs.HDNode.deriveHardened(hdNode, 0)
@@ -48,9 +48,9 @@ describe("#HDNode", () => {
}) })
}) })
describe("derive BIP44 $BCH account", () => { describe('derive BIP44 $BCH account', () => {
fixtures.deriveBIP44.forEach(derive => { fixtures.deriveBIP44.forEach(derive => {
it(`should derive BIP44 $BCH account`, async () => { it('should derive BIP44 $BCH account', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const purpose = bchjs.HDNode.deriveHardened(hdNode, 44) const purpose = bchjs.HDNode.deriveHardened(hdNode, 44)
@@ -63,22 +63,22 @@ describe("#HDNode", () => {
}) })
}) })
describe("#derivePath", () => { describe('#derivePath', () => {
describe("derive non hardened Path", () => { describe('derive non hardened Path', () => {
fixtures.derivePath.forEach(derive => { fixtures.derivePath.forEach(derive => {
it(`should derive non hardened child HDNode from path`, async () => { it('should derive non hardened child HDNode from path', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "0") const childHDNode = bchjs.HDNode.derivePath(hdNode, '0')
assert.equal(bchjs.HDNode.toXPub(childHDNode), derive.xpub) assert.equal(bchjs.HDNode.toXPub(childHDNode), derive.xpub)
assert.equal(bchjs.HDNode.toXPriv(childHDNode), derive.xpriv) assert.equal(bchjs.HDNode.toXPriv(childHDNode), derive.xpriv)
}) })
}) })
}) })
describe("derive hardened Path", () => { describe('derive hardened Path', () => {
fixtures.deriveHardenedPath.forEach(derive => { fixtures.deriveHardenedPath.forEach(derive => {
it(`should derive hardened child HDNode from path`, async () => { it('should derive hardened child HDNode from path', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "0'") const childHDNode = bchjs.HDNode.derivePath(hdNode, "0'")
@@ -88,9 +88,9 @@ describe("#HDNode", () => {
}) })
}) })
describe("derive BIP44 $BCH account", () => { describe('derive BIP44 $BCH account', () => {
fixtures.deriveBIP44.forEach(derive => { fixtures.deriveBIP44.forEach(derive => {
it(`should derive BIP44 $BCH account`, async () => { it('should derive BIP44 $BCH account', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(derive.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "44'/145'/0'") const childHDNode = bchjs.HDNode.derivePath(hdNode, "44'/145'/0'")
@@ -101,24 +101,24 @@ describe("#HDNode", () => {
}) })
}) })
describe("#toLegacyAddress", () => { describe('#toLegacyAddress', () => {
fixtures.toLegacyAddress.forEach(fixture => { fixtures.toLegacyAddress.forEach(fixture => {
it(`should get address ${fixture.address} from HDNode`, async () => { it(`should get address ${fixture.address} from HDNode`, async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "0") const childHDNode = bchjs.HDNode.derivePath(hdNode, '0')
const addy = bchjs.HDNode.toLegacyAddress(childHDNode) const addy = bchjs.HDNode.toLegacyAddress(childHDNode)
assert.equal(addy, fixture.address) assert.equal(addy, fixture.address)
}) })
}) })
}) })
describe("#toCashAddress", () => { describe('#toCashAddress', () => {
fixtures.toCashAddress.forEach(fixture => { fixtures.toCashAddress.forEach(fixture => {
it(`should get address ${fixture.address} from HDNode`, async () => { it(`should get address ${fixture.address} from HDNode`, async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "0") const childHDNode = bchjs.HDNode.derivePath(hdNode, '0')
const addy = bchjs.HDNode.toCashAddress(childHDNode) const addy = bchjs.HDNode.toCashAddress(childHDNode)
assert.equal(addy, fixture.address) assert.equal(addy, fixture.address)
}) })
@@ -126,14 +126,14 @@ describe("#HDNode", () => {
it(`should get address ${fixture.regtestAddress} from HDNode`, async () => { it(`should get address ${fixture.regtestAddress} from HDNode`, async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const childHDNode = bchjs.HDNode.derivePath(hdNode, "0") const childHDNode = bchjs.HDNode.derivePath(hdNode, '0')
const addr = bchjs.HDNode.toCashAddress(childHDNode, true) const addr = bchjs.HDNode.toCashAddress(childHDNode, true)
assert.equal(addr, fixture.regtestAddress) assert.equal(addr, fixture.regtestAddress)
}) })
}) })
}) })
describe("#toWIF", () => { describe('#toWIF', () => {
fixtures.toWIF.forEach(fixture => { fixtures.toWIF.forEach(fixture => {
it(`should get privateKeyWIF ${fixture.privateKeyWIF} from HDNode`, () => { it(`should get privateKeyWIF ${fixture.privateKeyWIF} from HDNode`, () => {
const hdNode = bchjs.HDNode.fromXPriv(fixture.xpriv) const hdNode = bchjs.HDNode.fromXPriv(fixture.xpriv)
@@ -142,7 +142,7 @@ describe("#HDNode", () => {
}) })
}) })
describe("#toXPub", () => { describe('#toXPub', () => {
fixtures.toXPub.forEach(fixture => { fixtures.toXPub.forEach(fixture => {
it(`should create xpub ${fixture.xpub} from an HDNode`, async () => { it(`should create xpub ${fixture.xpub} from an HDNode`, async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
@@ -153,7 +153,7 @@ describe("#HDNode", () => {
}) })
}) })
describe("#toXPriv", () => { describe('#toXPriv', () => {
fixtures.toXPriv.forEach(fixture => { fixtures.toXPriv.forEach(fixture => {
it(`should create xpriv ${fixture.xpriv} from an HDNode`, async () => { it(`should create xpriv ${fixture.xpriv} from an HDNode`, async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
@@ -164,30 +164,30 @@ describe("#HDNode", () => {
}) })
}) })
describe("#toKeyPair", () => { describe('#toKeyPair', () => {
fixtures.toKeyPair.forEach(fixture => { fixtures.toKeyPair.forEach(fixture => {
it(`should get ECPair from an HDNode`, async () => { it('should get ECPair from an HDNode', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const keyPair = bchjs.HDNode.toKeyPair(hdNode) const keyPair = bchjs.HDNode.toKeyPair(hdNode)
assert.equal(typeof keyPair, "object") assert.equal(typeof keyPair, 'object')
}) })
}) })
}) })
describe("#toPublicKey", () => { describe('#toPublicKey', () => {
fixtures.toPublicKey.forEach(fixture => { fixtures.toPublicKey.forEach(fixture => {
it(`should create public key buffer from an HDNode`, async () => { it('should create public key buffer from an HDNode', async () => {
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const rootSeedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer) const hdNode = bchjs.HDNode.fromSeed(rootSeedBuffer)
const publicKeyBuffer = bchjs.HDNode.toPublicKey(hdNode) const publicKeyBuffer = bchjs.HDNode.toPublicKey(hdNode)
assert.equal(typeof publicKeyBuffer, "object") assert.equal(typeof publicKeyBuffer, 'object')
}) })
}) })
}) })
describe("#fromXPriv", () => { describe('#fromXPriv', () => {
it("should exercise fromXPriv", () => { it('should exercise fromXPriv', () => {
fixtures.fromXPriv.forEach(fixture => { fixtures.fromXPriv.forEach(fixture => {
const hdNode = bchjs.HDNode.fromXPriv(fixture.xpriv) const hdNode = bchjs.HDNode.fromXPriv(fixture.xpriv)
it(`should create HDNode from xpriv ${fixture.xpriv}`, () => { it(`should create HDNode from xpriv ${fixture.xpriv}`, () => {
@@ -224,8 +224,8 @@ describe("#HDNode", () => {
}) })
}) })
describe("#fromXPub", () => { describe('#fromXPub', () => {
it("should exercise fromXPub", () => { it('should exercise fromXPub', () => {
fixtures.fromXPub.forEach(fixture => { fixtures.fromXPub.forEach(fixture => {
const hdNode = bchjs.HDNode.fromXPub(fixture.xpub) const hdNode = bchjs.HDNode.fromXPub(fixture.xpub)
it(`should create HDNode from xpub ${fixture.xpub}`, () => { it(`should create HDNode from xpub ${fixture.xpub}`, () => {
@@ -254,21 +254,21 @@ describe("#HDNode", () => {
}) })
}) })
describe("#bip32", () => { describe('#bip32', () => {
it("should create accounts and addresses", () => { it('should create accounts and addresses', () => {
fixtures.accounts.forEach(async fixture => { fixtures.accounts.forEach(async fixture => {
const seedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic) const seedBuffer = await bchjs.Mnemonic.toSeed(fixture.mnemonic)
console.log(`seedBuffer: ${seedBuffer.toString()}`) console.log(`seedBuffer: ${seedBuffer.toString()}`)
const hdNode = bchjs.HDNode.fromSeed(seedBuffer) const hdNode = bchjs.HDNode.fromSeed(seedBuffer)
const a = bchjs.HDNode.derivePath(hdNode, "0'") const a = bchjs.HDNode.derivePath(hdNode, "0'")
const external = bchjs.HDNode.derivePath(a, "0") const external = bchjs.HDNode.derivePath(a, '0')
const account = bchjs.HDNode.createAccount([external]) const account = bchjs.HDNode.createAccount([external])
it(`#createAccount`, () => { it('#createAccount', () => {
assert.notEqual(account, null) assert.notEqual(account, null)
}) })
describe("#getChainAddress", () => { describe('#getChainAddress', () => {
const external1 = bchjs.Address.toCashAddress( const external1 = bchjs.Address.toCashAddress(
account.getChainAddress(0) account.getChainAddress(0)
) )
@@ -277,7 +277,7 @@ describe("#HDNode", () => {
}) })
}) })
describe("#nextChainAddress", () => { describe('#nextChainAddress', () => {
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
const ex = bchjs.Address.toCashAddress(account.nextChainAddress(0)) const ex = bchjs.Address.toCashAddress(account.nextChainAddress(0))
it(`should create external change address ${ex}`, () => { it(`should create external change address ${ex}`, () => {
@@ -289,22 +289,22 @@ describe("#HDNode", () => {
}) })
}) })
describe("#sign", () => { describe('#sign', () => {
fixtures.sign.forEach(fixture => { fixtures.sign.forEach(fixture => {
it(`should sign 32 byte hash buffer`, () => { it('should sign 32 byte hash buffer', () => {
const hdnode = bchjs.HDNode.fromXPriv(fixture.privateKeyWIF) const hdnode = bchjs.HDNode.fromXPriv(fixture.privateKeyWIF)
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex") const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), 'hex')
const signatureBuf = bchjs.HDNode.sign(hdnode, buf) const signatureBuf = bchjs.HDNode.sign(hdnode, buf)
assert.equal(typeof signatureBuf, "object") assert.equal(typeof signatureBuf, 'object')
}) })
}) })
}) })
describe("#verify", () => { describe('#verify', () => {
fixtures.verify.forEach(fixture => { fixtures.verify.forEach(fixture => {
it(`should verify signed 32 byte hash buffer`, () => { it('should verify signed 32 byte hash buffer', () => {
const hdnode1 = bchjs.HDNode.fromXPriv(fixture.privateKeyWIF1) const hdnode1 = bchjs.HDNode.fromXPriv(fixture.privateKeyWIF1)
const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), "hex") const buf = Buffer.from(bchjs.Crypto.sha256(fixture.data), 'hex')
const signature = bchjs.HDNode.sign(hdnode1, buf) const signature = bchjs.HDNode.sign(hdnode1, buf)
const verify = bchjs.HDNode.verify(hdnode1, buf, signature) const verify = bchjs.HDNode.verify(hdnode1, buf, signature)
assert.equal(verify, true) assert.equal(verify, true)
@@ -312,46 +312,46 @@ describe("#HDNode", () => {
}) })
}) })
describe("#isPublic", () => { describe('#isPublic', () => {
fixtures.isPublic.forEach(fixture => { fixtures.isPublic.forEach(fixture => {
it(`should verify hdnode is public`, () => { it('should verify hdnode is public', () => {
const node = bchjs.HDNode.fromXPub(fixture.xpub) const node = bchjs.HDNode.fromXPub(fixture.xpub)
assert.equal(bchjs.HDNode.isPublic(node), true) assert.equal(bchjs.HDNode.isPublic(node), true)
}) })
}) })
fixtures.isPublic.forEach(fixture => { fixtures.isPublic.forEach(fixture => {
it(`should verify hdnode is not public`, () => { it('should verify hdnode is not public', () => {
const node = bchjs.HDNode.fromXPriv(fixture.xpriv) const node = bchjs.HDNode.fromXPriv(fixture.xpriv)
assert.equal(bchjs.HDNode.isPublic(node), false) assert.equal(bchjs.HDNode.isPublic(node), false)
}) })
}) })
}) })
describe("#isPrivate", () => { describe('#isPrivate', () => {
fixtures.isPrivate.forEach(fixture => { fixtures.isPrivate.forEach(fixture => {
it(`should verify hdnode is not private`, () => { it('should verify hdnode is not private', () => {
const node = bchjs.HDNode.fromXPub(fixture.xpub) const node = bchjs.HDNode.fromXPub(fixture.xpub)
assert.equal(bchjs.HDNode.isPrivate(node), false) assert.equal(bchjs.HDNode.isPrivate(node), false)
}) })
}) })
fixtures.isPrivate.forEach(fixture => { fixtures.isPrivate.forEach(fixture => {
it(`should verify hdnode is private`, () => { it('should verify hdnode is private', () => {
const node = bchjs.HDNode.fromXPriv(fixture.xpriv) const node = bchjs.HDNode.fromXPriv(fixture.xpriv)
assert.equal(bchjs.HDNode.isPrivate(node), true) assert.equal(bchjs.HDNode.isPrivate(node), true)
}) })
}) })
}) })
describe("#toIdentifier", () => { describe('#toIdentifier', () => {
fixtures.toIdentifier.forEach(fixture => { fixtures.toIdentifier.forEach(fixture => {
it(`should get identifier of hdnode`, () => { it('should get identifier of hdnode', () => {
const node = bchjs.HDNode.fromXPriv(fixture.xpriv) const node = bchjs.HDNode.fromXPriv(fixture.xpriv)
const publicKeyBuffer = bchjs.HDNode.toPublicKey(node) const publicKeyBuffer = bchjs.HDNode.toPublicKey(node)
const hash160 = bchjs.Crypto.hash160(publicKeyBuffer) const hash160 = bchjs.Crypto.hash160(publicKeyBuffer)
const identifier = bchjs.HDNode.toIdentifier(node) const identifier = bchjs.HDNode.toIdentifier(node)
assert.equal(identifier.toString("hex"), hash160.toString("hex")) assert.equal(identifier.toString('hex'), hash160.toString('hex'))
}) })
}) })
}) })
+146 -146
View File
@@ -2,14 +2,14 @@
Unit tests for the IPFS Class. Unit tests for the IPFS Class.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
const mockData = require("./fixtures/ipfs-mock") const mockData = require('./fixtures/ipfs-mock')
describe(`#IPFS`, () => { describe('#IPFS', () => {
let sandbox let sandbox
beforeEach(() => { beforeEach(() => {
@@ -20,203 +20,203 @@ describe(`#IPFS`, () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe("#initUppy", () => { describe('#initUppy', () => {
it("should initialize uppy", () => { it('should initialize uppy', () => {
bchjs.IPFS.initUppy() bchjs.IPFS.initUppy()
}) })
}) })
describe("#createFileModelServer", () => { describe('#createFileModelServer', () => {
it("should throw an error if file does not exist", async () => { it('should throw an error if file does not exist', async () => {
try { try {
const path = "/non-existant-file" const path = '/non-existant-file'
await bchjs.IPFS.createFileModelServer(path) await bchjs.IPFS.createFileModelServer(path)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `Could not find this file`) assert.include(err.message, 'Could not find this file')
} }
}) })
it("should create a new file model", async () => { it('should create a new file model', async () => {
const path = `${__dirname}/ipfs.js` const path = `${__dirname}/ipfs.js`
sandbox sandbox
.stub(bchjs.IPFS.axios, "post") .stub(bchjs.IPFS.axios, 'post')
.resolves({ data: mockData.mockNewFileModel }) .resolves({ data: mockData.mockNewFileModel })
const result = await bchjs.IPFS.createFileModelServer(path) const result = await bchjs.IPFS.createFileModelServer(path)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "hostingCostBCH") assert.property(result, 'hostingCostBCH')
assert.property(result, "hostingCostUSD") assert.property(result, 'hostingCostUSD')
assert.property(result, "file") assert.property(result, 'file')
assert.property(result.file, "payloadLink") assert.property(result.file, 'payloadLink')
assert.property(result.file, "hasBeenPaid") assert.property(result.file, 'hasBeenPaid')
assert.property(result.file, "_id") assert.property(result.file, '_id')
assert.property(result.file, "schemaVersion") assert.property(result.file, 'schemaVersion')
assert.property(result.file, "size") assert.property(result.file, 'size')
assert.property(result.file, "fileName") assert.property(result.file, 'fileName')
assert.property(result.file, "fileExtension") assert.property(result.file, 'fileExtension')
assert.property(result.file, "createdTimestamp") assert.property(result.file, 'createdTimestamp')
assert.property(result.file, "hostingCost") assert.property(result.file, 'hostingCost')
assert.property(result.file, "walletIndex") assert.property(result.file, 'walletIndex')
assert.property(result.file, "bchAddr") assert.property(result.file, 'bchAddr')
}) })
}) })
describe("#uploadFileServer", () => { describe('#uploadFileServer', () => {
it("should throw an error if file does not exist", async () => { it('should throw an error if file does not exist', async () => {
try { try {
const path = "/non-existant-file" const path = '/non-existant-file'
await bchjs.IPFS.uploadFileServer(path) await bchjs.IPFS.uploadFileServer(path)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `Could not find this file`) assert.include(err.message, 'Could not find this file')
} }
}) })
it("should throw an error if modelId is not included", async () => { it('should throw an error if modelId is not included', async () => {
try { try {
const path = `${__dirname}/ipfs.js` const path = `${__dirname}/ipfs.js`
await bchjs.IPFS.uploadFileServer(path) await bchjs.IPFS.uploadFileServer(path)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `Must include a file model ID`) assert.include(err.message, 'Must include a file model ID')
} }
}) })
it("Should throw error if the file was not uploaded", async () => { it('Should throw error if the file was not uploaded', async () => {
try { try {
const mock = { const mock = {
successful: [], successful: [],
failed: [ failed: [
{ {
id: "file id" id: 'file id'
} }
] ]
} }
sandbox.stub(bchjs.IPFS.uppy, "upload").resolves(mock) sandbox.stub(bchjs.IPFS.uppy, 'upload').resolves(mock)
const path = `${__dirname}/ipfs.js` const path = `${__dirname}/ipfs.js`
await bchjs.IPFS.uploadFileServer(path, "5ec562319bfacc745e8d8a52") await bchjs.IPFS.uploadFileServer(path, '5ec562319bfacc745e8d8a52')
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(err) // console.log(err)
assert.include(err.message, `The file could not be uploaded`) assert.include(err.message, 'The file could not be uploaded')
} }
}) })
it("should return file object if the file is uploaded", async () => { it('should return file object if the file is uploaded', async () => {
try { try {
sandbox.stub(bchjs.IPFS.uppy, "upload").resolves(mockData.uploadData) sandbox.stub(bchjs.IPFS.uppy, 'upload').resolves(mockData.uploadData)
const path = `${__dirname}/ipfs.js` const path = `${__dirname}/ipfs.js`
const result = await bchjs.IPFS.uploadFileServer( const result = await bchjs.IPFS.uploadFileServer(
path, path,
"5ec562319bfacc745e8d8a52" '5ec562319bfacc745e8d8a52'
) )
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "schemaVersion") assert.property(result, 'schemaVersion')
assert.property(result, "size") assert.property(result, 'size')
assert.property(result, "fileId") assert.property(result, 'fileId')
assert.property(result, "fileName") assert.property(result, 'fileName')
assert.property(result, "fileExtension") assert.property(result, 'fileExtension')
} catch (err) { } catch (err) {
// console.log(err) // console.log(err)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} }
}) })
}) })
describe("#getStatus", () => { describe('#getStatus', () => {
it("should throw an error if modelId is not included", async () => { it('should throw an error if modelId is not included', async () => {
try { try {
await bchjs.IPFS.getStatus() await bchjs.IPFS.getStatus()
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `Must include a file model ID`) assert.include(err.message, 'Must include a file model ID')
} }
}) })
it("should get data on an unpaid file", async () => { it('should get data on an unpaid file', async () => {
const modelId = "5ec7392c2acfe57aa62e945a" const modelId = '5ec7392c2acfe57aa62e945a'
sandbox sandbox
.stub(bchjs.IPFS.axios, "get") .stub(bchjs.IPFS.axios, 'get')
.resolves({ data: mockData.unpaidFileData }) .resolves({ data: mockData.unpaidFileData })
const result = await bchjs.IPFS.getStatus(modelId) const result = await bchjs.IPFS.getStatus(modelId)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "hasBeenPaid") assert.property(result, 'hasBeenPaid')
assert.property(result, "satCost") assert.property(result, 'satCost')
assert.property(result, "bchAddr") assert.property(result, 'bchAddr')
assert.property(result, "ipfsHash") assert.property(result, 'ipfsHash')
assert.property(result, "fileId") assert.property(result, 'fileId')
assert.property(result, "fileName") assert.property(result, 'fileName')
}) })
it("should get data on an unpaid file", async () => { it('should get data on an unpaid file', async () => {
const modelId = "5ec7392c2acfe57aa62e945a" const modelId = '5ec7392c2acfe57aa62e945a'
sandbox sandbox
.stub(bchjs.IPFS.axios, "get") .stub(bchjs.IPFS.axios, 'get')
.resolves({ data: mockData.paidFileData }) .resolves({ data: mockData.paidFileData })
const result = await bchjs.IPFS.getStatus(modelId) const result = await bchjs.IPFS.getStatus(modelId)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "hasBeenPaid") assert.property(result, 'hasBeenPaid')
assert.property(result, "satCost") assert.property(result, 'satCost')
assert.property(result, "bchAddr") assert.property(result, 'bchAddr')
assert.property(result, "ipfsHash") assert.property(result, 'ipfsHash')
assert.property(result, "fileId") assert.property(result, 'fileId')
assert.property(result, "fileName") assert.property(result, 'fileName')
}) })
}) })
describe("#createFileModelWeb", () => { describe('#createFileModelWeb', () => {
it("should throw an error if file is undefined", async () => { it('should throw an error if file is undefined', async () => {
try { try {
let file let file
await bchjs.IPFS.createFileModelWeb(file) await bchjs.IPFS.createFileModelWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `File is required`) assert.include(err.message, 'File is required')
} }
}) })
it("should throw an error if file is empty", async () => { it('should throw an error if file is empty', async () => {
try { try {
const file = {} const file = {}
await bchjs.IPFS.createFileModelWeb(file) await bchjs.IPFS.createFileModelWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'name' of string type` 'File should have the property \'name\' of string type'
) )
} }
}) })
@@ -228,12 +228,12 @@ describe(`#IPFS`, () => {
await bchjs.IPFS.createFileModelWeb(file) await bchjs.IPFS.createFileModelWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'name' of string type` 'File should have the property \'name\' of string type'
) )
} }
}) })
@@ -241,80 +241,80 @@ describe(`#IPFS`, () => {
it("should throw an error if 'size' property is not included", async () => { it("should throw an error if 'size' property is not included", async () => {
try { try {
const file = { const file = {
name: "ipfs.js" name: 'ipfs.js'
} }
await bchjs.IPFS.createFileModelWeb(file) await bchjs.IPFS.createFileModelWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'size' of number type` 'File should have the property \'size\' of number type'
) )
} }
}) })
it("should create a new file model", async () => { it('should create a new file model', async () => {
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
size: 5000, size: 5000,
type: "text/plain" type: 'text/plain'
} }
sandbox sandbox
.stub(bchjs.IPFS.axios, "post") .stub(bchjs.IPFS.axios, 'post')
.resolves({ data: mockData.mockNewFileModel }) .resolves({ data: mockData.mockNewFileModel })
const result = await bchjs.IPFS.createFileModelWeb(file) const result = await bchjs.IPFS.createFileModelWeb(file)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "success") assert.property(result, 'success')
assert.equal(result.success, true) assert.equal(result.success, true)
assert.property(result, "hostingCostBCH") assert.property(result, 'hostingCostBCH')
assert.property(result, "hostingCostUSD") assert.property(result, 'hostingCostUSD')
assert.property(result, "file") assert.property(result, 'file')
assert.property(result.file, "payloadLink") assert.property(result.file, 'payloadLink')
assert.property(result.file, "hasBeenPaid") assert.property(result.file, 'hasBeenPaid')
assert.property(result.file, "_id") assert.property(result.file, '_id')
assert.property(result.file, "schemaVersion") assert.property(result.file, 'schemaVersion')
assert.property(result.file, "size") assert.property(result.file, 'size')
assert.property(result.file, "fileName") assert.property(result.file, 'fileName')
assert.property(result.file, "fileExtension") assert.property(result.file, 'fileExtension')
assert.property(result.file, "createdTimestamp") assert.property(result.file, 'createdTimestamp')
assert.property(result.file, "hostingCost") assert.property(result.file, 'hostingCost')
assert.property(result.file, "walletIndex") assert.property(result.file, 'walletIndex')
assert.property(result.file, "bchAddr") assert.property(result.file, 'bchAddr')
}) })
}) })
describe("#uploadFileWeb", () => { describe('#uploadFileWeb', () => {
it("should throw an error if file is undefined", async () => { it('should throw an error if file is undefined', async () => {
try { try {
let file let file
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `File is required`) assert.include(err.message, 'File is required')
} }
}) })
it("should throw an error if file is empty", async () => { it('should throw an error if file is empty', async () => {
try { try {
const file = {} const file = {}
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'name' of string type` 'File should have the property \'name\' of string type'
) )
} }
}) })
@@ -322,121 +322,121 @@ describe(`#IPFS`, () => {
try { try {
const file = { const file = {
size: 5000, size: 5000,
type: "text/plain" type: 'text/plain'
} }
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'name' of string type` 'File should have the property \'name\' of string type'
) )
} }
}) })
it("should throw an error if 'size' property is not included", async () => { it("should throw an error if 'size' property is not included", async () => {
try { try {
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
type: "text/plain" type: 'text/plain'
} }
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'size' of number type` 'File should have the property \'size\' of number type'
) )
} }
}) })
it("should throw an error if 'type' property is not included", async () => { it("should throw an error if 'type' property is not included", async () => {
try { try {
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
size: 5000 size: 5000
} }
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include( assert.include(
err.message, err.message,
`File should have the property 'type' of string type` 'File should have the property \'type\' of string type'
) )
} }
}) })
it("should throw an error if modelId is not included", async () => { it('should throw an error if modelId is not included', async () => {
try { try {
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
size: 5000, size: 5000,
type: "text/plain" type: 'text/plain'
} }
await bchjs.IPFS.uploadFileWeb(file) await bchjs.IPFS.uploadFileWeb(file)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(`err.message: ${err.message}`) // console.log(`err.message: ${err.message}`)
assert.include(err.message, `Must include a file model ID`) assert.include(err.message, 'Must include a file model ID')
} }
}) })
it("Should throw error if the file was not uploaded", async () => { it('Should throw error if the file was not uploaded', async () => {
try { try {
const mock = { const mock = {
successful: [], successful: [],
failed: [ failed: [
{ {
id: "file id" id: 'file id'
} }
] ]
} }
sandbox.stub(bchjs.IPFS.uppy, "upload").resolves(mock) sandbox.stub(bchjs.IPFS.uppy, 'upload').resolves(mock)
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
size: 5000, size: 5000,
type: "text/plain" type: 'text/plain'
} }
await bchjs.IPFS.uploadFileWeb(file, "5ec562319bfacc745e8d8a52") await bchjs.IPFS.uploadFileWeb(file, '5ec562319bfacc745e8d8a52')
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} catch (err) { } catch (err) {
// console.log(err) // console.log(err)
assert.include(err.message, `The file could not be uploaded`) assert.include(err.message, 'The file could not be uploaded')
} }
}) })
it("should return file object if the file is uploaded", async () => { it('should return file object if the file is uploaded', async () => {
try { try {
sandbox.stub(bchjs.IPFS.uppy, "upload").resolves(mockData.uploadData) sandbox.stub(bchjs.IPFS.uppy, 'upload').resolves(mockData.uploadData)
const file = { const file = {
name: "ipfs.js", name: 'ipfs.js',
size: 5000, size: 5000,
type: "text/plain" type: 'text/plain'
} }
const result = await bchjs.IPFS.uploadFileWeb( const result = await bchjs.IPFS.uploadFileWeb(
file, file,
"5ec562319bfacc745e8d8a52" '5ec562319bfacc745e8d8a52'
) )
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "schemaVersion") assert.property(result, 'schemaVersion')
assert.property(result, "size") assert.property(result, 'size')
assert.property(result, "fileId") assert.property(result, 'fileId')
assert.property(result, "fileName") assert.property(result, 'fileName')
assert.property(result, "fileExtension") assert.property(result, 'fileExtension')
} catch (err) { } catch (err) {
// console.log(err) // console.log(err)
assert.equal(true, false, "Unexpected result") assert.equal(true, false, 'Unexpected result')
} }
}) })
}) })
+23 -23
View File
@@ -1,39 +1,39 @@
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
describe("#Mining", () => { describe('#Mining', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#getBlockTemplate", () => { describe('#getBlockTemplate', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get block template", done => { it('should get block template', done => {
const data = { const data = {
data: data:
"01000000017f6305e3b0b05f5b57a82f4e6d4187e148bbe56a947208390e488bad36472368000000006a47304402203b0079ff5b896187feb02e2679c87ac2fb8d483b60e0721ed33601e2c0eecc700220590f8a0e1a51b53b368294861fd5fc99db3a6607d0f4e543f6217108e208c1834121024c93c841d7f576584ffbf513b7abd8283e6562669905f6554f788fce4cc67a34ffffffff0228100000000000001976a914af78709a76abc8a28e568c9210c8247dd10cff2c88ac22020000000000001976a914f339927678803f451b41400737e7dc83c6a8682188ac00000000", '01000000017f6305e3b0b05f5b57a82f4e6d4187e148bbe56a947208390e488bad36472368000000006a47304402203b0079ff5b896187feb02e2679c87ac2fb8d483b60e0721ed33601e2c0eecc700220590f8a0e1a51b53b368294861fd5fc99db3a6607d0f4e543f6217108e208c1834121024c93c841d7f576584ffbf513b7abd8283e6562669905f6554f788fce4cc67a34ffffffff0228100000000000001976a914af78709a76abc8a28e568c9210c8247dd10cff2c88ac22020000000000001976a914f339927678803f451b41400737e7dc83c6a8682188ac00000000',
txid: txid:
"7f462d71c649a0d8cfbaa2d20d8ff86677966b308f0ac9906ee015bf4453f97a", '7f462d71c649a0d8cfbaa2d20d8ff86677966b308f0ac9906ee015bf4453f97a',
hash: hash:
"7f462d71c649a0d8cfbaa2d20d8ff86677966b308f0ac9906ee015bf4453f97a", '7f462d71c649a0d8cfbaa2d20d8ff86677966b308f0ac9906ee015bf4453f97a',
depends: [], depends: [],
fee: 226, fee: 226,
sigops: 2 sigops: 2
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Mining.getBlockTemplate("") bchjs.Mining.getBlockTemplate('')
.then(result => { .then(result => {
assert.deepEqual(data, result) assert.deepEqual(data, result)
}) })
@@ -41,26 +41,26 @@ describe("#Mining", () => {
}) })
}) })
describe("#getMiningInfo", () => { describe('#getMiningInfo', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get mining info", done => { it('should get mining info', done => {
const data = { const data = {
blocks: 527816, blocks: 527816,
currentblocksize: 89408, currentblocksize: 89408,
currentblocktx: 156, currentblocktx: 156,
difficulty: 568757800682.7649, difficulty: 568757800682.7649,
blockprioritypercentage: 5, blockprioritypercentage: 5,
errors: "", errors: '',
networkhashps: 4347259225696976000, networkhashps: 4347259225696976000,
pooledtx: 184, pooledtx: 184,
chain: "main" chain: 'main'
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Mining.getMiningInfo() bchjs.Mining.getMiningInfo()
.then(result => { .then(result => {
@@ -70,16 +70,16 @@ describe("#Mining", () => {
}) })
}) })
describe("#getNetworkHashps", () => { describe('#getNetworkHashps', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get network hashps", done => { it('should get network hashps', done => {
const data = 3586365937646890000 const data = 3586365937646890000
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.Mining.getNetworkHashps() bchjs.Mining.getNetworkHashps()
.then(result => { .then(result => {
@@ -89,17 +89,17 @@ describe("#Mining", () => {
}) })
}) })
describe("#submitBlock", () => { describe('#submitBlock', () => {
// TODO finish // TODO finish
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should TODO", done => { it('should TODO', done => {
const data = {} const data = {}
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved) sandbox.stub(axios, 'post').returns(resolved)
bchjs.Mining.submitBlock() bchjs.Mining.submitBlock()
.then(result => { .then(result => {
+90 -90
View File
@@ -1,82 +1,82 @@
const fixtures = require("./fixtures/mnemonic.json") const fixtures = require('./fixtures/mnemonic.json')
const assert = require("assert") const assert = require('assert')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
describe("#Mnemonic", () => { describe('#Mnemonic', () => {
describe("#generate", () => { describe('#generate', () => {
it("should generate a 12 word mnemonic", () => { it('should generate a 12 word mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(128) const mnemonic = bchjs.Mnemonic.generate(128)
assert.equal(mnemonic.split(" ").length, 12) assert.equal(mnemonic.split(' ').length, 12)
}) })
it("should generate a 15 word mnemonic", () => { it('should generate a 15 word mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(160) const mnemonic = bchjs.Mnemonic.generate(160)
assert.equal(mnemonic.split(" ").length, 15) assert.equal(mnemonic.split(' ').length, 15)
}) })
it("should generate a 18 word mnemonic", () => { it('should generate a 18 word mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(192) const mnemonic = bchjs.Mnemonic.generate(192)
assert.equal(mnemonic.split(" ").length, 18) assert.equal(mnemonic.split(' ').length, 18)
}) })
it("should generate an 21 word mnemonic", () => { it('should generate an 21 word mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(224) const mnemonic = bchjs.Mnemonic.generate(224)
assert.equal(mnemonic.split(" ").length, 21) assert.equal(mnemonic.split(' ').length, 21)
}) })
it("should generate an 24 word mnemonic", () => { it('should generate an 24 word mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(256) const mnemonic = bchjs.Mnemonic.generate(256)
assert.equal(mnemonic.split(" ").length, 24) assert.equal(mnemonic.split(' ').length, 24)
}) })
it("should generate an 24 word italian mnemonic", () => { it('should generate an 24 word italian mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate( const mnemonic = bchjs.Mnemonic.generate(
256, 256,
bchjs.Mnemonic.wordLists().italian bchjs.Mnemonic.wordLists().italian
) )
assert.equal(mnemonic.split(" ").length, 24) assert.equal(mnemonic.split(' ').length, 24)
}) })
}) })
describe("#fromEntropy", () => { describe('#fromEntropy', () => {
it("should generate a 12 word mnemonic from 16 bytes of entropy", () => { it('should generate a 12 word mnemonic from 16 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(16) const rand = bchjs.Crypto.randomBytes(16)
const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString("hex")) const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString('hex'))
assert.equal(mnemonic.split(" ").length, 12) assert.equal(mnemonic.split(' ').length, 12)
}) })
it("should generate a 15 word mnemonic from 20 bytes of entropy", () => { it('should generate a 15 word mnemonic from 20 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(20) const rand = bchjs.Crypto.randomBytes(20)
const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString("hex")) const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString('hex'))
assert.equal(mnemonic.split(" ").length, 15) assert.equal(mnemonic.split(' ').length, 15)
}) })
it("should generate an 18 word mnemonic from 24 bytes of entropy", () => { it('should generate an 18 word mnemonic from 24 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(24) const rand = bchjs.Crypto.randomBytes(24)
const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString("hex")) const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString('hex'))
assert.equal(mnemonic.split(" ").length, 18) assert.equal(mnemonic.split(' ').length, 18)
}) })
it("should generate an 21 word mnemonic from 28 bytes of entropy", () => { it('should generate an 21 word mnemonic from 28 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(28) const rand = bchjs.Crypto.randomBytes(28)
const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString("hex")) const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString('hex'))
assert.equal(mnemonic.split(" ").length, 21) assert.equal(mnemonic.split(' ').length, 21)
}) })
it("should generate an 24 word mnemonic from 32 bytes of entropy", () => { it('should generate an 24 word mnemonic from 32 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(32) const rand = bchjs.Crypto.randomBytes(32)
const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString("hex")) const mnemonic = bchjs.Mnemonic.fromEntropy(rand.toString('hex'))
assert.equal(mnemonic.split(" ").length, 24) assert.equal(mnemonic.split(' ').length, 24)
}) })
it("should generate an 24 french word mnemonic 32 bytes of entropy", () => { it('should generate an 24 french word mnemonic 32 bytes of entropy', () => {
const rand = bchjs.Crypto.randomBytes(32) const rand = bchjs.Crypto.randomBytes(32)
const mnemonic = bchjs.Mnemonic.fromEntropy( const mnemonic = bchjs.Mnemonic.fromEntropy(
rand.toString("hex"), rand.toString('hex'),
bchjs.Mnemonic.wordLists().french bchjs.Mnemonic.wordLists().french
) )
assert.equal(mnemonic.split(" ").length, 24) assert.equal(mnemonic.split(' ').length, 24)
}) })
fixtures.fromEntropy.forEach(entropy => { fixtures.fromEntropy.forEach(entropy => {
@@ -87,38 +87,38 @@ describe("#Mnemonic", () => {
}) })
}) })
describe("#toEntropy", () => { describe('#toEntropy', () => {
it("should turn a 12 word mnemonic to entropy", () => { it('should turn a 12 word mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate(128) const mnemonic = bchjs.Mnemonic.generate(128)
const entropy = bchjs.Mnemonic.toEntropy(mnemonic) const entropy = bchjs.Mnemonic.toEntropy(mnemonic)
assert.equal(entropy.length, 16) assert.equal(entropy.length, 16)
}) })
it("should turn a 15 word mnemonic to entropy", () => { it('should turn a 15 word mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate(160) const mnemonic = bchjs.Mnemonic.generate(160)
const entropy = bchjs.Mnemonic.toEntropy(mnemonic) const entropy = bchjs.Mnemonic.toEntropy(mnemonic)
assert.equal(entropy.length, 20) assert.equal(entropy.length, 20)
}) })
it("should turn a 18 word mnemonic to entropy", () => { it('should turn a 18 word mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate(192) const mnemonic = bchjs.Mnemonic.generate(192)
const entropy = bchjs.Mnemonic.toEntropy(mnemonic) const entropy = bchjs.Mnemonic.toEntropy(mnemonic)
assert.equal(entropy.length, 24) assert.equal(entropy.length, 24)
}) })
it("should turn a 21 word mnemonic to entropy", () => { it('should turn a 21 word mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate(224) const mnemonic = bchjs.Mnemonic.generate(224)
const entropy = bchjs.Mnemonic.toEntropy(mnemonic) const entropy = bchjs.Mnemonic.toEntropy(mnemonic)
assert.equal(entropy.length, 28) assert.equal(entropy.length, 28)
}) })
it("should turn a 24 word mnemonic to entropy", () => { it('should turn a 24 word mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate(256) const mnemonic = bchjs.Mnemonic.generate(256)
const entropy = bchjs.Mnemonic.toEntropy(mnemonic) const entropy = bchjs.Mnemonic.toEntropy(mnemonic)
assert.equal(entropy.length, 32) assert.equal(entropy.length, 32)
}) })
it("should turn a 24 word spanish mnemonic to entropy", () => { it('should turn a 24 word spanish mnemonic to entropy', () => {
const mnemonic = bchjs.Mnemonic.generate( const mnemonic = bchjs.Mnemonic.generate(
256, 256,
bchjs.Mnemonic.wordLists().spanish bchjs.Mnemonic.wordLists().spanish
@@ -133,83 +133,83 @@ describe("#Mnemonic", () => {
fixtures.fromEntropy.forEach(fixture => { fixtures.fromEntropy.forEach(fixture => {
const entropy = bchjs.Mnemonic.toEntropy(fixture.mnemonic) const entropy = bchjs.Mnemonic.toEntropy(fixture.mnemonic)
it(`should convert ${fixture.mnemonic} to ${fixture.entropy}`, () => { it(`should convert ${fixture.mnemonic} to ${fixture.entropy}`, () => {
assert.equal(entropy.toString("hex"), fixture.entropy) assert.equal(entropy.toString('hex'), fixture.entropy)
}) })
}) })
}) })
describe("#validate", () => { describe('#validate', () => {
it("fails for a mnemonic that is too short", () => { it('fails for a mnemonic that is too short', () => {
assert.equal( assert.equal(
bchjs.Mnemonic.validate( bchjs.Mnemonic.validate(
"mixed winner", 'mixed winner',
bchjs.Mnemonic.wordLists().english bchjs.Mnemonic.wordLists().english
), ),
"Invalid mnemonic" 'Invalid mnemonic'
) )
}) })
it("fails for a mnemonic that is too long", () => { it('fails for a mnemonic that is too long', () => {
assert.equal( assert.equal(
bchjs.Mnemonic.validate( bchjs.Mnemonic.validate(
"mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake", 'mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake mixed winner decide drift danger together twice planet impose asthma catch require select mask awkward spy relief front work solar pitch economy render cake',
bchjs.Mnemonic.wordLists().english bchjs.Mnemonic.wordLists().english
), ),
"Invalid mnemonic" 'Invalid mnemonic'
) )
}) })
it("fails if mnemonic words are not in the word list", () => { it('fails if mnemonic words are not in the word list', () => {
assert.equal( assert.equal(
bchjs.Mnemonic.validate( bchjs.Mnemonic.validate(
"failsauce one two three four five six seven eight nine ten eleven", 'failsauce one two three four five six seven eight nine ten eleven',
bchjs.Mnemonic.wordLists().english bchjs.Mnemonic.wordLists().english
), ),
"failsauce is not in wordlist, did you mean balance?" 'failsauce is not in wordlist, did you mean balance?'
) )
}) })
it("validate a 128 bit mnemonic", () => { it('validate a 128 bit mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(128) const mnemonic = bchjs.Mnemonic.generate(128)
assert.equal( assert.equal(
bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english), bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
it("validate a 160 bit mnemonic", () => { it('validate a 160 bit mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(160) const mnemonic = bchjs.Mnemonic.generate(160)
assert.equal( assert.equal(
bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english), bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
it("validate a 192 bit mnemonic", () => { it('validate a 192 bit mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(192) const mnemonic = bchjs.Mnemonic.generate(192)
assert.equal( assert.equal(
bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english), bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
it("validate a 224 bit mnemonic", () => { it('validate a 224 bit mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(224) const mnemonic = bchjs.Mnemonic.generate(224)
assert.equal( assert.equal(
bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english), bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
it("validate a 256 bit mnemonic", () => { it('validate a 256 bit mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate(256) const mnemonic = bchjs.Mnemonic.generate(256)
assert.equal( assert.equal(
bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english), bchjs.Mnemonic.validate(mnemonic, bchjs.Mnemonic.wordLists().english),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
it("validate a 256 bit chinese simplified mnemonic", () => { it('validate a 256 bit chinese simplified mnemonic', () => {
const mnemonic = bchjs.Mnemonic.generate( const mnemonic = bchjs.Mnemonic.generate(
256, 256,
bchjs.Mnemonic.wordLists().chinese_simplified bchjs.Mnemonic.wordLists().chinese_simplified
@@ -219,82 +219,82 @@ describe("#Mnemonic", () => {
mnemonic, mnemonic,
bchjs.Mnemonic.wordLists().chinese_simplified bchjs.Mnemonic.wordLists().chinese_simplified
), ),
"Valid mnemonic" 'Valid mnemonic'
) )
}) })
}) })
describe("#toSeed", () => { describe('#toSeed', () => {
it("should create 512 bit / 64 byte HMAC-SHA512 root seed from a 128 bit mnemonic", async () => { it('should create 512 bit / 64 byte HMAC-SHA512 root seed from a 128 bit mnemonic', async () => {
const mnemonic = bchjs.Mnemonic.generate(128) const mnemonic = bchjs.Mnemonic.generate(128)
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, "") const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, '')
assert.equal(rootSeedBuffer.byteLength, 64) assert.equal(rootSeedBuffer.byteLength, 64)
}) })
it("should create 512 bit / 64 byte HMAC-SHA512 root seed from a 160 bit mnemonic", async () => { it('should create 512 bit / 64 byte HMAC-SHA512 root seed from a 160 bit mnemonic', async () => {
const mnemonic = bchjs.Mnemonic.generate(160) const mnemonic = bchjs.Mnemonic.generate(160)
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, "") const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, '')
assert.equal(rootSeedBuffer.byteLength, 64) assert.equal(rootSeedBuffer.byteLength, 64)
}) })
it("should create 512 bit / 64 byte HMAC-SHA512 root seed from a 192 bit mnemonic", async () => { it('should create 512 bit / 64 byte HMAC-SHA512 root seed from a 192 bit mnemonic', async () => {
const mnemonic = bchjs.Mnemonic.generate(192) const mnemonic = bchjs.Mnemonic.generate(192)
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, "") const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, '')
assert.equal(rootSeedBuffer.byteLength, 64) assert.equal(rootSeedBuffer.byteLength, 64)
}) })
it("should create 512 bit / 64 byte HMAC-SHA512 root seed from a 224 bit mnemonic", async () => { it('should create 512 bit / 64 byte HMAC-SHA512 root seed from a 224 bit mnemonic', async () => {
const mnemonic = bchjs.Mnemonic.generate(224) const mnemonic = bchjs.Mnemonic.generate(224)
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, "") const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, '')
assert.equal(rootSeedBuffer.byteLength, 64) assert.equal(rootSeedBuffer.byteLength, 64)
}) })
it("should create 512 bit / 64 byte HMAC-SHA512 root seed from a 256 bit mnemonic", async () => { it('should create 512 bit / 64 byte HMAC-SHA512 root seed from a 256 bit mnemonic', async () => {
const mnemonic = bchjs.Mnemonic.generate(256) const mnemonic = bchjs.Mnemonic.generate(256)
const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, "") const rootSeedBuffer = await bchjs.Mnemonic.toSeed(mnemonic, '')
assert.equal(rootSeedBuffer.byteLength, 64) assert.equal(rootSeedBuffer.byteLength, 64)
}) })
}) })
describe("#wordLists", () => { describe('#wordLists', () => {
it("return a list of 2048 english words", () => { it('return a list of 2048 english words', () => {
assert.equal(bchjs.Mnemonic.wordLists().english.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().english.length, 2048)
}) })
it("return a list of 2048 japanese words", () => { it('return a list of 2048 japanese words', () => {
assert.equal(bchjs.Mnemonic.wordLists().japanese.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().japanese.length, 2048)
}) })
it("return a list of 2048 chinese simplified words", () => { it('return a list of 2048 chinese simplified words', () => {
assert.equal(bchjs.Mnemonic.wordLists().chinese_simplified.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().chinese_simplified.length, 2048)
}) })
it("return a list of 2048 chinese traditional words", () => { it('return a list of 2048 chinese traditional words', () => {
assert.equal(bchjs.Mnemonic.wordLists().chinese_traditional.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().chinese_traditional.length, 2048)
}) })
it("return a list of 2048 french words", () => { it('return a list of 2048 french words', () => {
assert.equal(bchjs.Mnemonic.wordLists().french.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().french.length, 2048)
}) })
it("return a list of 2048 italian words", () => { it('return a list of 2048 italian words', () => {
assert.equal(bchjs.Mnemonic.wordLists().italian.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().italian.length, 2048)
}) })
it("return a list of 2048 korean words", () => { it('return a list of 2048 korean words', () => {
assert.equal(bchjs.Mnemonic.wordLists().korean.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().korean.length, 2048)
}) })
it("return a list of 2048 spanish words", () => { it('return a list of 2048 spanish words', () => {
assert.equal(bchjs.Mnemonic.wordLists().spanish.length, 2048) assert.equal(bchjs.Mnemonic.wordLists().spanish.length, 2048)
}) })
}) })
describe("#toKeypairs", async () => { describe('#toKeypairs', async () => {
fixtures.toKeypairs.forEach(async (fixture, i) => { fixtures.toKeypairs.forEach(async (fixture, i) => {
const keypairs = await bchjs.Mnemonic.toKeypairs(fixture.mnemonic, 5) const keypairs = await bchjs.Mnemonic.toKeypairs(fixture.mnemonic, 5)
keypairs.forEach((keypair, j) => { keypairs.forEach((keypair, j) => {
it(`Generate keypair from mnemonic`, () => { it('Generate keypair from mnemonic', () => {
assert.equal( assert.equal(
keypair.privateKeyWIF, keypair.privateKeyWIF,
fixtures.toKeypairs[i].output[j].privateKeyWIF fixtures.toKeypairs[i].output[j].privateKeyWIF
@@ -312,7 +312,7 @@ describe("#Mnemonic", () => {
true true
) )
regtestKeypairs.forEach((keypair, j) => { regtestKeypairs.forEach((keypair, j) => {
it(`Generate keypair from mnemonic`, () => { it('Generate keypair from mnemonic', () => {
assert.equal( assert.equal(
keypair.privateKeyWIF, keypair.privateKeyWIF,
fixtures.toKeypairs[i].output[j].privateKeyWIFRegTest fixtures.toKeypairs[i].output[j].privateKeyWIFRegTest
@@ -326,7 +326,7 @@ describe("#Mnemonic", () => {
}) })
}) })
describe("#findNearestWord", () => { describe('#findNearestWord', () => {
fixtures.findNearestWord.forEach((fixture, i) => { fixtures.findNearestWord.forEach((fixture, i) => {
const word = bchjs.Mnemonic.findNearestWord( const word = bchjs.Mnemonic.findNearestWord(
fixture.word, fixture.word,
+110 -110
View File
@@ -1,67 +1,67 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const mockData = require("./fixtures/ninsight-mock") const mockData = require('./fixtures/ninsight-mock')
describe(`#Ninsight`, () => { describe('#Ninsight', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Ninsight.utxo(addr) await bchjs.Ninsight.utxo(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings.` 'Input address must be a string or array of strings.'
) )
} }
}) })
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.utxo }) sandbox.stub(axios, 'post').resolves({ data: mockData.utxo })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.property(result, "legacyAddress") assert.property(result, 'legacyAddress')
assert.property(result, "cashAddress") assert.property(result, 'cashAddress')
assert.property(result, "slpAddress") assert.property(result, 'slpAddress')
assert.property(result, "scriptPubKey") assert.property(result, 'scriptPubKey')
assert.property(result, "asm") assert.property(result, 'asm')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "txid") assert.property(result.utxos[0], 'txid')
assert.property(result.utxos[0], "vout") assert.property(result.utxos[0], 'vout')
assert.property(result.utxos[0], "amount") assert.property(result.utxos[0], 'amount')
assert.property(result.utxos[0], "satoshis") assert.property(result.utxos[0], 'satoshis')
assert.property(result.utxos[0], "height") assert.property(result.utxos[0], 'height')
assert.property(result.utxos[0], "confirmations") assert.property(result.utxos[0], 'confirmations')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
// Mock the network call. // Mock the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.utxoPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.utxoPost })
const addr = [ const addr = [
"bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7", 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr" 'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
] ]
const result = await bchjs.Ninsight.utxo(addr) const result = await bchjs.Ninsight.utxo(addr)
@@ -70,62 +70,62 @@ describe(`#Ninsight`, () => {
assert.isArray(result) assert.isArray(result)
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
assert.property(result[0], "asm") assert.property(result[0], 'asm')
}) })
}) })
describe("#unconfirmed", () => { describe('#unconfirmed', () => {
it("should throw an error for improper input", async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Ninsight.unconfirmed(addr) await bchjs.Ninsight.unconfirmed(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
assert.include( assert.include(
err.message, err.message,
"Input address must be a string or array of strings." 'Input address must be a string or array of strings.'
) )
} }
}) })
it(`should POST utxos for a single address`, async () => { it('should POST utxos for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.unconfirmed }) sandbox.stub(axios, 'post').resolves({ data: mockData.unconfirmed })
const addr = "bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5" const addr = 'bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5'
const result = await bchjs.Ninsight.unconfirmed(addr) const result = await bchjs.Ninsight.unconfirmed(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, "utxos") assert.property(result, 'utxos')
assert.property(result, "legacyAddress") assert.property(result, 'legacyAddress')
assert.property(result, "cashAddress") assert.property(result, 'cashAddress')
assert.property(result, "slpAddress") assert.property(result, 'slpAddress')
assert.property(result, "scriptPubKey") assert.property(result, 'scriptPubKey')
assert.isArray(result.utxos) assert.isArray(result.utxos)
assert.property(result.utxos[0], "txid") assert.property(result.utxos[0], 'txid')
assert.property(result.utxos[0], "vout") assert.property(result.utxos[0], 'vout')
assert.property(result.utxos[0], "amount") assert.property(result.utxos[0], 'amount')
assert.property(result.utxos[0], "satoshis") assert.property(result.utxos[0], 'satoshis')
assert.property(result.utxos[0], "confirmations") assert.property(result.utxos[0], 'confirmations')
assert.property(result.utxos[0], "ts") assert.property(result.utxos[0], 'ts')
}) })
it(`should POST utxo details for an array of addresses`, async () => { it('should POST utxo details for an array of addresses', async () => {
// Mock the network call. // Mock the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.unconfirmedPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.unconfirmedPost })
const addr = [ const addr = [
"bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5", 'bitcoincash:qpkkjkhe29mqhqmu3evtq3dsnruuzl3rku6usknlh5',
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr" 'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
] ]
const result = await bchjs.Ninsight.unconfirmed(addr) const result = await bchjs.Ninsight.unconfirmed(addr)
@@ -134,122 +134,122 @@ describe(`#Ninsight`, () => {
assert.isArray(result) assert.isArray(result)
assert.isArray(result[0].utxos) assert.isArray(result[0].utxos)
assert.property(result[0], "utxos") assert.property(result[0], 'utxos')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "slpAddress") assert.property(result[0], 'slpAddress')
assert.property(result[0], "scriptPubKey") assert.property(result[0], 'scriptPubKey')
}) })
}) })
describe(`#transactions`, () => { describe('#transactions', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.Ninsight.transactions(addr) await bchjs.Ninsight.transactions(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Input address must be a string or array of strings.` 'Input address must be a string or array of strings.'
) )
} }
}) })
it(`should POST transaction history for a single address`, async () => { it('should POST transaction history for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.transactionsPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.transactionsPost })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
assert.property(result[0].txs[0], "vin") assert.property(result[0].txs[0], 'vin')
assert.property(result[0].txs[0], "vout") assert.property(result[0].txs[0], 'vout')
}) })
it(`should POST transaction history for an array of addresses`, async () => { it('should POST transaction history for an array of addresses', async () => {
// Mock the network call. // Mock the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.transactionsPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.transactionsPost })
const addr = [ const addr = [
"bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7", 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
"bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr" 'bitcoincash:qz0us0z6ucpqt07jgpad0shgh7xmwxyr3ynlcsq0wr'
] ]
const result = await bchjs.Ninsight.transactions(addr) const result = await bchjs.Ninsight.transactions(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "cashAddress") assert.property(result[0], 'cashAddress')
assert.property(result[0], "legacyAddress") assert.property(result[0], 'legacyAddress')
assert.property(result[0], "txs") assert.property(result[0], 'txs')
assert.isArray(result[0].txs) assert.isArray(result[0].txs)
assert.property(result[0].txs[0], "txid") assert.property(result[0].txs[0], 'txid')
}) })
}) })
describe(`#txDetails`, () => { describe('#txDetails', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const txid = 12345 const txid = 12345
await bchjs.Ninsight.txDetails(txid) await bchjs.Ninsight.txDetails(txid)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include( assert.include(
err.message, err.message,
`Transaction ID must be a string or array of strings.` 'Transaction ID must be a string or array of strings.'
) )
} }
}) })
it(`should POST transaction details for a single TxID`, async () => { it('should POST transaction details for a single TxID', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.detailsPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.detailsPost })
const txid = "fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33" const txid = 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "version") assert.property(result[0], 'version')
assert.property(result[0], "locktime") assert.property(result[0], 'locktime')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
assert.property(result[0], "blockhash") assert.property(result[0], 'blockhash')
assert.property(result[0], "blockheight") assert.property(result[0], 'blockheight')
assert.property(result[0], "confirmations") assert.property(result[0], 'confirmations')
assert.property(result[0], "time") assert.property(result[0], 'time')
assert.property(result[0], "blocktime") assert.property(result[0], 'blocktime')
assert.property(result[0], "isCoinBase") assert.property(result[0], 'isCoinBase')
assert.property(result[0], "valueOut") assert.property(result[0], 'valueOut')
assert.property(result[0], "size") assert.property(result[0], 'size')
}) })
it(`should POST transaction details for an array of TxIDs`, async () => { it('should POST transaction details for an array of TxIDs', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "post").resolves({ data: mockData.detailsPost }) sandbox.stub(axios, 'post').resolves({ data: mockData.detailsPost })
const txid = [ const txid = [
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33", 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33" 'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'
] ]
const result = await bchjs.Ninsight.txDetails(txid) const result = await bchjs.Ninsight.txDetails(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.property(result[0], "txid") assert.property(result[0], 'txid')
assert.property(result[0], "vin") assert.property(result[0], 'vin')
assert.property(result[0], "vout") assert.property(result[0], 'vout')
}) })
}) })
}) })
+56 -56
View File
@@ -1,126 +1,126 @@
const chai = require("chai") const chai = require('chai')
const assert = chai.assert const assert = chai.assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
const mockData = require("./fixtures/openbazaar-mock") const mockData = require('./fixtures/openbazaar-mock')
describe(`#OpenBazaar`, () => { describe('#OpenBazaar', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe(`#Balance`, () => { describe('#Balance', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.OpenBazaar.balance(addr) await bchjs.OpenBazaar.balance(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `Input address must be a string`) assert.include(err.message, 'Input address must be a string')
} }
}) })
it(`should GET balance for a single address`, async () => { it('should GET balance for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.balance }) sandbox.stub(axios, 'get').resolves({ data: mockData.balance })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.OpenBazaar.balance(addr) const result = await bchjs.OpenBazaar.balance(addr)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"page", 'page',
"totalPages", 'totalPages',
"itemsOnPage", 'itemsOnPage',
"addrStr", 'addrStr',
"balance", 'balance',
"totalReceived", 'totalReceived',
"totalSent", 'totalSent',
"unconfirmedBalance", 'unconfirmedBalance',
"unconfirmedTxApperances", 'unconfirmedTxApperances',
"txApperances", 'txApperances',
"transactions" 'transactions'
]) ])
assert.isArray(result.transactions) assert.isArray(result.transactions)
}) })
}) })
describe(`#utxo`, () => { describe('#utxo', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const addr = 12345 const addr = 12345
await bchjs.OpenBazaar.utxo(addr) await bchjs.OpenBazaar.utxo(addr)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `Input address must be a string`) assert.include(err.message, 'Input address must be a string')
} }
}) })
it(`should GET utxos for a single address`, async () => { it('should GET utxos for a single address', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.utxo }) sandbox.stub(axios, 'get').resolves({ data: mockData.utxo })
const addr = "bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9" const addr = 'bitcoincash:qqh793x9au6ehvh7r2zflzguanlme760wuzehgzjh9'
const result = await bchjs.OpenBazaar.utxo(addr) const result = await bchjs.OpenBazaar.utxo(addr)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result) assert.isArray(result)
assert.hasAllKeys(result[0], [ assert.hasAllKeys(result[0], [
"txid", 'txid',
"vout", 'vout',
"amount", 'amount',
"height", 'height',
"confirmations", 'confirmations',
"satoshis" 'satoshis'
]) ])
}) })
}) })
describe(`#tx`, () => { describe('#tx', () => {
it(`should throw an error for improper input`, async () => { it('should throw an error for improper input', async () => {
try { try {
const txid = 12345 const txid = 12345
await bchjs.OpenBazaar.tx(txid) await bchjs.OpenBazaar.tx(txid)
assert.equal(true, false, "Unexpected result!") assert.equal(true, false, 'Unexpected result!')
} catch (err) { } catch (err) {
// console.log(`err: `, err) // console.log(`err: `, err)
assert.include(err.message, `Input txid must be a string`) assert.include(err.message, 'Input txid must be a string')
} }
}) })
it(`should GET tx details for a single txid`, async () => { it('should GET tx details for a single txid', async () => {
// Stub the network call. // Stub the network call.
sandbox.stub(axios, "get").resolves({ data: mockData.tx }) sandbox.stub(axios, 'get').resolves({ data: mockData.tx })
const txid = const txid =
"2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7" '2b37bdb3b63dd0bca720437754a36671431a950e684b64c44ea910ea9d5297c7'
const result = await bchjs.OpenBazaar.tx(txid) const result = await bchjs.OpenBazaar.tx(txid)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [ assert.hasAllKeys(result, [
"txid", 'txid',
"version", 'version',
"vin", 'vin',
"vout", 'vout',
"blockhash", 'blockhash',
"blockheight", 'blockheight',
"confirmations", 'confirmations',
"blocktime", 'blocktime',
"valueOut", 'valueOut',
"valueIn", 'valueIn',
"fees", 'fees',
"hex" 'hex'
]) ])
assert.isArray(result.vin) assert.isArray(result.vin)
assert.isArray(result.vout) assert.isArray(result.vout)
+20 -20
View File
@@ -1,11 +1,11 @@
const assert = require("chai").assert const assert = require('chai').assert
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const sinon = require("sinon") const sinon = require('sinon')
const mockDataLib = require("./fixtures/price-mocks") const mockDataLib = require('./fixtures/price-mocks')
let mockData let mockData
describe("#price", () => { describe('#price', () => {
let sandbox let sandbox
let bchjs let bchjs
@@ -19,22 +19,22 @@ describe("#price", () => {
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
describe("#current", () => { describe('#current', () => {
it("should get current price for single currency", async () => { it('should get current price for single currency', async () => {
sandbox sandbox
.stub(bchjs.Price.axios, "get") .stub(bchjs.Price.axios, 'get')
.resolves({ data: { price: 24905 } }) .resolves({ data: { price: 24905 } })
const result = await bchjs.Price.current("usd") const result = await bchjs.Price.current('usd')
// console.log(result) // console.log(result)
assert.isNumber(result) assert.isNumber(result)
}) })
}) })
describe("#getUsd", () => { describe('#getUsd', () => {
it("should get the USD price of BCH", async () => { it('should get the USD price of BCH', async () => {
sandbox.stub(bchjs.Price.axios, "get").resolves({ data: { usd: 249.87 } }) sandbox.stub(bchjs.Price.axios, 'get').resolves({ data: { usd: 249.87 } })
const result = await bchjs.Price.getUsd() const result = await bchjs.Price.getUsd()
// console.log(result) // console.log(result)
@@ -43,23 +43,23 @@ describe("#price", () => {
}) })
}) })
describe("#rates", () => { describe('#rates', () => {
it("should get the price of BCH in several currencies", async () => { it('should get the price of BCH in several currencies', async () => {
sandbox sandbox
.stub(bchjs.Price.axios, "get") .stub(bchjs.Price.axios, 'get')
.resolves({ data: mockData.mockRates }) .resolves({ data: mockData.mockRates })
const result = await bchjs.Price.rates() const result = await bchjs.Price.rates()
// console.log(result) // console.log(result)
assert.property(result, "USD") assert.property(result, 'USD')
assert.property(result, "CAD") assert.property(result, 'CAD')
}) })
}) })
describe("#getBchaUsd", () => { describe('#getBchaUsd', () => {
it("should get the USD price of BCHA", async () => { it('should get the USD price of BCHA', async () => {
sandbox.stub(bchjs.Price.axios, "get").resolves({ data: { usd: 18.87 } }) sandbox.stub(bchjs.Price.axios, 'get').resolves({ data: { usd: 18.87 } })
const result = await bchjs.Price.getBchaUsd() const result = await bchjs.Price.getBchaUsd()
// console.log(result) // console.log(result)
+28 -28
View File
@@ -4,13 +4,13 @@
*/ */
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
const axios = require("axios") const axios = require('axios')
const sinon = require("sinon") const sinon = require('sinon')
// const nock = require("nock") // HTTP mocking // const nock = require("nock") // HTTP mocking
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const bchjs = new BCHJS() // const bchjs = new BCHJS()
let bchjs let bchjs
@@ -18,22 +18,22 @@ let bchjs
// const util = require("util") // const util = require("util")
// util.inspect.defaultOptions = { depth: 1 } // util.inspect.defaultOptions = { depth: 1 }
describe("#RawTransactions", () => { describe('#RawTransactions', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#decodeRawTransaction", () => { describe('#decodeRawTransaction', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should decode raw transaction", done => { it('should decode raw transaction', done => {
const data = { const data = {
txid: txid:
"4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a", '4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a',
hash: hash:
"4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a", '4ebd325a4b394cff8c57e8317ccf5a8d0e2bdf1b8526f8aad6c8e43d8240621a',
size: 10, size: 10,
version: 2, version: 2,
locktime: 0, locktime: 0,
@@ -42,9 +42,9 @@ describe("#RawTransactions", () => {
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.RawTransactions.decodeRawTransaction("02000000000000000000") bchjs.RawTransactions.decodeRawTransaction('02000000000000000000')
.then(result => { .then(result => {
assert.equal(data, result) assert.equal(data, result)
}) })
@@ -52,23 +52,23 @@ describe("#RawTransactions", () => {
}) })
}) })
describe("#decodeScript", () => { describe('#decodeScript', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should decode script", async () => { it('should decode script', async () => {
const data = { const data = {
asm: "OP_RETURN 5361746f736869204e616b616d6f746f", asm: 'OP_RETURN 5361746f736869204e616b616d6f746f',
type: "nulldata", type: 'nulldata',
p2sh: "bitcoincash:prswx5965nfumux9qng5kj8hw603vcne7q08t8c6jp" p2sh: 'bitcoincash:prswx5965nfumux9qng5kj8hw603vcne7q08t8c6jp'
} }
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
const result = await bchjs.RawTransactions.decodeScript( const result = await bchjs.RawTransactions.decodeScript(
"6a105361746f736869204e616b616d6f746f" '6a105361746f736869204e616b616d6f746f'
) )
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
@@ -76,20 +76,20 @@ describe("#RawTransactions", () => {
}) })
}) })
describe("#getRawTransaction", () => { describe('#getRawTransaction', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should get raw transaction", done => { it('should get raw transaction', done => {
const data = const data =
"020000000160d663961c63c7f0a07f22ec07b8f55b3935bfdbed8b1d8454916e8932fbf109010000006b4830450221008479fab4cfdcb111833d250a43f98ac26d43272b7a29cb1b9a0491eae5c44b3502203448b17253632395c29a7d62058bbfe93efb20fc8636ba6837002d464195aec04121029123258f7cdcd45b864066bcaa9b71f24d5ed1fa1dd36eaf107d8432b5014658ffffffff016d180000000000001976a91479d3297d1823149f4ec61df31d19f2fad5390c0288ac00000000" '020000000160d663961c63c7f0a07f22ec07b8f55b3935bfdbed8b1d8454916e8932fbf109010000006b4830450221008479fab4cfdcb111833d250a43f98ac26d43272b7a29cb1b9a0491eae5c44b3502203448b17253632395c29a7d62058bbfe93efb20fc8636ba6837002d464195aec04121029123258f7cdcd45b864066bcaa9b71f24d5ed1fa1dd36eaf107d8432b5014658ffffffff016d180000000000001976a91479d3297d1823149f4ec61df31d19f2fad5390c0288ac00000000'
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
bchjs.RawTransactions.getRawTransaction( bchjs.RawTransactions.getRawTransaction(
"808d617eccaad4f1397fe07a06ec5ed15a0821cf22a3e0931c0c92aef9e572b6" '808d617eccaad4f1397fe07a06ec5ed15a0821cf22a3e0931c0c92aef9e572b6'
) )
.then(result => { .then(result => {
assert.equal(data, result) assert.equal(data, result)
@@ -98,19 +98,19 @@ describe("#RawTransactions", () => {
}) })
}) })
describe("#sendRawTransaction", () => { describe('#sendRawTransaction', () => {
let sandbox let sandbox
beforeEach(() => (sandbox = sinon.createSandbox())) beforeEach(() => (sandbox = sinon.createSandbox()))
afterEach(() => sandbox.restore()) afterEach(() => sandbox.restore())
it("should send single raw transaction", async () => { it('should send single raw transaction', async () => {
const data = "Error: transaction already in block chain" const data = 'Error: transaction already in block chain'
const resolved = new Promise(r => r({ data: data })) const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved) sandbox.stub(axios, 'get').returns(resolved)
const result = await bchjs.RawTransactions.sendRawTransaction( const result = await bchjs.RawTransactions.sendRawTransaction(
"020000000160d663961c63c7f0a07f22ec07b8f55b3935bfdbed8b1d8454916e8932fbf109010000006b4830450221008479fab4cfdcb111833d250a43f98ac26d43272b7a29cb1b9a0491eae5c44b3502203448b17253632395c29a7d62058bbfe93efb20fc8636ba6837002d464195aec04121029123258f7cdcd45b864066bcaa9b71f24d5ed1fa1dd36eaf107d8432b5014658ffffffff016d180000000000001976a91479d3297d1823149f4ec61df31d19f2fad5390c0288ac00000000" '020000000160d663961c63c7f0a07f22ec07b8f55b3935bfdbed8b1d8454916e8932fbf109010000006b4830450221008479fab4cfdcb111833d250a43f98ac26d43272b7a29cb1b9a0491eae5c44b3502203448b17253632395c29a7d62058bbfe93efb20fc8636ba6837002d464195aec04121029123258f7cdcd45b864066bcaa9b71f24d5ed1fa1dd36eaf107d8432b5014658ffffffff016d180000000000001976a91479d3297d1823149f4ec61df31d19f2fad5390c0288ac00000000'
) )
assert.equal(data, result) assert.equal(data, result)
+137 -137
View File
@@ -1,32 +1,32 @@
// Public npm libraries // Public npm libraries
const assert = require("assert") const assert = require('assert')
const Buffer = require("safe-buffer").Buffer const Buffer = require('safe-buffer').Buffer
// Mocks // Mocks
const fixtures = require("./fixtures/script.json") const fixtures = require('./fixtures/script.json')
// Unit under test (uut) // Unit under test (uut)
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let bchjs let bchjs
describe("#Script", () => { describe('#Script', () => {
beforeEach(() => { beforeEach(() => {
bchjs = new BCHJS() bchjs = new BCHJS()
}) })
describe("#decode", () => { describe('#decode', () => {
describe("P2PKH scriptSig", () => { describe('P2PKH scriptSig', () => {
fixtures.decodeScriptSig.forEach(fixture => { fixtures.decodeScriptSig.forEach(fixture => {
it(`should decode scriptSig buffer`, () => { it('should decode scriptSig buffer', () => {
const decodedScriptSig = bchjs.Script.decode( const decodedScriptSig = bchjs.Script.decode(
Buffer.from(fixture.scriptSigHex, "hex") Buffer.from(fixture.scriptSigHex, 'hex')
) )
assert.equal(typeof decodedScriptSig, "object") assert.equal(typeof decodedScriptSig, 'object')
}) })
it(`should decode scriptSig buffer to cash address ${fixture.cashAddress}`, () => { it(`should decode scriptSig buffer to cash address ${fixture.cashAddress}`, () => {
const decodedScriptSig = bchjs.Script.decode( const decodedScriptSig = bchjs.Script.decode(
Buffer.from(fixture.scriptSigHex, "hex") Buffer.from(fixture.scriptSigHex, 'hex')
) )
const address = bchjs.HDNode.toCashAddress( const address = bchjs.HDNode.toCashAddress(
bchjs.ECPair.fromPublicKey(decodedScriptSig[1]) bchjs.ECPair.fromPublicKey(decodedScriptSig[1])
@@ -36,7 +36,7 @@ describe("#Script", () => {
it(`should decode scriptSig buffer to legacy address ${fixture.legacyAddress}`, () => { it(`should decode scriptSig buffer to legacy address ${fixture.legacyAddress}`, () => {
const decodedScriptSig = bchjs.Script.decode( const decodedScriptSig = bchjs.Script.decode(
Buffer.from(fixture.scriptSigHex, "hex") Buffer.from(fixture.scriptSigHex, 'hex')
) )
const address = bchjs.HDNode.toLegacyAddress( const address = bchjs.HDNode.toLegacyAddress(
bchjs.ECPair.fromPublicKey(decodedScriptSig[1]) bchjs.ECPair.fromPublicKey(decodedScriptSig[1])
@@ -46,74 +46,74 @@ describe("#Script", () => {
}) })
}) })
describe("P2PKH scriptPubKey", () => { describe('P2PKH scriptPubKey', () => {
fixtures.decodeScriptPubKey.forEach(fixture => { fixtures.decodeScriptPubKey.forEach(fixture => {
it(`should decode scriptSig buffer`, () => { it('should decode scriptSig buffer', () => {
const decodedScriptPubKey = bchjs.Script.decode( const decodedScriptPubKey = bchjs.Script.decode(
Buffer.from(fixture.scriptPubKeyHex, "hex") Buffer.from(fixture.scriptPubKeyHex, 'hex')
) )
assert.equal(decodedScriptPubKey.length, 5) assert.equal(decodedScriptPubKey.length, 5)
}) })
it(`should match hashed pubKey ${fixture.pubKeyHex}`, () => { it(`should match hashed pubKey ${fixture.pubKeyHex}`, () => {
const decodedScriptPubKey = bchjs.Script.decode( const decodedScriptPubKey = bchjs.Script.decode(
Buffer.from(fixture.scriptPubKeyHex, "hex") Buffer.from(fixture.scriptPubKeyHex, 'hex')
) )
const data = Buffer.from(fixture.pubKeyHex, "hex") const data = Buffer.from(fixture.pubKeyHex, 'hex')
const hash160 = bchjs.Crypto.hash160(data).toString("hex") const hash160 = bchjs.Crypto.hash160(data).toString('hex')
assert.equal(decodedScriptPubKey[2].toString("hex"), hash160) assert.equal(decodedScriptPubKey[2].toString('hex'), hash160)
}) })
}) })
}) })
}) })
describe("#encode", () => { describe('#encode', () => {
describe("P2PKH scriptSig", () => { describe('P2PKH scriptSig', () => {
fixtures.encodeScriptSig.forEach(fixture => { fixtures.encodeScriptSig.forEach(fixture => {
it(`should encode scriptSig chunks to buffer`, () => { it('should encode scriptSig chunks to buffer', () => {
const arr = [ const arr = [
Buffer.from(fixture.scriptSigChunks[0], "hex"), Buffer.from(fixture.scriptSigChunks[0], 'hex'),
Buffer.from(fixture.scriptSigChunks[1], "hex") Buffer.from(fixture.scriptSigChunks[1], 'hex')
] ]
const encodedScriptSig = bchjs.Script.encode(arr) const encodedScriptSig = bchjs.Script.encode(arr)
assert.equal(typeof encodedScriptSig, "object") assert.equal(typeof encodedScriptSig, 'object')
}) })
}) })
}) })
describe("P2PKH scriptPubKey", () => { describe('P2PKH scriptPubKey', () => {
fixtures.encodeScriptPubKey.forEach(fixture => { fixtures.encodeScriptPubKey.forEach(fixture => {
it(`should encode scriptPubKey buffer`, () => { it('should encode scriptPubKey buffer', () => {
const decodedScriptPubKey = bchjs.Script.decode( const decodedScriptPubKey = bchjs.Script.decode(
Buffer.from(fixture.scriptPubKeyHex, "hex") Buffer.from(fixture.scriptPubKeyHex, 'hex')
) )
const compiledScriptPubKey = bchjs.Script.encode(decodedScriptPubKey) const compiledScriptPubKey = bchjs.Script.encode(decodedScriptPubKey)
assert.equal( assert.equal(
compiledScriptPubKey.toString("hex"), compiledScriptPubKey.toString('hex'),
fixture.scriptPubKeyHex fixture.scriptPubKeyHex
) )
}) })
}) })
}) })
describe("Encode SLP SEND OP_RETURN properly", () => { describe('Encode SLP SEND OP_RETURN properly', () => {
it("should correctly compile OP_RETURN SLP SEND transaction", () => { it('should correctly compile OP_RETURN SLP SEND transaction', () => {
const scriptArr = [ const scriptArr = [
bchjs.Script.opcodes.OP_RETURN, bchjs.Script.opcodes.OP_RETURN,
Buffer.from("534c5000", "hex"), Buffer.from('534c5000', 'hex'),
Buffer.from("01", "hex"), Buffer.from('01', 'hex'),
Buffer.from(`SEND`), Buffer.from('SEND'),
Buffer.from( Buffer.from(
"73db55368981e4878440637e448d4abe7f661be5c3efdcbcb63bd86a01a76b5a", '73db55368981e4878440637e448d4abe7f661be5c3efdcbcb63bd86a01a76b5a',
"hex" 'hex'
), ),
Buffer.from("00000001", "hex") Buffer.from('00000001', 'hex')
] ]
const data = bchjs.Script.encode2(scriptArr) const data = bchjs.Script.encode2(scriptArr)
// convert data to a hex string // convert data to a hex string
let str = "" let str = ''
for (let i = 0; i < data.length; i++) { for (let i = 0; i < data.length; i++) {
let hex = Number(data[i]).toString(16) let hex = Number(data[i]).toString(16)
@@ -129,20 +129,20 @@ describe("#Script", () => {
// console.log(`scriptArr: ${JSON.stringify(data,null,2)}`) // console.log(`scriptArr: ${JSON.stringify(data,null,2)}`)
const correctStr = const correctStr =
"6a04534c500001010453454e442073db55368981e4878440637e448d4abe7f661be5c3efdcbcb63bd86a01a76b5a0400000001" '6a04534c500001010453454e442073db55368981e4878440637e448d4abe7f661be5c3efdcbcb63bd86a01a76b5a0400000001'
assert.equal(str, correctStr) assert.equal(str, correctStr)
}) })
}) })
}) })
describe("#toASM", () => { describe('#toASM', () => {
describe("P2PKH scriptSig", () => { describe('P2PKH scriptSig', () => {
fixtures.scriptSigToASM.forEach(fixture => { fixtures.scriptSigToASM.forEach(fixture => {
it(`should encode scriptSig buffer to ${fixture.asm}`, () => { it(`should encode scriptSig buffer to ${fixture.asm}`, () => {
const arr = [ const arr = [
Buffer.from(fixture.scriptSigChunks[0], "hex"), Buffer.from(fixture.scriptSigChunks[0], 'hex'),
Buffer.from(fixture.scriptSigChunks[1], "hex") Buffer.from(fixture.scriptSigChunks[1], 'hex')
] ]
const compiledScriptSig = bchjs.Script.encode(arr) const compiledScriptSig = bchjs.Script.encode(arr)
const asm = bchjs.Script.toASM(compiledScriptSig) const asm = bchjs.Script.toASM(compiledScriptSig)
@@ -151,11 +151,11 @@ describe("#Script", () => {
}) })
}) })
describe("P2PKH scriptPubKey", () => { describe('P2PKH scriptPubKey', () => {
fixtures.scriptPubKeyToASM.forEach(fixture => { fixtures.scriptPubKeyToASM.forEach(fixture => {
it(`should compile scriptPubKey buffer to ${fixture.asm}`, () => { it(`should compile scriptPubKey buffer to ${fixture.asm}`, () => {
const asm = bchjs.Script.toASM( const asm = bchjs.Script.toASM(
Buffer.from(fixture.scriptPubKeyHex, "hex") Buffer.from(fixture.scriptPubKeyHex, 'hex')
) )
assert.equal(asm, fixture.asm) assert.equal(asm, fixture.asm)
}) })
@@ -163,27 +163,27 @@ describe("#Script", () => {
}) })
}) })
describe("#fromASM", () => { describe('#fromASM', () => {
describe("P2PKH scriptSig", () => { describe('P2PKH scriptSig', () => {
fixtures.scriptSigFromASM.forEach(fixture => { fixtures.scriptSigFromASM.forEach(fixture => {
it(`should decode scriptSig asm to buffer`, () => { it('should decode scriptSig asm to buffer', () => {
const buf = bchjs.Script.fromASM(fixture.asm) const buf = bchjs.Script.fromASM(fixture.asm)
assert.equal(typeof buf, "object") assert.equal(typeof buf, 'object')
}) })
}) })
}) })
describe("P2PKH scriptPubKey", () => { describe('P2PKH scriptPubKey', () => {
fixtures.scriptPubKeyFromASM.forEach(fixture => { fixtures.scriptPubKeyFromASM.forEach(fixture => {
it(`should decode scriptPubKey asm to buffer`, () => { it('should decode scriptPubKey asm to buffer', () => {
const buf = bchjs.Script.fromASM(fixture.asm) const buf = bchjs.Script.fromASM(fixture.asm)
assert.equal(typeof buf, "object") assert.equal(typeof buf, 'object')
}) })
}) })
}) })
}) })
describe("#OPCodes", () => { describe('#OPCodes', () => {
for (const opcode in fixtures.opcodes) { for (const opcode in fixtures.opcodes) {
it(`should have OP Code ${opcode}`, () => { it(`should have OP Code ${opcode}`, () => {
assert.equal(bchjs.Script.opcodes[opcode], fixtures.opcodes[opcode]) assert.equal(bchjs.Script.opcodes[opcode], fixtures.opcodes[opcode])
@@ -191,7 +191,7 @@ describe("#Script", () => {
} }
}) })
describe("#classifyInput", () => { describe('#classifyInput', () => {
fixtures.classifyInput.forEach(fixture => { fixtures.classifyInput.forEach(fixture => {
it(`should classify input type ${fixture.type}`, () => { it(`should classify input type ${fixture.type}`, () => {
const type = bchjs.Script.classifyInput( const type = bchjs.Script.classifyInput(
@@ -202,7 +202,7 @@ describe("#Script", () => {
}) })
}) })
describe("#classifyOutput", () => { describe('#classifyOutput', () => {
fixtures.classifyOutput.forEach(fixture => { fixtures.classifyOutput.forEach(fixture => {
it(`should classify ouput type ${fixture.type}`, () => { it(`should classify ouput type ${fixture.type}`, () => {
const type = bchjs.Script.classifyOutput( const type = bchjs.Script.classifyOutput(
@@ -213,25 +213,25 @@ describe("#Script", () => {
}) })
}) })
describe("#nullDataTemplate", () => { describe('#nullDataTemplate', () => {
fixtures.nullDataTemplate.forEach(fixture => { fixtures.nullDataTemplate.forEach(fixture => {
it(`should encode nulldata output`, () => { it('should encode nulldata output', () => {
const buf = bchjs.Script.nullData.output.encode( const buf = bchjs.Script.nullData.output.encode(
Buffer.from(`${fixture.data}`, "ascii") Buffer.from(`${fixture.data}`, 'ascii')
) )
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode nulldata output`, () => { it('should decode nulldata output', () => {
const buf = bchjs.Script.nullData.output.decode( const buf = bchjs.Script.nullData.output.decode(
Buffer.from(`${fixture.hex}`, "hex") Buffer.from(`${fixture.hex}`, 'hex')
) )
assert.equal(buf.toString("ascii"), fixture.data) assert.equal(buf.toString('ascii'), fixture.data)
}) })
it(`should confirm correctly formatted nulldata output`, () => { it('should confirm correctly formatted nulldata output', () => {
const buf = bchjs.Script.nullData.output.encode( const buf = bchjs.Script.nullData.output.encode(
Buffer.from(`${fixture.data}`, "ascii") Buffer.from(`${fixture.data}`, 'ascii')
) )
const valid = bchjs.Script.nullData.output.check(buf) const valid = bchjs.Script.nullData.output.check(buf)
assert.equal(valid, true) assert.equal(valid, true)
@@ -239,26 +239,26 @@ describe("#Script", () => {
}) })
}) })
describe("#pubKeyTemplate", () => { describe('#pubKeyTemplate', () => {
describe("#pubKeyInputTemplate", () => { describe('#pubKeyInputTemplate', () => {
fixtures.pubKeyInputTemplate.forEach(fixture => { fixtures.pubKeyInputTemplate.forEach(fixture => {
it(`should encode pubKey input`, () => { it('should encode pubKey input', () => {
const buf = bchjs.Script.pubKey.input.encode( const buf = bchjs.Script.pubKey.input.encode(
Buffer.from(fixture.signature, "hex") Buffer.from(fixture.signature, 'hex')
) )
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode pubKey input`, () => { it('should decode pubKey input', () => {
const buf = bchjs.Script.pubKey.input.decode( const buf = bchjs.Script.pubKey.input.decode(
Buffer.from(fixture.hex, "hex") Buffer.from(fixture.hex, 'hex')
) )
assert.equal(buf.toString("hex"), fixture.signature) assert.equal(buf.toString('hex'), fixture.signature)
}) })
it(`should confirm correctly formatted pubKeyHash input`, () => { it('should confirm correctly formatted pubKeyHash input', () => {
const buf = bchjs.Script.pubKey.input.encode( const buf = bchjs.Script.pubKey.input.encode(
Buffer.from(fixture.signature, "hex") Buffer.from(fixture.signature, 'hex')
) )
const valid = bchjs.Script.pubKey.input.check(buf) const valid = bchjs.Script.pubKey.input.check(buf)
assert.equal(valid, true) assert.equal(valid, true)
@@ -266,25 +266,25 @@ describe("#Script", () => {
}) })
}) })
describe("#pubKeyOutputTemplate", () => { describe('#pubKeyOutputTemplate', () => {
fixtures.pubKeyOutputTemplate.forEach(fixture => { fixtures.pubKeyOutputTemplate.forEach(fixture => {
it(`should encode pubKey output`, () => { it('should encode pubKey output', () => {
const buf = bchjs.Script.pubKey.output.encode( const buf = bchjs.Script.pubKey.output.encode(
Buffer.from(fixture.pubKey, "hex") Buffer.from(fixture.pubKey, 'hex')
) )
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode pubKey output`, () => { it('should decode pubKey output', () => {
const buf = bchjs.Script.pubKey.output.decode( const buf = bchjs.Script.pubKey.output.decode(
Buffer.from(`${fixture.hex}`, "hex") Buffer.from(`${fixture.hex}`, 'hex')
) )
assert.equal(buf.toString("hex"), fixture.pubKey) assert.equal(buf.toString('hex'), fixture.pubKey)
}) })
it(`should confirm correctly formatted pubKey output`, () => { it('should confirm correctly formatted pubKey output', () => {
const buf = bchjs.Script.pubKey.output.encode( const buf = bchjs.Script.pubKey.output.encode(
Buffer.from(fixture.pubKey, "hex") Buffer.from(fixture.pubKey, 'hex')
) )
const valid = bchjs.Script.pubKey.output.check(buf) const valid = bchjs.Script.pubKey.output.check(buf)
assert.equal(valid, true) assert.equal(valid, true)
@@ -293,35 +293,35 @@ describe("#Script", () => {
}) })
}) })
describe("#pubKeyHashTemplate", () => { describe('#pubKeyHashTemplate', () => {
describe("#pubKeyHashInputTemplate", () => { describe('#pubKeyHashInputTemplate', () => {
fixtures.pubKeyHashInputTemplate.forEach(fixture => { fixtures.pubKeyHashInputTemplate.forEach(fixture => {
it(`should encode pubKeyHash input`, () => { it('should encode pubKeyHash input', () => {
const buf = bchjs.Script.pubKeyHash.input.encode( const buf = bchjs.Script.pubKeyHash.input.encode(
Buffer.from(fixture.signature, "hex"), Buffer.from(fixture.signature, 'hex'),
Buffer.from(fixture.pubKey, "hex") Buffer.from(fixture.pubKey, 'hex')
) )
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode pubKeyHash input signature`, () => { it('should decode pubKeyHash input signature', () => {
const buf = bchjs.Script.pubKeyHash.input.decode( const buf = bchjs.Script.pubKeyHash.input.decode(
Buffer.from(fixture.hex, "hex") Buffer.from(fixture.hex, 'hex')
) )
assert.equal(buf.signature.toString("hex"), fixture.signature) assert.equal(buf.signature.toString('hex'), fixture.signature)
}) })
it(`should decode pubKeyHash input pubkey`, () => { it('should decode pubKeyHash input pubkey', () => {
const buf = bchjs.Script.pubKeyHash.input.decode( const buf = bchjs.Script.pubKeyHash.input.decode(
Buffer.from(fixture.hex, "hex") Buffer.from(fixture.hex, 'hex')
) )
assert.equal(buf.pubKey.toString("hex"), fixture.pubKey) assert.equal(buf.pubKey.toString('hex'), fixture.pubKey)
}) })
it(`should confirm correctly formatted pubKeyHash input`, () => { it('should confirm correctly formatted pubKeyHash input', () => {
const buf = bchjs.Script.pubKeyHash.input.encode( const buf = bchjs.Script.pubKeyHash.input.encode(
Buffer.from(fixture.signature, "hex"), Buffer.from(fixture.signature, 'hex'),
Buffer.from(fixture.pubKey, "hex") Buffer.from(fixture.pubKey, 'hex')
) )
const valid = bchjs.Script.pubKeyHash.input.check(buf) const valid = bchjs.Script.pubKeyHash.input.check(buf)
assert.equal(valid, true) assert.equal(valid, true)
@@ -329,24 +329,24 @@ describe("#Script", () => {
}) })
}) })
describe("#pubKeyHashOutputTemplate", () => { describe('#pubKeyHashOutputTemplate', () => {
it("should exercise pubKeyHashOutputTemplate", () => { it('should exercise pubKeyHashOutputTemplate', () => {
fixtures.pubKeyHashOutputTemplate.forEach(fixture => { fixtures.pubKeyHashOutputTemplate.forEach(fixture => {
const node = bchjs.HDNode.fromXPriv(fixture.xpriv) const node = bchjs.HDNode.fromXPriv(fixture.xpriv)
const identifier = bchjs.HDNode.toIdentifier(node) const identifier = bchjs.HDNode.toIdentifier(node)
it(`should encode pubKeyHash output`, () => { it('should encode pubKeyHash output', () => {
const buf = bchjs.Script.pubKeyHash.output.encode(identifier) const buf = bchjs.Script.pubKeyHash.output.encode(identifier)
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode pubKeyHash output`, () => { it('should decode pubKeyHash output', () => {
const buf = bchjs.Script.pubKeyHash.output.decode( const buf = bchjs.Script.pubKeyHash.output.decode(
Buffer.from(`${fixture.hex}`, "hex") Buffer.from(`${fixture.hex}`, 'hex')
) )
assert.equal(buf.toString("hex"), identifier.toString("hex")) assert.equal(buf.toString('hex'), identifier.toString('hex'))
}) })
it(`should confirm correctly formatted pubKeyHash output`, () => { it('should confirm correctly formatted pubKeyHash output', () => {
const buf = bchjs.Script.pubKeyHash.output.encode(identifier) const buf = bchjs.Script.pubKeyHash.output.encode(identifier)
const valid = bchjs.Script.pubKeyHash.output.check(buf) const valid = bchjs.Script.pubKeyHash.output.check(buf)
assert.equal(valid, true) assert.equal(valid, true)
@@ -356,31 +356,31 @@ describe("#Script", () => {
}) })
}) })
describe("#multisigTemplate", () => { describe('#multisigTemplate', () => {
describe("#multisigInputTemplate", () => { describe('#multisigInputTemplate', () => {
fixtures.multisigInputTemplate.forEach(fixture => { fixtures.multisigInputTemplate.forEach(fixture => {
it(`should encode multisig input`, () => { it('should encode multisig input', () => {
const signatures = fixture.signatures.map(signature => const signatures = fixture.signatures.map(signature =>
signature signature
? Buffer.from(signature, "hex") ? Buffer.from(signature, 'hex')
: bchjs.Script.opcodes.OP_0 : bchjs.Script.opcodes.OP_0
) )
const buf = bchjs.Script.multisig.input.encode(signatures) const buf = bchjs.Script.multisig.input.encode(signatures)
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode multisig input`, () => { it('should decode multisig input', () => {
const buf = bchjs.Script.multisig.input.decode( const buf = bchjs.Script.multisig.input.decode(
Buffer.from(fixture.hex, "hex") Buffer.from(fixture.hex, 'hex')
) )
assert.equal(buf[0].toString("hex"), fixture.signatures[0]) assert.equal(buf[0].toString('hex'), fixture.signatures[0])
}) })
it(`should confirm correctly formatted multisig input`, () => { it('should confirm correctly formatted multisig input', () => {
const signatures = fixture.signatures.map(signature => const signatures = fixture.signatures.map(signature =>
signature signature
? Buffer.from(signature, "hex") ? Buffer.from(signature, 'hex')
: bchjs.Script.opcodes.OP_0 : bchjs.Script.opcodes.OP_0
) )
@@ -391,25 +391,25 @@ describe("#Script", () => {
}) })
}) })
describe("#multisigOutputTemplate", () => { describe('#multisigOutputTemplate', () => {
fixtures.multisigOutputTemplate.forEach(fixture => { fixtures.multisigOutputTemplate.forEach(fixture => {
it(`should encode multisig output`, () => { it('should encode multisig output', () => {
const pubKeys = fixture.pubKeys.map(p => Buffer.from(p, "hex")) const pubKeys = fixture.pubKeys.map(p => Buffer.from(p, 'hex'))
const m = pubKeys.length const m = pubKeys.length
const buf = bchjs.Script.multisig.output.encode(m, pubKeys) const buf = bchjs.Script.multisig.output.encode(m, pubKeys)
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode multisig output`, () => { it('should decode multisig output', () => {
const output = bchjs.Script.multisig.output.decode( const output = bchjs.Script.multisig.output.decode(
Buffer.from(`${fixture.hex}`, "hex") Buffer.from(`${fixture.hex}`, 'hex')
) )
assert.equal(output.m, fixture.pubKeys.length) assert.equal(output.m, fixture.pubKeys.length)
}) })
it(`should confirm correctly formatted multisig output`, () => { it('should confirm correctly formatted multisig output', () => {
const pubKeys = fixture.pubKeys.map(p => Buffer.from(p, "hex")) const pubKeys = fixture.pubKeys.map(p => Buffer.from(p, 'hex'))
const m = pubKeys.length const m = pubKeys.length
const buf = bchjs.Script.multisig.output.encode(m, pubKeys) const buf = bchjs.Script.multisig.output.encode(m, pubKeys)
const valid = bchjs.Script.multisig.output.check(buf) const valid = bchjs.Script.multisig.output.check(buf)
@@ -419,23 +419,23 @@ describe("#Script", () => {
}) })
}) })
describe("#scriptHashTemplate", () => { describe('#scriptHashTemplate', () => {
describe("#scriptHashInputTemplate", () => { describe('#scriptHashInputTemplate', () => {
fixtures.scriptHashInputTemplate.forEach(fixture => { fixtures.scriptHashInputTemplate.forEach(fixture => {
it(`should encode scriptHash input`, () => { it('should encode scriptHash input', () => {
const buf = bchjs.Script.scriptHash.input.encode( const buf = bchjs.Script.scriptHash.input.encode(
bchjs.Script.fromASM(fixture.redeemScriptSig), bchjs.Script.fromASM(fixture.redeemScriptSig),
bchjs.Script.fromASM(fixture.redeemScript) bchjs.Script.fromASM(fixture.redeemScript)
) )
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode scriptHash input`, () => { it('should decode scriptHash input', () => {
const redeemScriptSig = bchjs.Script.fromASM(fixture.redeemScriptSig) const redeemScriptSig = bchjs.Script.fromASM(fixture.redeemScriptSig)
const redeemScript = bchjs.Script.fromASM(fixture.redeemScript) const redeemScript = bchjs.Script.fromASM(fixture.redeemScript)
assert.deepEqual( assert.deepEqual(
bchjs.Script.scriptHash.input.decode( bchjs.Script.scriptHash.input.decode(
Buffer.from(fixture.hex, "hex") Buffer.from(fixture.hex, 'hex')
), ),
{ {
redeemScriptSig: redeemScriptSig, redeemScriptSig: redeemScriptSig,
@@ -444,7 +444,7 @@ describe("#Script", () => {
) )
}) })
it(`should confirm correctly formatted scriptHash input`, () => { it('should confirm correctly formatted scriptHash input', () => {
const buf = bchjs.Script.scriptHash.input.encode( const buf = bchjs.Script.scriptHash.input.encode(
bchjs.Script.fromASM(fixture.redeemScriptSig), bchjs.Script.fromASM(fixture.redeemScriptSig),
bchjs.Script.fromASM(fixture.redeemScript) bchjs.Script.fromASM(fixture.redeemScript)
@@ -455,26 +455,26 @@ describe("#Script", () => {
}) })
}) })
describe("#scriptHashOutputTemplate", () => { describe('#scriptHashOutputTemplate', () => {
fixtures.scriptHashOutputTemplate.forEach(fixture => { fixtures.scriptHashOutputTemplate.forEach(fixture => {
it(`should encode scriptHash output`, () => { it('should encode scriptHash output', () => {
const redeemScript = bchjs.Script.fromASM(fixture.output) const redeemScript = bchjs.Script.fromASM(fixture.output)
const scriptHash = bchjs.Crypto.hash160(redeemScript) const scriptHash = bchjs.Crypto.hash160(redeemScript)
const buf = bchjs.Script.scriptHash.output.encode(scriptHash) const buf = bchjs.Script.scriptHash.output.encode(scriptHash)
assert.equal(buf.toString("hex"), fixture.hex) assert.equal(buf.toString('hex'), fixture.hex)
}) })
it(`should decode scriptHash output`, () => { it('should decode scriptHash output', () => {
const redeemScript = bchjs.Script.fromASM(fixture.output) const redeemScript = bchjs.Script.fromASM(fixture.output)
const scriptHash = bchjs.Crypto.hash160(redeemScript) const scriptHash = bchjs.Crypto.hash160(redeemScript)
const buf = bchjs.Script.scriptHash.output.decode( const buf = bchjs.Script.scriptHash.output.decode(
Buffer.from(`${fixture.hex}`, "hex") Buffer.from(`${fixture.hex}`, 'hex')
) )
assert.deepEqual(buf, scriptHash) assert.deepEqual(buf, scriptHash)
}) })
it(`should confirm correctly formatted scriptHash output`, () => { it('should confirm correctly formatted scriptHash output', () => {
const redeemScript = bchjs.Script.fromASM(fixture.output) const redeemScript = bchjs.Script.fromASM(fixture.output)
const scriptHash = bchjs.Crypto.hash160(redeemScript) const scriptHash = bchjs.Crypto.hash160(redeemScript)
const buf = bchjs.Script.scriptHash.output.encode(scriptHash) const buf = bchjs.Script.scriptHash.output.encode(scriptHash)
+99 -99
View File
@@ -1,11 +1,11 @@
const assert = require("assert") const assert = require('assert')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
// const SLP = require("../../src/slp/slp") // const SLP = require("../../src/slp/slp")
// const SLP = new slp({ restURL: "http://fakeurl.com/" }) // const SLP = new slp({ restURL: "http://fakeurl.com/" })
let slp let slp
const fixtures = require("./fixtures/slp/address.json") const fixtures = require('./fixtures/slp/address.json')
// const axios = require("axios") // const axios = require("axios")
// const sinon = require("sinon") // const sinon = require("sinon")
@@ -87,16 +87,16 @@ const SLP_TESTNET_ADDRESSES_NO_PREFIX = SLP_TESTNET_ADDRESSES.map(address => {
return parts[1] return parts[1]
}) })
*/ */
describe("#SLP Address", () => { describe('#SLP Address', () => {
beforeEach(() => { beforeEach(() => {
const bchjs = new BCHJS() const bchjs = new BCHJS()
// console.log(`bchjs.restURL: ${bchjs.restURL}`) // console.log(`bchjs.restURL: ${bchjs.restURL}`)
slp = bchjs.SLP slp = bchjs.SLP
}) })
describe("#mainnet", () => { describe('#mainnet', () => {
describe("#toLegacyAddress", () => { describe('#toLegacyAddress', () => {
it("should convert mainnet legacy address format to itself correctly", () => { it('should convert mainnet legacy address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
LEGACY_MAINNET_ADDRESSES.map(address => LEGACY_MAINNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -105,7 +105,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert cashAddr to legacyAddr`, async () => { it('should convert cashAddr to legacyAddr', async () => {
assert.deepEqual( assert.deepEqual(
CASH_MAINNET_ADDRESSES.map(address => CASH_MAINNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -114,7 +114,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert slpAddr to legacyAddr`, async () => { it('should convert slpAddr to legacyAddr', async () => {
assert.deepEqual( assert.deepEqual(
SLP_MAINNET_ADDRESSES.map(address => SLP_MAINNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -124,8 +124,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#toCashAddress", () => { describe('#toCashAddress', () => {
it("should convert mainnet cash address format to itself correctly", () => { it('should convert mainnet cash address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
CASH_MAINNET_ADDRESSES.map(address => CASH_MAINNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -134,7 +134,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert legacyAddr to cashAddr`, async () => { it('should convert legacyAddr to cashAddr', async () => {
assert.deepEqual( assert.deepEqual(
LEGACY_MAINNET_ADDRESSES.map(address => LEGACY_MAINNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -143,7 +143,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert slpAddr to cashAddr`, async () => { it('should convert slpAddr to cashAddr', async () => {
assert.deepEqual( assert.deepEqual(
SLP_MAINNET_ADDRESSES.map(address => SLP_MAINNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -153,8 +153,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#toSLPAddress", () => { describe('#toSLPAddress', () => {
it("should convert mainnet slp address format to itself correctly", () => { it('should convert mainnet slp address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
SLP_MAINNET_ADDRESSES.map(address => SLP_MAINNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -163,7 +163,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert legacyAddr to slpAddr`, async () => { it('should convert legacyAddr to slpAddr', async () => {
assert.deepEqual( assert.deepEqual(
LEGACY_MAINNET_ADDRESSES.map(address => LEGACY_MAINNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -172,7 +172,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert cashAddr to slpAddr`, async () => { it('should convert cashAddr to slpAddr', async () => {
assert.deepEqual( assert.deepEqual(
CASH_MAINNET_ADDRESSES.map(address => CASH_MAINNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -182,8 +182,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isLegacyAddress", () => { describe('#isLegacyAddress', () => {
describe("is legacy addr", () => { describe('is legacy addr', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy address`, () => { it(`should detect ${address} is a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -192,7 +192,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("cashaddr is not legacy addr", () => { describe('cashaddr is not legacy addr', () => {
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a legacy address`, () => { it(`should detect ${address} is not a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -201,7 +201,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("slpaddr is not legacy addr", () => { describe('slpaddr is not legacy addr', () => {
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a legacy address`, () => { it(`should detect ${address} is not a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -211,8 +211,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isCashAddress", () => { describe('#isCashAddress', () => {
describe("is cashaddr", () => { describe('is cashaddr', () => {
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a cashaddr address`, () => { it(`should detect ${address} is a cashaddr address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -221,7 +221,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("legacy is not cash addr", () => { describe('legacy is not cash addr', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a cash address`, () => { it(`should detect ${address} is not a cash address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -230,7 +230,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("slpaddr is not cash addr", () => { describe('slpaddr is not cash addr', () => {
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a cash address`, () => { it(`should detect ${address} is not a cash address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -240,8 +240,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isSLPAddress", () => { describe('#isSLPAddress', () => {
describe("is slpaddr", () => { describe('is slpaddr', () => {
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is an slp address`, () => { it(`should detect ${address} is an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -250,7 +250,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("legacy is not slp addr", () => { describe('legacy is not slp addr', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not an slp address`, () => { it(`should detect ${address} is not an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -259,7 +259,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("cash is not slp addr", () => { describe('cash is not slp addr', () => {
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not an slp address`, () => { it(`should detect ${address} is not an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -269,8 +269,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isMainnetAddress", () => { describe('#isMainnetAddress', () => {
describe("mainnet legacy addr", () => { describe('mainnet legacy addr', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -279,7 +279,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("mainnet cash addr", () => { describe('mainnet cash addr', () => {
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -288,7 +288,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("mainnet slp addr", () => { describe('mainnet slp addr', () => {
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -297,7 +297,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("testnet legacy addr", () => { describe('testnet legacy addr', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a mainnet address`, () => { it(`should detect ${address} is not a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -306,7 +306,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("testnet cash addr", () => { describe('testnet cash addr', () => {
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a mainnet address`, () => { it(`should detect ${address} is not a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -315,7 +315,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("testnet slp addr", () => { describe('testnet slp addr', () => {
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a mainnet address`, () => { it(`should detect ${address} is not a mainnet address`, () => {
const isMainnetaddr = slp.Address.isMainnetAddress(address) const isMainnetaddr = slp.Address.isMainnetAddress(address)
@@ -325,8 +325,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isP2PKHAddress", () => { describe('#isP2PKHAddress', () => {
describe("mainnet legacy addr", () => { describe('mainnet legacy addr', () => {
MAINNET_P2PKH_ADDRESSES.forEach(address => { MAINNET_P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2PKH address`, () => { it(`should detect ${address} is a P2PKH address`, () => {
const isP2PKHaddr = slp.Address.isP2PKHAddress(address) const isP2PKHaddr = slp.Address.isP2PKHAddress(address)
@@ -336,8 +336,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isP2SHAddress", () => { describe('#isP2SHAddress', () => {
describe("mainnet legacy addr", () => { describe('mainnet legacy addr', () => {
MAINNET_P2SH_ADDRESSES.forEach(address => { MAINNET_P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2SH address`, () => { it(`should detect ${address} is a P2SH address`, () => {
const isP2SHaddr = slp.Address.isP2SHAddress(address) const isP2SHaddr = slp.Address.isP2SHAddress(address)
@@ -347,72 +347,72 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#detectAddressFormat", () => { describe('#detectAddressFormat', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy address`, () => { it(`should detect ${address} is a legacy address`, () => {
const isLegacy = slp.Address.detectAddressFormat(address) const isLegacy = slp.Address.detectAddressFormat(address)
assert.equal(isLegacy, "legacy") assert.equal(isLegacy, 'legacy')
}) })
}) })
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a cash address`, () => { it(`should detect ${address} is a cash address`, () => {
const isCashaddr = slp.Address.detectAddressFormat(address) const isCashaddr = slp.Address.detectAddressFormat(address)
assert.equal(isCashaddr, "cashaddr") assert.equal(isCashaddr, 'cashaddr')
}) })
}) })
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is an slp address`, () => { it(`should detect ${address} is an slp address`, () => {
const isSlpaddr = slp.Address.detectAddressFormat(address) const isSlpaddr = slp.Address.detectAddressFormat(address)
assert.equal(isSlpaddr, "slpaddr") assert.equal(isSlpaddr, 'slpaddr')
}) })
}) })
}) })
describe("#detectAddressNetwork", () => { describe('#detectAddressNetwork', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnet = slp.Address.detectAddressNetwork(address) const isMainnet = slp.Address.detectAddressNetwork(address)
assert.equal(isMainnet, "mainnet") assert.equal(isMainnet, 'mainnet')
}) })
}) })
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnet = slp.Address.detectAddressNetwork(address) const isMainnet = slp.Address.detectAddressNetwork(address)
assert.equal(isMainnet, "mainnet") assert.equal(isMainnet, 'mainnet')
}) })
}) })
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a mainnet address`, () => { it(`should detect ${address} is a mainnet address`, () => {
const isMainnet = slp.Address.detectAddressNetwork(address) const isMainnet = slp.Address.detectAddressNetwork(address)
assert.equal(isMainnet, "mainnet") assert.equal(isMainnet, 'mainnet')
}) })
}) })
}) })
describe("#detectAddressType", () => { describe('#detectAddressType', () => {
MAINNET_P2PKH_ADDRESSES.forEach(address => { MAINNET_P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a p2pkh address`, () => { it(`should detect ${address} is a p2pkh address`, () => {
const isp2pkh = slp.Address.detectAddressType(address) const isp2pkh = slp.Address.detectAddressType(address)
assert.equal(isp2pkh, "p2pkh") assert.equal(isp2pkh, 'p2pkh')
}) })
}) })
MAINNET_P2SH_ADDRESSES.forEach(address => { MAINNET_P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a p2sh address`, () => { it(`should detect ${address} is a p2sh address`, () => {
const isp2sh = slp.Address.detectAddressType(address) const isp2sh = slp.Address.detectAddressType(address)
assert.equal(isp2sh, "p2sh") assert.equal(isp2sh, 'p2sh')
}) })
}) })
}) })
}) })
describe("#testnet", () => { describe('#testnet', () => {
describe("#toLegacyAddress", () => { describe('#toLegacyAddress', () => {
it("should convert testnet legacy address format to itself correctly", () => { it('should convert testnet legacy address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
LEGACY_TESTNET_ADDRESSES.map(address => LEGACY_TESTNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -421,7 +421,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert cashAddr to legacyAddr`, async () => { it('should convert cashAddr to legacyAddr', async () => {
assert.deepEqual( assert.deepEqual(
CASH_TESTNET_ADDRESSES.map(address => CASH_TESTNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -430,7 +430,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert slpAddr to legacyAddr`, async () => { it('should convert slpAddr to legacyAddr', async () => {
assert.deepEqual( assert.deepEqual(
SLP_TESTNET_ADDRESSES.map(address => SLP_TESTNET_ADDRESSES.map(address =>
slp.Address.toLegacyAddress(address) slp.Address.toLegacyAddress(address)
@@ -440,8 +440,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#toCashAddress", () => { describe('#toCashAddress', () => {
it("should convert testnet cash address format to itself correctly", () => { it('should convert testnet cash address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
CASH_TESTNET_ADDRESSES.map(address => CASH_TESTNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -450,7 +450,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert legacyAddr to cashAddr`, async () => { it('should convert legacyAddr to cashAddr', async () => {
assert.deepEqual( assert.deepEqual(
LEGACY_TESTNET_ADDRESSES.map(address => LEGACY_TESTNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -459,7 +459,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert slpAddr to cashAddr`, async () => { it('should convert slpAddr to cashAddr', async () => {
assert.deepEqual( assert.deepEqual(
SLP_TESTNET_ADDRESSES.map(address => SLP_TESTNET_ADDRESSES.map(address =>
slp.Address.toCashAddress(address) slp.Address.toCashAddress(address)
@@ -469,8 +469,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#toSLPAddress", () => { describe('#toSLPAddress', () => {
it("should convert testnet slp address format to itself correctly", () => { it('should convert testnet slp address format to itself correctly', () => {
assert.deepEqual( assert.deepEqual(
SLP_TESTNET_ADDRESSES.map(address => SLP_TESTNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -479,7 +479,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert legacyAddr to slpAddr`, async () => { it('should convert legacyAddr to slpAddr', async () => {
assert.deepEqual( assert.deepEqual(
LEGACY_TESTNET_ADDRESSES.map(address => LEGACY_TESTNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -488,7 +488,7 @@ describe("#SLP Address", () => {
) )
}) })
it(`should convert cashAddr to slpAddr`, async () => { it('should convert cashAddr to slpAddr', async () => {
assert.deepEqual( assert.deepEqual(
CASH_TESTNET_ADDRESSES.map(address => CASH_TESTNET_ADDRESSES.map(address =>
slp.Address.toSLPAddress(address) slp.Address.toSLPAddress(address)
@@ -498,8 +498,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isLegacyAddress", () => { describe('#isLegacyAddress', () => {
describe("is legacy addr", () => { describe('is legacy addr', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy address`, () => { it(`should detect ${address} is a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -508,7 +508,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("cashaddr is not legacy addr", () => { describe('cashaddr is not legacy addr', () => {
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a legacy address`, () => { it(`should detect ${address} is not a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -517,7 +517,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("slpaddr is not legacy addr", () => { describe('slpaddr is not legacy addr', () => {
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a legacy address`, () => { it(`should detect ${address} is not a legacy address`, () => {
const isLegacyaddr = slp.Address.isLegacyAddress(address) const isLegacyaddr = slp.Address.isLegacyAddress(address)
@@ -527,8 +527,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isCashAddress", () => { describe('#isCashAddress', () => {
describe("is cashaddr", () => { describe('is cashaddr', () => {
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a cashaddr address`, () => { it(`should detect ${address} is a cashaddr address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -537,7 +537,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("legacy is not cash addr", () => { describe('legacy is not cash addr', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a cash address`, () => { it(`should detect ${address} is not a cash address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -546,7 +546,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("slpaddr is not cash addr", () => { describe('slpaddr is not cash addr', () => {
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a cash address`, () => { it(`should detect ${address} is not a cash address`, () => {
const isCashaddr = slp.Address.isCashAddress(address) const isCashaddr = slp.Address.isCashAddress(address)
@@ -556,8 +556,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isSLPAddress", () => { describe('#isSLPAddress', () => {
describe("is slpaddr", () => { describe('is slpaddr', () => {
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is an slp address`, () => { it(`should detect ${address} is an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -566,7 +566,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("legacy is not slp addr", () => { describe('legacy is not slp addr', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not an slp address`, () => { it(`should detect ${address} is not an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -575,7 +575,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("cash is not slp addr", () => { describe('cash is not slp addr', () => {
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not an slp address`, () => { it(`should detect ${address} is not an slp address`, () => {
const isSLPaddr = slp.Address.isSLPAddress(address) const isSLPaddr = slp.Address.isSLPAddress(address)
@@ -585,8 +585,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isTestnetAddress", () => { describe('#isTestnetAddress', () => {
describe("testnet legacy addr", () => { describe('testnet legacy addr', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -595,7 +595,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("testnet cash addr", () => { describe('testnet cash addr', () => {
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -604,7 +604,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("testnet slp addr", () => { describe('testnet slp addr', () => {
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -613,7 +613,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("mainnet legacy addr", () => { describe('mainnet legacy addr', () => {
LEGACY_MAINNET_ADDRESSES.forEach(address => { LEGACY_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a testnet address`, () => { it(`should detect ${address} is not a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -622,7 +622,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("mainnet cash addr", () => { describe('mainnet cash addr', () => {
CASH_MAINNET_ADDRESSES.forEach(address => { CASH_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a testnet address`, () => { it(`should detect ${address} is not a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -631,7 +631,7 @@ describe("#SLP Address", () => {
}) })
}) })
describe("mainnet slp addr", () => { describe('mainnet slp addr', () => {
SLP_MAINNET_ADDRESSES.forEach(address => { SLP_MAINNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is not a testnet address`, () => { it(`should detect ${address} is not a testnet address`, () => {
const isTestnetaddr = slp.Address.isTestnetAddress(address) const isTestnetaddr = slp.Address.isTestnetAddress(address)
@@ -641,8 +641,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isP2PKHAddress", () => { describe('#isP2PKHAddress', () => {
describe("testnet legacy addr", () => { describe('testnet legacy addr', () => {
TESTNET_P2PKH_ADDRESSES.forEach(address => { TESTNET_P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2PKH address`, () => { it(`should detect ${address} is a P2PKH address`, () => {
const isP2PKHaddr = slp.Address.isP2PKHAddress(address) const isP2PKHaddr = slp.Address.isP2PKHAddress(address)
@@ -652,8 +652,8 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#isP2SHAddress", () => { describe('#isP2SHAddress', () => {
describe("testnet legacy addr", () => { describe('testnet legacy addr', () => {
TESTNET_P2SH_ADDRESSES.forEach(address => { TESTNET_P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a P2SH address`, () => { it(`should detect ${address} is a P2SH address`, () => {
const isP2SHaddr = slp.Address.isP2SHAddress(address) const isP2SHaddr = slp.Address.isP2SHAddress(address)
@@ -663,66 +663,66 @@ describe("#SLP Address", () => {
}) })
}) })
describe("#detectAddressFormat", () => { describe('#detectAddressFormat', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a legacy address`, () => { it(`should detect ${address} is a legacy address`, () => {
const isLegacy = slp.Address.detectAddressFormat(address) const isLegacy = slp.Address.detectAddressFormat(address)
assert.equal(isLegacy, "legacy") assert.equal(isLegacy, 'legacy')
}) })
}) })
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a cash address`, () => { it(`should detect ${address} is a cash address`, () => {
const isCashaddr = slp.Address.detectAddressFormat(address) const isCashaddr = slp.Address.detectAddressFormat(address)
assert.equal(isCashaddr, "cashaddr") assert.equal(isCashaddr, 'cashaddr')
}) })
}) })
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is an slp address`, () => { it(`should detect ${address} is an slp address`, () => {
const isSlpaddr = slp.Address.detectAddressFormat(address) const isSlpaddr = slp.Address.detectAddressFormat(address)
assert.equal(isSlpaddr, "slpaddr") assert.equal(isSlpaddr, 'slpaddr')
}) })
}) })
}) })
describe("#detectAddressNetwork", () => { describe('#detectAddressNetwork', () => {
LEGACY_TESTNET_ADDRESSES.forEach(address => { LEGACY_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = slp.Address.detectAddressNetwork(address) const isTestnet = slp.Address.detectAddressNetwork(address)
assert.equal(isTestnet, "testnet") assert.equal(isTestnet, 'testnet')
}) })
}) })
CASH_TESTNET_ADDRESSES.forEach(address => { CASH_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = slp.Address.detectAddressNetwork(address) const isTestnet = slp.Address.detectAddressNetwork(address)
assert.equal(isTestnet, "testnet") assert.equal(isTestnet, 'testnet')
}) })
}) })
SLP_TESTNET_ADDRESSES.forEach(address => { SLP_TESTNET_ADDRESSES.forEach(address => {
it(`should detect ${address} is a testnet address`, () => { it(`should detect ${address} is a testnet address`, () => {
const isTestnet = slp.Address.detectAddressNetwork(address) const isTestnet = slp.Address.detectAddressNetwork(address)
assert.equal(isTestnet, "testnet") assert.equal(isTestnet, 'testnet')
}) })
}) })
}) })
describe("#detectAddressType", () => { describe('#detectAddressType', () => {
TESTNET_P2PKH_ADDRESSES.forEach(address => { TESTNET_P2PKH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a p2pkh address`, () => { it(`should detect ${address} is a p2pkh address`, () => {
const isp2pkh = slp.Address.detectAddressType(address) const isp2pkh = slp.Address.detectAddressType(address)
assert.equal(isp2pkh, "p2pkh") assert.equal(isp2pkh, 'p2pkh')
}) })
}) })
}) })
describe("#detectAddressType", () => { describe('#detectAddressType', () => {
TESTNET_P2SH_ADDRESSES.forEach(address => { TESTNET_P2SH_ADDRESSES.forEach(address => {
it(`should detect ${address} is a p2sh address`, () => { it(`should detect ${address} is a p2sh address`, () => {
const isp2sh = slp.Address.detectAddressType(address) const isp2sh = slp.Address.detectAddressType(address)
assert.equal(isp2sh, "p2sh") assert.equal(isp2sh, 'p2sh')
}) })
}) })
}) })
+6 -6
View File
@@ -1,21 +1,21 @@
const assert = require("assert") const assert = require('assert')
const fixtures = require("./fixtures/slp/ecpair.json") const fixtures = require('./fixtures/slp/ecpair.json')
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
let slp let slp
// const SLP = require("../../src/slp/slp") // const SLP = require("../../src/slp/slp")
// const slp = new SLP({ restURL: "http://fakeurl.com/" }) // const slp = new SLP({ restURL: "http://fakeurl.com/" })
describe("#SLP ECPair", () => { describe('#SLP ECPair', () => {
beforeEach(() => { beforeEach(() => {
const bchjs = new BCHJS() const bchjs = new BCHJS()
slp = bchjs.SLP slp = bchjs.SLP
}) })
describe("#toSLPAddress", () => { describe('#toSLPAddress', () => {
it(`should return slp address for ecpair`, async () => { it('should return slp address for ecpair', async () => {
fixtures.wif.forEach((wif, index) => { fixtures.wif.forEach((wif, index) => {
const ecpair = slp.ECPair.fromWIF(wif) const ecpair = slp.ECPair.fromWIF(wif)
const slpAddr = slp.ECPair.toSLPAddress(ecpair) const slpAddr = slp.ECPair.toSLPAddress(ecpair)
+83 -83
View File
@@ -2,25 +2,25 @@
Unit tests for the TokenType1 library. Unit tests for the TokenType1 library.
*/ */
const assert = require("chai").assert const assert = require('chai').assert
const nock = require("nock") // http call mocking const nock = require('nock') // http call mocking
const sinon = require("sinon") const sinon = require('sinon')
// const axios = require("axios") // const axios = require("axios")
// Default to unit tests unless some other value for TEST is passed. // Default to unit tests unless some other value for TEST is passed.
if (!process.env.TEST) process.env.TEST = "unit" if (!process.env.TEST) process.env.TEST = 'unit'
// const SERVER = bchjs.restURL // const SERVER = bchjs.restURL
const BCHJS = require("../../src/bch-js") const BCHJS = require('../../src/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// Mock data used for unit tests // Mock data used for unit tests
// const mockData = require("./fixtures/slp/mock-utils") // const mockData = require("./fixtures/slp/mock-utils")
// Default to unit tests unless some other value for TEST is passed. // Default to unit tests unless some other value for TEST is passed.
if (!process.env.TEST) process.env.TEST = "unit" if (!process.env.TEST) process.env.TEST = 'unit'
describe("#SLP NFT1", () => { describe('#SLP NFT1', () => {
let sandbox let sandbox
beforeEach(() => { beforeEach(() => {
@@ -38,13 +38,13 @@ describe("#SLP NFT1", () => {
sandbox.restore() sandbox.restore()
}) })
describe("#newNFTGroupOpReturn", () => { describe('#newNFTGroupOpReturn', () => {
it("should generate new NFT Group OP_RETURN code", () => { it('should generate new NFT Group OP_RETURN code', () => {
const configObj = { const configObj = {
name: "SLP Test Token", name: 'SLP Test Token',
ticker: "SLPTEST", ticker: 'SLPTEST',
documentUrl: "https://bchjs.cash", documentUrl: 'https://bchjs.cash',
documentHash: "", documentHash: '',
initialQty: 5 initialQty: 5
} }
@@ -55,48 +55,48 @@ describe("#SLP NFT1", () => {
}) })
}) })
describe("#mintNFTGroupOpReturn", () => { describe('#mintNFTGroupOpReturn', () => {
it("should generate NFT Group Mint OP_RETURN code", () => { it('should generate NFT Group Mint OP_RETURN code', () => {
const tokenUtxoData = [ const tokenUtxoData = [
{ {
txid: txid:
"3de3766b10506c9156533f1639979e49d1884521543c13e4af73647df1ed3f76", '3de3766b10506c9156533f1639979e49d1884521543c13e4af73647df1ed3f76',
vout: 2, vout: 2,
value: "546", value: '546',
height: 638207, height: 638207,
confirmations: 63, confirmations: 63,
satoshis: 546, satoshis: 546,
utxoType: "minting-baton", utxoType: 'minting-baton',
transactionType: "mint", transactionType: 'mint',
tokenId: tokenId:
"680967b3f6fe080dbca8dbd370665bd29742e3490db24e2f28d08b424511807e", '680967b3f6fe080dbca8dbd370665bd29742e3490db24e2f28d08b424511807e',
tokenType: 129, tokenType: 129,
tokenTicker: "NFTP", tokenTicker: 'NFTP',
tokenName: "NFT Parent", tokenName: 'NFT Parent',
tokenDocumentUrl: "FullStack.cash", tokenDocumentUrl: 'FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
mintBatonVout: 2, mintBatonVout: 2,
isValid: true isValid: true
}, },
{ {
txid: txid:
"3de3766b10506c9156533f1639979e49d1884521543c13e4af73647df1ed3f76", '3de3766b10506c9156533f1639979e49d1884521543c13e4af73647df1ed3f76',
vout: 1, vout: 1,
value: "546", value: '546',
height: 638207, height: 638207,
confirmations: 63, confirmations: 63,
satoshis: 546, satoshis: 546,
utxoType: "token", utxoType: 'token',
tokenQty: 10, tokenQty: 10,
transactionType: "mint", transactionType: 'mint',
tokenId: tokenId:
"680967b3f6fe080dbca8dbd370665bd29742e3490db24e2f28d08b424511807e", '680967b3f6fe080dbca8dbd370665bd29742e3490db24e2f28d08b424511807e',
tokenType: 129, tokenType: 129,
tokenTicker: "NFTP", tokenTicker: 'NFTP',
tokenName: "NFT Parent", tokenName: 'NFT Parent',
tokenDocumentUrl: "FullStack.cash", tokenDocumentUrl: 'FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
mintBatonVout: 2, mintBatonVout: 2,
isValid: true isValid: true
@@ -110,13 +110,13 @@ describe("#SLP NFT1", () => {
}) })
}) })
describe("#generateNFTChildOpReturn", () => { describe('#generateNFTChildOpReturn', () => {
it("should generate NFT Genesis OP_RETURN code", () => { it('should generate NFT Genesis OP_RETURN code', () => {
const configObj = { const configObj = {
name: "SLP Test Token", name: 'SLP Test Token',
ticker: "SLPTEST", ticker: 'SLPTEST',
documentUrl: "https://bchjs.cash", documentUrl: 'https://bchjs.cash',
documentHash: "" documentHash: ''
} }
const result = bchjs.SLP.NFT1.generateNFTChildGenesisOpReturn(configObj) const result = bchjs.SLP.NFT1.generateNFTChildGenesisOpReturn(configObj)
@@ -126,26 +126,26 @@ describe("#SLP NFT1", () => {
}) })
}) })
describe("#generateNFTChildSendOpReturn", () => { describe('#generateNFTChildSendOpReturn', () => {
it("should generate send OP_RETURN code for no change", () => { it('should generate send OP_RETURN code for no change', () => {
// Mock UTXO. // Mock UTXO.
const tokenUtxos = [ const tokenUtxos = [
{ {
txid: txid:
"81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3", '81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3',
vout: 1, vout: 1,
value: "546", value: '546',
height: 638273, height: 638273,
confirmations: 42, confirmations: 42,
satoshis: 546, satoshis: 546,
utxoType: "token", utxoType: 'token',
tokenQty: 1, tokenQty: 1,
tokenId: tokenId:
"81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3", '81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3',
tokenTicker: "NFTC", tokenTicker: 'NFTC',
tokenName: "NFT Child", tokenName: 'NFT Child',
tokenDocumentUrl: "https://FullStack.cash", tokenDocumentUrl: 'https://FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
tokenType: 129, tokenType: 129,
isValid: true isValid: true
@@ -155,29 +155,29 @@ describe("#SLP NFT1", () => {
const result = bchjs.SLP.NFT1.generateNFTChildSendOpReturn(tokenUtxos, 1) const result = bchjs.SLP.NFT1.generateNFTChildSendOpReturn(tokenUtxos, 1)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["script", "outputs"]) assert.hasAllKeys(result, ['script', 'outputs'])
assert.isNumber(result.outputs) assert.isNumber(result.outputs)
}) })
it("should generate send OP_RETURN code with change", () => { it('should generate send OP_RETURN code with change', () => {
// Mock UTXO. // Mock UTXO.
const tokenUtxos = [ const tokenUtxos = [
{ {
txid: txid:
"81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3", '81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3',
vout: 1, vout: 1,
value: "546", value: '546',
height: 638273, height: 638273,
confirmations: 42, confirmations: 42,
satoshis: 546, satoshis: 546,
utxoType: "token", utxoType: 'token',
tokenQty: 4, tokenQty: 4,
tokenId: tokenId:
"81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3", '81955624a8eb7011769ff5faa607f78f84b0f8152b9145e7db8b1e521c895ee3',
tokenTicker: "NFTC", tokenTicker: 'NFTC',
tokenName: "NFT Child", tokenName: 'NFT Child',
tokenDocumentUrl: "https://FullStack.cash", tokenDocumentUrl: 'https://FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
tokenType: 129, tokenType: 129,
isValid: true isValid: true
@@ -187,33 +187,33 @@ describe("#SLP NFT1", () => {
const result = bchjs.SLP.NFT1.generateNFTChildSendOpReturn(tokenUtxos, 1) const result = bchjs.SLP.NFT1.generateNFTChildSendOpReturn(tokenUtxos, 1)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["script", "outputs"]) assert.hasAllKeys(result, ['script', 'outputs'])
assert.isNumber(result.outputs) assert.isNumber(result.outputs)
}) })
}) })
describe("#generateNFTGroupSendOpReturn", () => { describe('#generateNFTGroupSendOpReturn', () => {
it("should generate send OP_RETURN with change", () => { it('should generate send OP_RETURN with change', () => {
// Mock UTXO. // Mock UTXO.
const tokenUtxos = [ const tokenUtxos = [
{ {
txid: txid:
"35846676e7514658bbd2fd60b1f0d4d86195908f6b2de5328d54c8e4a2d05919", '35846676e7514658bbd2fd60b1f0d4d86195908f6b2de5328d54c8e4a2d05919',
vout: 1, vout: 1,
value: "546", value: '546',
height: 638207, height: 638207,
confirmations: 3, confirmations: 3,
satoshis: 546, satoshis: 546,
utxoType: "token", utxoType: 'token',
tokenQty: 10, tokenQty: 10,
transactionType: "mint", transactionType: 'mint',
tokenId: tokenId:
"eee4b82e4bb7113eca433829144363fc45f110693c286494fbf5b5c8043cc981", 'eee4b82e4bb7113eca433829144363fc45f110693c286494fbf5b5c8043cc981',
tokenType: 129, tokenType: 129,
tokenTicker: "NFTTT", tokenTicker: 'NFTTT',
tokenName: "NFT Test Token", tokenName: 'NFT Test Token',
tokenDocumentUrl: "https://FullStack.cash", tokenDocumentUrl: 'https://FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
mintBatonVout: 2, mintBatonVout: 2,
isValid: true isValid: true
@@ -223,31 +223,31 @@ describe("#SLP NFT1", () => {
const result = bchjs.SLP.NFT1.generateNFTGroupSendOpReturn(tokenUtxos, 1) const result = bchjs.SLP.NFT1.generateNFTGroupSendOpReturn(tokenUtxos, 1)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["script", "outputs"]) assert.hasAllKeys(result, ['script', 'outputs'])
assert.isNumber(result.outputs) assert.isNumber(result.outputs)
}) })
it("should generate send OP_RETURN with no change", () => { it('should generate send OP_RETURN with no change', () => {
// Mock UTXO. // Mock UTXO.
const tokenUtxos = [ const tokenUtxos = [
{ {
txid: txid:
"35846676e7514658bbd2fd60b1f0d4d86195908f6b2de5328d54c8e4a2d05919", '35846676e7514658bbd2fd60b1f0d4d86195908f6b2de5328d54c8e4a2d05919',
vout: 1, vout: 1,
value: "546", value: '546',
height: 638207, height: 638207,
confirmations: 3, confirmations: 3,
satoshis: 546, satoshis: 546,
utxoType: "token", utxoType: 'token',
tokenQty: 10, tokenQty: 10,
transactionType: "mint", transactionType: 'mint',
tokenId: tokenId:
"eee4b82e4bb7113eca433829144363fc45f110693c286494fbf5b5c8043cc981", 'eee4b82e4bb7113eca433829144363fc45f110693c286494fbf5b5c8043cc981',
tokenType: 129, tokenType: 129,
tokenTicker: "NFTTT", tokenTicker: 'NFTTT',
tokenName: "NFT Test Token", tokenName: 'NFT Test Token',
tokenDocumentUrl: "https://FullStack.cash", tokenDocumentUrl: 'https://FullStack.cash',
tokenDocumentHash: "", tokenDocumentHash: '',
decimals: 0, decimals: 0,
mintBatonVout: 2, mintBatonVout: 2,
isValid: true isValid: true
@@ -257,7 +257,7 @@ describe("#SLP NFT1", () => {
const result = bchjs.SLP.NFT1.generateNFTGroupSendOpReturn(tokenUtxos, 10) const result = bchjs.SLP.NFT1.generateNFTGroupSendOpReturn(tokenUtxos, 10)
// console.log(`result: ${JSON.stringify(result, null, 2)}`) // console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, ["script", "outputs"]) assert.hasAllKeys(result, ['script', 'outputs'])
assert.isNumber(result.outputs) assert.isNumber(result.outputs)
}) })
}) })
File diff suppressed because it is too large Load Diff
+638 -638
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More