Finished writing unit and integration tests for ElectrumX UTXO call

This commit is contained in:
Chris Troutner
2020-04-07 12:12:36 -07:00
parent 8910bfd33b
commit 381b89f9d8
3 changed files with 70 additions and 133 deletions
+1
View File
@@ -18,6 +18,7 @@ const config = {
// 'electron.jochen-hoenicke.de:51002' // 'electron.jochen-hoenicke.de:51002'
// ] // ]
serverUrl: 'fulcrum.fountainhead.cash', serverUrl: 'fulcrum.fountainhead.cash',
// serverUrl: 'badurl.com',
serverPort: '50002' serverPort: '50002'
}, },
ratelimit: { ratelimit: {
+14 -90
View File
@@ -52,12 +52,7 @@ class Electrum {
_this.router = router _this.router = router
_this.router.get('/', _this.root) _this.router.get('/', _this.root)
// _this.router.get('/balance/:address', _this.balanceSingle) _this.router.get('/utxos/:address', _this.getUtxos)
// _this.router.post('/balance', _this.balanceBulk)
// _this.router.get('/utxos/:address', _this.utxosSingle)
// _this.router.post('/utxos', _this.utxosBulk)
// _this.router.get('/tx/:txid', _this.txSingle)
// _this.router.post('/tx', _this.txBulk)
} }
// Initializes a connection to electrum servers. // Initializes a connection to electrum servers.
@@ -113,6 +108,13 @@ class Electrum {
return res.json({ error: msg }) return res.json({ error: msg })
} }
// Handle error patterns specific to this route.
if (err.message) {
res.status(400)
return res.json({ success: false, error: err.message })
}
// If error can be handled, return the stack trace
res.status(500) res.status(500)
return res.json({ error: util.inspect(err) }) return res.json({ error: util.inspect(err) })
} }
@@ -122,114 +124,36 @@ class Electrum {
return res.json({ status: 'electrumx' }) return res.json({ status: 'electrumx' })
} }
// Query the Blockbook Node API for a balance on a single BCH address. async getUtxos (req, res, next) {
// Returns a Promise.
async balanceFromBlockbook (thisAddress) {
try {
// console.log(`BLOCKBOOK_URL: ${BLOCKBOOK_URL}`)
// Convert the address to a cashaddr without a prefix.
const addr = _this.bchjs.Address.toCashAddress(thisAddress)
const path = `${_this.BLOCKBOOKPATH.addrPath}${addr}`
// console.log(`path: ${path}`)
// Query the Blockbook Node API.
const options = {
method: 'get',
baseURL: path
}
const axiosResponse = await _this.axios.request(options)
const retData = axiosResponse.data
// console.log(`retData: ${util.inspect(retData)}`)
return retData
} catch (err) {
// Dev Note: Do not log error messages here. Throw them instead and let the
// parent function handle it.
wlogger.debug('Error in blockbook.js/balanceFromBlockbook()')
throw err
}
}
/**
* @api {get} /electrumx/balance/{addr} Get balance for a single address.
* @apiName Balance for a single address
* @apiGroup Blockbook
* @apiDescription Returns an object with balance and details about an address.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/balance/bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" -H "accept: application/json"
*
*/
// GET handler for single balance
async balanceSingle (req, res, next) {
try { try {
const address = req.params.address const address = req.params.address
if (!address || address === '') {
res.status(400)
return res.json({ error: 'address can not be empty' })
}
// Reject if address is an array. // Reject if address is an array.
if (Array.isArray(address)) { if (Array.isArray(address)) {
res.status(400) res.status(400)
return res.json({ return res.json({
success: false,
error: 'address can not be an array. Use POST for bulk upload.' error: 'address can not be an array. Use POST for bulk upload.'
}) })
} }
wlogger.debug( const cashAddr = _this.bchjs.Address.toCashAddress(address)
'Executing blockbook/balanceSingle with this address: ',
address
)
// Ensure the input is a valid BCH address.
try {
// const legacyAddr = bchjs.Address.toLegacyAddress(address)
_this.bchjs.Address.toLegacyAddress(address)
} catch (err) {
res.status(400)
return res.json({
error: `Invalid BCH address. Double check your address is valid: ${address}`
})
}
// Prevent a common user error. Ensure they are using the correct network address. // Prevent a common user error. Ensure they are using the correct network address.
const networkIsValid = _this.routeUtils.validateNetwork(address) const networkIsValid = _this.routeUtils.validateNetwork(cashAddr)
if (!networkIsValid) { if (!networkIsValid) {
res.status(400) res.status(400)
return res.json({ return res.json({
success: false,
error: error:
'Invalid network. Trying to use a testnet address on mainnet, or vice versa.' 'Invalid network. Trying to use a testnet address on mainnet, or vice versa.'
}) })
} }
// Query the Blockbook Node API.
const retData = await _this.balanceFromBlockbook(address)
// Return the retrieved address information.
res.status(200)
return res.json(retData)
} catch (err) {
// Write out error to error log.
wlogger.error('Error in blockbook.js/balanceSingle().', err)
return _this.errorHandler(err, res)
}
}
async getUtxos (req, res, next) {
try {
const address = _this.bchjs.Address.toCashAddress(req.params.address)
wlogger.debug('Executing electrumx/getUtxos with this address: ', address) wlogger.debug('Executing electrumx/getUtxos with this address: ', address)
// Convert the address to a scripthash. // Convert the address to a scripthash.
const scripthash = _this.addressToScripthash(address) const scripthash = _this.addressToScripthash(cashAddr)
if (!_this.isReady) { if (!_this.isReady) {
throw new Error( throw new Error(
+55 -43
View File
@@ -106,53 +106,65 @@ describe('#ElectrumX Router', () => {
}) })
describe('#UTXO', () => { describe('#UTXO', () => {
// details route handler. it('should throw 400 if address is empty', async () => {
// const balanceSingle = blockbookRoute.balanceSingle const result = await electrumxRoute.getUtxos(req, res)
// console.log(`result: ${util.inspect(result)}`)
// it('should throw 400 if address is empty', async () => { assert.equal(res.statusCode, 400, 'Expect 400 status code')
// const result = await blockbookRoute.balanceSingle(req, res)
// // console.log(`result: ${util.inspect(result)}`)
//
// assert.hasAllKeys(result, ['error'])
// assert.include(result.error, 'address can not be empty')
// })
// it('should error on an array', async () => { assert.property(result, 'error')
// req.params.address = ['qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'] assert.include(result.error, 'Unsupported address format')
//
// const result = await blockbookRoute.balanceSingle(req, res)
//
// assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
// assert.include(
// result.error,
// 'address can not be an array',
// 'Proper error message'
// )
// })
// it('should throw an error for an invalid address', async () => { assert.property(result, 'success')
// req.params.address = assert.equal(result.success, false)
// '02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c' })
//
// const result = await blockbookRoute.balanceSingle(req, res)
//
// assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
// assert.include(
// result.error,
// 'Invalid BCH address',
// 'Proper error message'
// )
// })
// it('should detect a network mismatch', async () => { it('should throw 400 on array input', async () => {
// req.params.address = req.params.address = ['qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c']
// 'bchtest:qq89kjkeqz9mngp8kl3dpmu43y2wztdjqu500gn4c4'
// const result = await electrumxRoute.getUtxos(req, res)
// const result = await blockbookRoute.balanceSingle(req, res) // console.log(`result: ${util.inspect(result)}`)
//
// assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.') assert.equal(res.statusCode, 400, 'Expect 400 status code')
// assert.include(result.error, 'Invalid network', 'Proper error message')
// }) assert.property(result, 'error')
assert.include(result.error, 'address can not be an array')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw an error for an invalid address', async () => {
req.params.address =
'02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'
const result = await electrumxRoute.getUtxos(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 400, 'Expect 400 status code')
assert.property(result, 'error')
assert.include(result.error, 'Unsupported address format')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should detect a network mismatch', async () => {
req.params.address =
'bchtest:qq89kjkeqz9mngp8kl3dpmu43y2wztdjqu500gn4c4'
const result = await electrumxRoute.getUtxos(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 400, 'Expect 400 status code')
assert.property(result, 'error')
assert.include(result.error, 'Invalid network', 'Proper error message')
assert.property(result, 'success')
assert.equal(result.success, false)
})
// it('should throw 500 when network issues', async () => { // it('should throw 500 when network issues', async () => {
// const savedUrl = process.env.BLOCKBOOK_URL // const savedUrl = process.env.BLOCKBOOK_URL