Compare commits

..
22 Commits
Author SHA1 Message Date
Chris Troutner 4f4984a982 Merge pull request #162 from Permissionless-Software-Foundation/ct-unstable
feat(getBlockHash): Reimplementing lost getBlockHash method in Blockc…
2021-09-21 07:41:44 -07:00
Chris Troutner d9fc84f136 feat(getBlockHash): Reimplementing lost getBlockHash method in Blockchain lib 2021-09-21 07:39:18 -07:00
Chris Troutner d444666dec Merge pull request #160 from Permissionless-Software-Foundation/ct-unstable
fix(tests): Fixing broken JWT token test
2021-08-16 08:30:31 -07:00
Chris Troutner c8f3649004 fix(tests): Fixing broken JWT token test 2021-08-16 08:26:39 -07:00
Chris Troutner ee876ce8e4 Merge pull request #159 from Permissionless-Software-Foundation/ct-unstable
fix(bch-js): Bumping to v4.20.7
2021-08-09 10:47:44 -07:00
Chris Troutner fbd02802f0 Merge branch 'master' into ct-unstable 2021-08-09 10:45:32 -07:00
Chris Troutner 6e72879103 fix(bch-js): Bumping to v4.20.7 2021-08-09 10:44:43 -07:00
Chris Troutner 2817300ad6 Merge pull request #158 from Permissionless-Software-Foundation/ct-unstable
fix(debug): Removing debugging statements
2021-08-07 12:45:43 -07:00
Chris Troutner 4aa7cad552 fix(debug): Removing debugging statements 2021-08-07 12:44:14 -07:00
Chris Troutner 5a9401aeb1 Merge pull request #157 from Permissionless-Software-Foundation/ct-unstable
fix(jwt): Getting closer to root cause
2021-08-07 12:23:27 -07:00
Chris Troutner 0ae02790a2 fix(jwt): Getting closer to root cause 2021-08-07 12:21:25 -07:00
Chris Troutner 4d3adab9e0 Merge pull request #156 from Permissionless-Software-Foundation/ct-unstable
fix(jwt): A little more jwt debugging
2021-08-07 12:16:21 -07:00
Chris Troutner 91f06b6311 Merge branch 'master' into ct-unstable 2021-08-07 12:14:23 -07:00
Chris Troutner 2fc175d818 fix(jwt): A little more jwt debugging 2021-08-07 12:14:09 -07:00
Chris Troutner 731861cb1d Merge pull request #155 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Digging deeper into rate limit debugging
2021-08-07 11:55:28 -07:00
Chris Troutner 9a01f5ffe6 Merge branch 'master' into ct-unstable 2021-08-07 11:45:53 -07:00
Chris Troutner c62c515474 fix(rate limits): Digging deeper into rate limit debugging 2021-08-07 11:45:42 -07:00
Chris Troutner ab198b958e Merge pull request #154 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Adding object for debugging rate limit issues
2021-08-07 11:35:29 -07:00
Chris Troutner 2618008247 fix(rate limits): Adding object for debugging rate limit issues 2021-08-07 11:32:04 -07:00
Chris Troutner df27ba2063 Merge pull request #153 from Permissionless-Software-Foundation/ct-unstable
Fixing unit tests
2021-08-03 11:41:02 -07:00
Chris Troutner f19e70ae40 feat(sweep): Removing sweep utility from v5/util route 2021-08-03 11:36:23 -07:00
Chris Troutner 63fa97c998 fix(electrumx): Fixing unit tests for v5 Electrumx route 2021-08-03 11:30:18 -07:00
11 changed files with 16193 additions and 1259 deletions
+15724 -273
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -31,7 +31,7 @@
"node": ">=10.15.1" "node": ">=10.15.1"
}, },
"dependencies": { "dependencies": {
"@psf/bch-js": "^4.18.0", "@psf/bch-js": "^4.20.7",
"apidoc": "^0.26.0", "apidoc": "^0.26.0",
"axios": "^0.21.1", "axios": "^0.21.1",
"bitcore-lib-cash": "^8.23.1", "bitcore-lib-cash": "^8.23.1",
+2
View File
@@ -12,6 +12,8 @@
// req.locals.jwtToken property. // req.locals.jwtToken property.
const getTokenFromHeaders = (req, res, next) => { const getTokenFromHeaders = (req, res, next) => {
try { try {
// console.log('req.headers: ', req.headers)
// Only executes if the authorization header exists. // Only executes if the authorization header exists.
if (req.headers.authorization) { if (req.headers.authorization) {
// Retrieve the auth string from the header object. // Retrieve the auth string from the header object.
+13
View File
@@ -220,11 +220,18 @@ class RateLimits {
// it will return the 'res' object with an error status and message, which // it will return the 'res' object with an error status and message, which
// should be returned by the middleware. // should be returned by the middleware.
async trackRateLimits (req, res, jwtToken) { async trackRateLimits (req, res, jwtToken) {
const debugInfo = {
jwtToken,
userObj: req.body.usrObj,
locals: req.locals
}
// Anonymous rate limits are used by default. // Anonymous rate limits are used by default.
let pointsToConsume = ANON_LIMITS let pointsToConsume = ANON_LIMITS
// console.log('pointsToConsume: ', pointsToConsume) // console.log('pointsToConsume: ', pointsToConsume)
let key = req.ip // Use the IP address as the key, by default. let key = req.ip // Use the IP address as the key, by default.
debugInfo.ip = req.ip
// console.log('jwtToken: ', jwtToken) // console.log('jwtToken: ', jwtToken)
@@ -236,8 +243,10 @@ class RateLimits {
// Preferentially use the decoded ID in the JWT payload, as the key. // Preferentially use the decoded ID in the JWT payload, as the key.
key = decoded.id key = decoded.id
debugInfo.id = key
pointsToConsume = decoded.pointsToConsume pointsToConsume = decoded.pointsToConsume
debugInfo.pointsToConsume = pointsToConsume
} }
// console.log(`rate limit key: ${key}`) // console.log(`rate limit key: ${key}`)
@@ -261,6 +270,10 @@ class RateLimits {
res.locals.rateLimitTriggered = true res.locals.rateLimitTriggered = true
// console.log('res.locals: ', res.locals) // console.log('res.locals: ', res.locals)
// console.log(
// `rate limit debug info: ${JSON.stringify(debugInfo, null, 2)}`
// )
// Rate limited was triggered // Rate limited was triggered
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330 res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({ return res.json({
+7 -1
View File
@@ -34,6 +34,7 @@ class Electrum {
this.fulcrumApi = process.env.FULCRUM_API this.fulcrumApi = process.env.FULCRUM_API
if (!this.fulcrumApi) { if (!this.fulcrumApi) {
// console.warn('FULCRUM_API env var not set. Can not connect to Fulcrum indexer.')
throw new Error( throw new Error(
'FULCRUM_API env var not set. Can not connect to Fulcrum indexer.' 'FULCRUM_API env var not set. Can not connect to Fulcrum indexer.'
) )
@@ -451,11 +452,13 @@ class Electrum {
const response = await _this.axios.get( const response = await _this.axios.get(
`${_this.fulcrumApi}electrumx/tx/data/${txid}` `${_this.fulcrumApi}electrumx/tx/data/${txid}`
) )
// console.log(`_transactionDetailsFromElectrum(): ${JSON.stringify(electrumResponse, null, 2)}`) // console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
res.status(200) res.status(200)
return res.json(response.data) return res.json(response.data)
} catch (err) { } catch (err) {
console.log('err: ', err)
// Write out error to error log. // Write out error to error log.
wlogger.error('Error in elecrumx.js/getTransactionDetails().', err) wlogger.error('Error in elecrumx.js/getTransactionDetails().', err)
@@ -1085,6 +1088,9 @@ class Electrum {
errorHandler (err, res) { errorHandler (err, res) {
// Attempt to decode the error message. // Attempt to decode the error message.
const { msg, status } = _this.routeUtils.decodeError(err) const { msg, status } = _this.routeUtils.decodeError(err)
// console.log('errorHandler msg: ', msg)
// console.log('errorHandler status: ', status)
if (msg) { if (msg) {
res.status(status) res.status(status)
return res.json({ success: false, error: msg }) return res.json({ success: false, error: msg })
File diff suppressed because it is too large Load Diff
+3 -409
View File
@@ -14,27 +14,8 @@ util.inspect.defaultOptions = { depth: 1 }
const BCHJS = require('@psf/bch-js') const BCHJS = require('@psf/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS()
// const BCHJS_TESTNET = 'https://testnet.bchjs.cash/v5/'
// const bchjsHTTP = axios.create({ // let _this
// baseURL: process.env.RPC_BASEURL
// })
// const username = process.env.RPC_USERNAME
// const password = process.env.RPC_PASSWORD
// const requestConfig = {
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: '1.0'
// }
// }
let _this
class UtilRoute { class UtilRoute {
constructor (utilConfig) { constructor (utilConfig) {
@@ -58,9 +39,9 @@ class UtilRoute {
this.router.get('/', this.root) this.router.get('/', this.root)
this.router.get('/validateAddress/:address', this.validateAddressSingle) this.router.get('/validateAddress/:address', this.validateAddressSingle)
this.router.post('/validateAddress', this.validateAddressBulk) this.router.post('/validateAddress', this.validateAddressBulk)
this.router.post('/sweep', this.sweepWif) // this.router.post('/sweep', this.sweepWif)
_this = this // _this = this
} }
root (req, res, next) { root (req, res, next) {
@@ -214,393 +195,6 @@ class UtilRoute {
return res.json({ error: util.inspect(err) }) return res.json({ error: util.inspect(err) })
} }
} }
/**
* @api {post} /util/sweep Sweep BCH and tokens
* @apiName Sweep BCH and tokens from a paper wallet
* @apiGroup Util
* @apiDescription This function can be used to check the BCH balance of a
* paper wallet. It can also be used to sweep BCH and tokens from a paper
* wallet and send them to a destination address.
*
* Note: It does not yet support multiple token classes on the same paper wallet.
*
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v5/util/sweep" -H "accept: application/json" -H "Content-Type: application/json" -d '{"wif":"Kz52sdXLAiKtH82iAFRi6aTZanWtW5Eyv37KWdpY6tTv7pjoHste", "balanceOnly": true}'
* curl -X POST "https://api.fullstack.cash/v5/util/sweep" -H "accept: application/json" -H "Content-Type: application/json" -d '{"wif":"Kz52sdXLAiKtH82iAFRi6aTZanWtW5Eyv37KWdpY6tTv7pjoHste", "toAddr": "bitcoincash:qpt8m4kqu963geedyrur6pdggqmv5kxwnq0rn322qu"}'
*
*
*/
async sweepWif (req, res, next) {
try {
// Validate input
const wif = req.body.wif
const toAddr = req.body.toAddr
const balanceOnly = req.body.balanceOnly
if (typeof wif !== 'string' || wif.length !== 52) {
res.status(400)
return res.json({
error: 'WIF needs to a proper compressed WIF starting with K or L'
})
}
if (!balanceOnly) {
// Only throw error if balanceOnly is false or undefined.
if (!toAddr || toAddr === '') {
res.status(400)
return res.json({ error: 'address can not be empty' })
}
}
wlogger.debug('Executing util/sweepWif with this address: ', toAddr)
// Generate a private and public key pair from the WIF.
const ecPair = bchjs.ECPair.fromWIF(wif)
const fromAddr = bchjs.ECPair.toCashAddress(ecPair)
// Get a balance on the public address
const balances = await _this.electrumx._balanceFromElectrumx(fromAddr)
// console.log(`balances: ${JSON.stringify(balances, null, 2)}`)
// Total balance is the sum of the confirmed and unconfirmed balance.
const totalBalance = balances.confirmed + balances.unconfirmed
// Exit if balance is zero.
if (isNaN(totalBalance) || totalBalance === 0) {
res.status(422)
return res.json({ error: 'No balance found at BCH address.' })
}
// Exit if this is a balance-only call.
if (balanceOnly) {
res.status(200)
return res.json(totalBalance)
}
// Get all UTXOs help by the address.
const utxos = await _this.electrumx._utxosFromElectrumx(fromAddr)
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
const tokenUtxos = []
const bchUtxos = []
// Exit if there are no UTXOs.
if (utxos.length === 0) {
res.status(422)
return res.json({ error: 'No utxos found.' })
}
// Figure out which UTXOs are associated with SLP tokens.
const isTokenUtxo = await _this.bchjs.SLP.Utils.tokenUtxoDetails(utxos)
// console.log(`isTokenUtxo: ${JSON.stringify(isTokenUtxo, null, 2)}`)
// Separate the bch and token UTXOs.
for (let i = 0; i < utxos.length; i++) {
// Filter based on isTokenUtxo.
if (!isTokenUtxo[i]) bchUtxos.push(utxos[i])
else tokenUtxos.push(isTokenUtxo[i])
}
// console.log(
// `bchUtxos.length: ${bchUtxos.length}, tokenUtxos.length: ${tokenUtxos.length}`
// )
// Throw error if no BCH to move tokens.
if (bchUtxos.length === 0 && tokenUtxos.length > 0) {
res.status(422)
return res.json({
error:
'Tokens found, but no BCH UTXOs found. Add BCH to wallet to move tokens.'
})
}
// console.log(`tokenUtxos: ${JSON.stringify(tokenUtxos, null, 2)}`)
const options = {
ecPair,
utxos,
fromAddr,
toAddr,
bchUtxos,
tokenUtxos
}
let hex
// Choose the sweeping algorithm, based on if there are tokens or not.
if (tokenUtxos.length === 0) hex = await _this._sweepBCH(options)
else hex = await _this._sweepTokens(options, bchUtxos, tokenUtxos)
// console.log(`hex: ${hex}`)
// Throw error if there is more than one token class.
// Generate a transaction to move tokens and BCH.
// Broadcast the transaction.
const txid = _this.bchjs.RawTransactions.sendRawTransaction([hex])
res.status(200)
return res.json(txid)
} catch (err) {
// Attempt to decode the error message.
const { msg, status } = routeUtils.decodeError(err)
if (msg) {
res.status(status)
return res.json({ error: msg })
}
// Catch the specific case of multiple tokens.
if (
err.message &&
err.message.indexOf('Multiple token classes detected') > -1
) {
res.status(422)
return res.json({ error: err.message })
}
wlogger.error('Error in util.js/sweepWif().', err)
console.error('Error in util.js/sweepWif().', err)
res.status(500)
return res.json({ error: err.message })
}
}
// Sweep BCH only from a private WIF.
async _sweepBCH (options) {
try {
// const wif = flags.wif
// const toAddr = flags.address
const ecPair = options.ecPair
const toAddr = options.toAddr
// const fromAddr = this.BITBOX.ECPair.toCashAddress(ecPair)
//
// // Get the UTXOs for that address.
// let utxos = await this.BITBOX.Blockbook.utxo(fromAddr)
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
let utxos = options.utxos
// Ensure all utxos have the satoshis property.
utxos = utxos.map((x) => {
x.satoshis = Number(x.value)
return x
})
// console.log(`utxos: ${JSON.stringify(utxos, null, 2)}`)
// instance of transaction builder
let transactionBuilder
if (options.testnet) {
transactionBuilder = new _this.bchjs.TransactionBuilder('testnet')
} else transactionBuilder = new _this.bchjs.TransactionBuilder()
let originalAmount = 0
// Loop through all UTXOs.
for (let i = 0; i < utxos.length; i++) {
const utxo = utxos[i]
originalAmount = originalAmount + utxo.value
transactionBuilder.addInput(utxo.tx_hash, utxo.tx_pos)
}
if (originalAmount < 546) {
throw new Error(
'Original amount less than the dust limit. Not enough BCH to send.'
)
}
// get byte count to calculate fee. paying 1 sat/byte
const byteCount = _this.bchjs.BitcoinCash.getByteCount(
{ P2PKH: utxos.length },
{ P2PKH: 1 }
)
const fee = Math.ceil(1.1 * byteCount)
// amount to send to receiver. It's the original amount - 1 sat/byte for tx size
const sendAmount = originalAmount - fee
// add output w/ address and amount to send
transactionBuilder.addOutput(
_this.bchjs.Address.toLegacyAddress(toAddr),
sendAmount
)
// Loop through each input and sign
let redeemScript
for (var i = 0; i < utxos.length; i++) {
const utxo = utxos[i]
transactionBuilder.sign(
i,
ecPair,
redeemScript,
transactionBuilder.hashTypes.SIGHASH_ALL,
utxo.value
)
}
// build tx
const tx = transactionBuilder.build()
// output rawhex
const hex = tx.toHex()
return hex
} catch (err) {
wlogger.error('Error in util.js/sweepBCH().')
throw err
}
}
// Sweep BCH and tokens from a WIF.
async _sweepTokens (options) {
try {
// const { ecPair, utxos, fromAddr, toAddr, bchUtxos, tokenUtxos } = options
const { ecPair, utxos, toAddr, bchUtxos, tokenUtxos } = options
// Input validation
if (!Array.isArray(bchUtxos) || bchUtxos.length === 0) {
throw new Error('bchUtxos need to be an array with one UTXO.')
}
if (!Array.isArray(tokenUtxos) || tokenUtxos.length === 0) {
throw new Error('tokenUtxos need to be an array with one UTXO.')
}
// if (flags.testnet)
// this.BITBOX = new config.BCHLIB({ restURL: config.TESTNET_REST })
// console.log(`tokenUtxos: ${JSON.stringify(tokenUtxos, null, 2)}`)
// Ensure there is only one class of token in the wallet. Throw an error if
// there is more than one.
const tokenId = tokenUtxos[0].tokenId
const otherTokens = tokenUtxos.filter((x) => x.tokenId !== tokenId)
if (otherTokens.length > 0) {
throw new Error(
'Multiple token classes detected. This function only supports a single class of token.'
)
}
// instance of transaction builder
let transactionBuilder
if (options.testnet) {
transactionBuilder = new _this.bchjs.TransactionBuilder('testnet')
} else transactionBuilder = new _this.bchjs.TransactionBuilder()
// Combine all the UTXOs into a single array.
const allUtxos = utxos
// console.log(`allUtxos: ${JSON.stringify(allUtxos, null, 2)}`)
// Loop through all UTXOs.
let originalAmount = 0
for (let i = 0; i < allUtxos.length; i++) {
const utxo = allUtxos[i]
originalAmount = originalAmount + utxo.value
transactionBuilder.addInput(utxo.tx_hash, utxo.tx_pos)
}
if (originalAmount < 300) {
throw new Error(
'Not enough BCH to send. Send more BCH to the wallet to pay miner fees.'
)
}
// get byte count to calculate fee. paying 1 sat
// Note: This may not be totally accurate. Just guessing on the byteCount size.
// const byteCount = this.BITBOX.BitcoinCash.getByteCount(
// { P2PKH: 3 },
// { P2PKH: 5 }
// )
// //console.log(`byteCount: ${byteCount}`)
// const satoshisPerByte = 1.1
// const txFee = Math.floor(satoshisPerByte * byteCount)
// console.log(`txFee: ${txFee} satoshis\n`)
const txFee = 500
// amount to send back to the sending address. It's the original amount - 1 sat/byte for tx size
const remainder = originalAmount - txFee - 546
if (remainder < 1) {
throw new Error('Selected UTXO does not have enough satoshis')
}
// console.log(`remainder: ${remainder}`)
// Tally up the quantity of tokens
let tokenQty = 0
for (let i = 0; i < tokenUtxos.length; i++) {
tokenQty += tokenUtxos[i].tokenQty
}
// console.log(`tokenQty: ${tokenQty}`)
// Generate the OP_RETURN entry for an SLP SEND transaction.
// console.log(`Generating op-return.`)
const {
script,
outputs
} = _this.bchjs.SLP.TokenType1.generateSendOpReturn(tokenUtxos, tokenQty)
// console.log(`token outputs: ${outputs}`)
// Since we are sweeping all tokens from the WIF, there generateOpReturn()
// function should only compute 1 token output. If it returns 2, then there
// is something unexpected happening.
if (outputs > 1) {
throw new Error(
'More than one class of token detected. Sweep feature not supported.'
)
}
// Add OP_RETURN as first output.
const data = _this.bchjs.Script.encode(script)
transactionBuilder.addOutput(data, 0)
// Send dust transaction representing tokens being sent.
transactionBuilder.addOutput(
_this.bchjs.Address.toLegacyAddress(toAddr),
546
)
// Last output: send remaining BCH
transactionBuilder.addOutput(
_this.bchjs.Address.toLegacyAddress(toAddr),
remainder
)
// console.log(`utxo: ${JSON.stringify(utxo, null, 2)}`)
// Sign each UTXO being consumed.
let redeemScript
for (let i = 0; i < allUtxos.length; i++) {
const thisUtxo = allUtxos[i]
// console.log(`thisUtxo: ${JSON.stringify(thisUtxo, null, 2)}`)
transactionBuilder.sign(
i,
ecPair,
redeemScript,
transactionBuilder.hashTypes.SIGHASH_ALL,
thisUtxo.value
)
}
// build tx
const tx = transactionBuilder.build()
// output rawhex
const hex = tx.toHex()
// console.log(`Transaction raw hex: `)
// console.log(hex)
return hex
} catch (err) {
wlogger.error('Error in util.js/sweepBCH().')
throw err
}
}
} }
module.exports = UtilRoute module.exports = UtilRoute
+5
View File
@@ -175,6 +175,11 @@ class RouteUtils {
msg: '429 Too Many Requests', msg: '429 Too Many Requests',
status: 429 status: 429
} }
} else if (err.error.includes('Network error:')) {
return {
msg: err.error,
status: 503
}
} }
} }
+38 -12
View File
@@ -30,25 +30,18 @@ const mockData = require('./mocks/electrumx-mock')
const util = require('util') const util = require('util')
util.inspect.defaultOptions = { depth: 1 } util.inspect.defaultOptions = { depth: 1 }
// A wrapper for asserting that the correct response is returned when an error if (!process.env.FULCRUM_API) process.env.FULCRUM_API = 'http://localhost'
// is expected.
// function expectRouteError (res, result, expectedError, code = 400) {
// assert.equal(res.statusCode, code, `HTTP status code ${code} expected.`)
//
// assert.property(result, 'error')
// assert.include(result.error, expectedError)
//
// assert.property(result, 'success')
// assert.equal(result.success, false)
// }
describe('#Electrumx', () => { describe('#Electrumx', () => {
let req, res let req, res
let sandbox let sandbox
const electrumxRoute = new ElecrumxRoute() const electrumxRoute = new ElecrumxRoute()
// let electrumxRoute
before(async () => { before(async () => {
if (!process.env.TEST) process.env.TEST = 'unit' if (!process.env.TEST) {
process.env.TEST = 'unit'
}
console.log(`Testing type is: ${process.env.TEST}`) console.log(`Testing type is: ${process.env.TEST}`)
if (!process.env.NETWORK) process.env.NETWORK = 'testnet' if (!process.env.NETWORK) process.env.NETWORK = 'testnet'
@@ -641,9 +634,25 @@ describe('#Electrumx', () => {
}) })
it('should pass errors from electrum-cash to user', async () => { it('should pass errors from electrum-cash to user', async () => {
if (process.env.TEST === 'unit') {
sandbox.stub(electrumxRoute.axios, 'get').rejects({
response: {
data: {
error: {
message: {
success: false,
error: 'Invalid tx hash'
}
}
}
}
})
}
req.params.txid = '02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c' req.params.txid = '02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'
const result = await electrumxRoute.getTransactionDetails(req, res) const result = await electrumxRoute.getTransactionDetails(req, res)
// console.log('result: ', result)
assert.property(result, 'error') assert.property(result, 'error')
assert.include(result.error.error, 'Invalid tx hash') assert.include(result.error.error, 'Invalid tx hash')
@@ -823,11 +832,28 @@ describe('#Electrumx', () => {
}) })
it('should pass errors from electrum-cash to user', async () => { it('should pass errors from electrum-cash to user', async () => {
if (process.env.TEST === 'unit') {
sandbox.stub(electrumxRoute.axios, 'post').rejects({
response: {
data: {
error: {
message: {
success: false,
error:
'the transaction was rejected by network rules.\n\nTX decode failed\n'
}
}
}
}
})
}
req.body.txHex = mockData.txDetails.hex.substring(10) req.body.txHex = mockData.txDetails.hex.substring(10)
const result = await electrumxRoute.broadcastTransaction(req, res) const result = await electrumxRoute.broadcastTransaction(req, res)
// console.log(`result: ${util.inspect(result)}`) // console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 400, 'Expect 400 status code') assert.equal(res.statusCode, 400, 'Expect 400 status code')
// assert.equal(res.statusCode, 503, 'Expect 503 status code')
assert.property(result, 'error') assert.property(result, 'error')
assert.include(result.error.error, 'the transaction was rejected') assert.include(result.error.error, 'the transaction was rejected')
+12 -10
View File
@@ -73,16 +73,18 @@ describe('#JWTRouter', () => {
const result = await uut.jwtInfo(req, res) const result = await uut.jwtInfo(req, res)
// console.log('result: ', result) // console.log('result: ', result)
assert.property(result, 'id') assert.equal(result.error, 'jwt expired')
assert.property(result, 'email')
assert.property(result, 'apiLevel') // assert.property(result, 'id')
assert.property(result, 'rateLimit') // assert.property(result, 'email')
assert.property(result, 'pointsToConsume') // assert.property(result, 'apiLevel')
assert.property(result, 'duration') // assert.property(result, 'rateLimit')
assert.property(result, 'iat') // assert.property(result, 'pointsToConsume')
assert.property(result, 'exp') // assert.property(result, 'duration')
assert.property(result, 'expiration') // assert.property(result, 'iat')
assert.property(result, 'createdAt') // assert.property(result, 'exp')
// assert.property(result, 'expiration')
// assert.property(result, 'createdAt')
}) })
it('should return an error with malformed JWT token', async () => { it('should return an error with malformed JWT token', async () => {
+5 -212
View File
@@ -19,7 +19,7 @@ const nock = require('nock') // HTTP mocking
const sinon = require('sinon') const sinon = require('sinon')
// Local libraries // Local libraries
const Electrumx = require('../../src/routes/v5/electrumx') // const Electrumx = require('../../src/routes/v5/electrumx')
const UtilRoute = require('../../src/routes/v5/util') const UtilRoute = require('../../src/routes/v5/util')
let originalEnvVars // Used during transition from integration to unit tests. let originalEnvVars // Used during transition from integration to unit tests.
@@ -38,8 +38,8 @@ const utilRouteInst = new UtilRoute({ electrumx: {} })
describe('#Util', () => { describe('#Util', () => {
let req, res let req, res
let sandbox let sandbox
let electrumx // let electrumx
let utilRoute // let utilRoute
before(async () => { before(async () => {
// Save existing environment variables. // Save existing environment variables.
@@ -59,7 +59,7 @@ describe('#Util', () => {
process.env.RPC_PASSWORD = 'fakepassword' process.env.RPC_PASSWORD = 'fakepassword'
} }
electrumx = new Electrumx() // electrumx = new Electrumx()
// await electrumx.connect() // await electrumx.connect()
}) })
@@ -79,7 +79,7 @@ describe('#Util', () => {
sandbox = sinon.createSandbox() sandbox = sinon.createSandbox()
utilRoute = new UtilRoute({ electrumx }) // utilRoute = new UtilRoute({ electrumx })
}) })
afterEach(() => { afterEach(() => {
@@ -322,211 +322,4 @@ describe('#Util', () => {
]) ])
}) })
}) })
describe('#sweepWif', () => {
it('should throw 400 if WIF is not included', async () => {
req.body = {}
const result = await utilRouteInst.sweepWif(req, res)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'WIF needs to a proper compressed WIF starting with K or L',
'Proper error message'
)
})
it('should throw 400 if WIF is malformed', async () => {
req.body = {
wif: 'abc123'
}
const result = await utilRouteInst.sweepWif(req, res)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'WIF needs to a proper compressed WIF starting with K or L',
'Proper error message'
)
})
it('should throw 400 if destination address is not included', async () => {
req.body = {
wif: 'L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt'
}
const result = await utilRouteInst.sweepWif(req, res)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'address can not be empty',
'Proper error message'
)
})
// Unit test only.
if (process.env.TEST === 'unit') {
it('should generate transaction for valid token sweep', async () => {
// Mock the RPC call for unit tests.
sandbox
.stub(utilRoute.electrumx, '_balanceFromElectrumx')
.resolves(mockData.mockBalance)
sandbox
.stub(utilRoute.electrumx, '_utxosFromElectrumx')
.resolves(mockData.mockUtxos)
sandbox
.stub(utilRoute.bchjs.SLP.Utils, 'tokenUtxoDetails')
.resolves(mockData.mockIsTokenUtxos)
// Mock sendRawTransaction() so that the hex does not actually get broadcast
// to the network.
sandbox
.stub(utilRoute.bchjs.RawTransactions, 'sendRawTransaction')
.resolves('test-txid')
req.body = {
wif: 'L1wAGEN721LHDoiN8pLwwBb87bYrU6Gs21UPcCRR7LjKypQyVaCq',
toAddr: 'bitcoincash:qp2g4cnekxsjspccmtvh5k73mczz6273js4mjr353r'
}
const result = await utilRoute.sweepWif(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result, 'test-txid')
})
it('should return balance if balance-only is true', async () => {
// Mock the RPC call for unit tests.
sandbox
.stub(utilRoute.electrumx, '_balanceFromElectrumx')
.resolves(mockData.mockBalance)
// Mock sendRawTransaction() so that the hex does not actually get broadcast
// to the network.
sandbox
.stub(utilRoute.bchjs.RawTransactions, 'sendRawTransaction')
.resolves('test-txid')
req.body = {
wif: 'L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt',
balanceOnly: true
}
const result = await utilRoute.sweepWif(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isNumber(result)
})
it('should generate transaction for valid BCH-only sweep', async () => {
sandbox
.stub(utilRoute.electrumx, '_balanceFromElectrumx')
.resolves(mockData.mockBalance)
sandbox
.stub(utilRoute.electrumx, '_utxosFromElectrumx')
.resolves(mockData.mockUtxos)
// Force token utxo to appear as regular BCH utxo.
sandbox
.stub(utilRoute.bchjs.SLP.Utils, 'tokenUtxoDetails')
.resolves([false, false])
// Mock sendRawTransaction() so that the hex does not actually get broadcast
// to the network.
sandbox
.stub(utilRoute.bchjs.RawTransactions, 'sendRawTransaction')
.resolves('test-txid')
req.body = {
wif: 'L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt',
toAddr: 'bitcoincash:qz2qn6zt4qmacf4r6c0e2pdcqsgnkxaa3ql2xpee6p'
}
const result = await utilRoute.sweepWif(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result, 'test-txid')
})
it('should throw 422 error if no non-token UTXOs', async () => {
sandbox
.stub(utilRoute.electrumx, '_balanceFromElectrumx')
.resolves(mockData.mockBalance)
sandbox
.stub(utilRoute.electrumx, '_utxosFromElectrumx')
.resolves(mockData.mockUtxos)
// Force token utxo to appear as regular BCH utxo.
sandbox
.stub(utilRoute.bchjs.SLP.Utils, 'tokenUtxoDetails')
.resolves(mockData.tokensOnly)
// Mock sendRawTransaction() so that the hex does not actually get broadcast
// to the network.
sandbox
.stub(utilRoute.bchjs.RawTransactions, 'sendRawTransaction')
.resolves('test-txid')
req.body = {
wif: 'L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt',
toAddr: 'bitcoincash:qz2qn6zt4qmacf4r6c0e2pdcqsgnkxaa3ql2xpee6p'
}
const result = await utilRoute.sweepWif(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(res.statusCode, 422)
assert.property(result, 'error')
assert.include(
result.error,
'Tokens found, but no BCH UTXOs found. Add BCH to wallet to move tokens'
)
})
it('should detect and throw error for multiple token classes', async () => {
sandbox
.stub(utilRoute.electrumx, '_balanceFromElectrumx')
.resolves(mockData.mockBalance)
sandbox
.stub(utilRoute.electrumx, '_utxosFromElectrumx')
.resolves(mockData.mockThreeUtxos)
// Force token utxo to appear as regular BCH utxo.
sandbox
.stub(utilRoute.bchjs.SLP.Utils, 'tokenUtxoDetails')
.resolves(mockData.multipleTokens)
// Mock sendRawTransaction() so that the hex does not actually get broadcast
// to the network.
sandbox
.stub(utilRoute.bchjs.RawTransactions, 'sendRawTransaction')
.resolves('test-txid')
req.body = {
wif: 'L5GEFg1tETLWBugmhSo9Zc4ms968qVmfmTroDxsJ982AiudAQGyt',
toAddr: 'bitcoincash:qz2qn6zt4qmacf4r6c0e2pdcqsgnkxaa3ql2xpee6p'
}
const result = await utilRoute.sweepWif(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(res.statusCode, 422)
assert.property(result, 'error')
assert.include(
result.error,
'Multiple token classes detected. This function only supports a single class of token'
)
})
}
})
}) })