fix(POST electrumx/balance): Implemented with unit and integration tests

This commit is contained in:
Chris Troutner
2020-04-16 20:26:54 -07:00
parent 9cb33f96f8
commit 9172c5ceb0
2 changed files with 235 additions and 14 deletions
+105 -14
View File
@@ -51,6 +51,7 @@ class Electrum {
_this.router.get('/utxos/:address', _this.getUtxos)
_this.router.post('/utxos', _this.utxosBulk)
_this.router.get('/balance/:address', _this.getBalance)
_this.router.post('/balance', _this.balanceBulk)
_this.router.get('/transactions/:address', _this.getTransactions)
}
@@ -423,26 +424,93 @@ class Electrum {
}
}
// Convert a 'bitcoincash:...' address to a script hash used by ElectrumX.
addressToScripthash (addrStr) {
/**
* @api {post} /electrumx/balance Get balances for an array of addresses.
* @apiName Balances for an array of addresses
* @apiGroup ElectrumX / Fulcrum
* @apiDescription Returns an array of balanes associated with an array of address.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/electrumx/balance" -H "accept: application/json" -H "Content-Type: application/json" -d '{"addresses":["bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf","bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"]}'
*
*
*/
// POST handler for bulk queries on address balance
async balanceBulk (req, res, next) {
try {
// console.log(`addrStr: ${addrStr}`)
let addresses = req.body.addresses
const address = _this.bitcore.Address.fromString(addrStr)
// console.log(`address: ${address}`)
// Reject if addresses is not an array.
if (!Array.isArray(addresses)) {
res.status(400)
return res.json({
error: 'addresses needs to be an array. Use GET for single address.'
})
}
const script = _this.bitcore.Script.buildPublicKeyHashOut(address)
// console.log(`script: ${script}`)
// Enforce array size rate limits
if (!_this.routeUtils.validateArraySize(req, addresses)) {
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: 'Array too large.'
})
}
const scripthash = _this.bitcore.crypto.Hash.sha256(script.toBuffer())
.reverse()
.toString('hex')
// console.log(`scripthash: ${scripthash}`)
wlogger.debug(
'Executing electrumx.js/balanceBulk with these addresses: ',
addresses
)
return scripthash
// Validate each element in the address array.
for (let i = 0; i < addresses.length; i++) {
const thisAddress = addresses[i]
// Ensure the input is a valid BCH address.
try {
_this.bchjs.Address.toLegacyAddress(thisAddress)
} catch (err) {
res.status(400)
return res.json({
error: `Invalid BCH address. Double check your address is valid: ${thisAddress}`
})
}
// Prevent a common user error. Ensure they are using the correct network address.
const networkIsValid = _this.routeUtils.validateNetwork(thisAddress)
if (!networkIsValid) {
res.status(400)
return res.json({
error: `Invalid network for address ${thisAddress}. Trying to use a testnet address on mainnet, or vice versa.`
})
}
}
// Loops through each address and creates an array of Promises, querying
// ElectrumX API in parallel.
addresses = addresses.map(async (address, index) => {
// console.log(`address: ${address}`)
const balance = await _this._balanceFromElectrumx(address)
return {
balance,
address
}
})
// Wait for all parallel Insight requests to return.
const result = await Promise.all(addresses)
// Return the array of retrieved address information.
res.status(200)
return res.json({
success: true,
balances: result
})
} catch (err) {
wlogger.error('Error in electrumx.js/addressToScripthash()')
throw err
wlogger.error('Error in electrumx.js/balanceBulk().', err)
return _this.errorHandler(err, res)
}
}
@@ -548,6 +616,29 @@ class Electrum {
return _this.errorHandler(err, res)
}
}
// Convert a 'bitcoincash:...' address to a script hash used by ElectrumX.
addressToScripthash (addrStr) {
try {
// console.log(`addrStr: ${addrStr}`)
const address = _this.bitcore.Address.fromString(addrStr)
// console.log(`address: ${address}`)
const script = _this.bitcore.Script.buildPublicKeyHashOut(address)
// console.log(`script: ${script}`)
const scripthash = _this.bitcore.crypto.Hash.sha256(script.toBuffer())
.reverse()
.toString('hex')
// console.log(`scripthash: ${scripthash}`)
return scripthash
} catch (err) {
wlogger.error('Error in electrumx.js/addressToScripthash()')
throw err
}
}
}
module.exports = Electrum
+130
View File
@@ -579,6 +579,136 @@ describe('#ElectrumX Router', () => {
})
})
describe('#balanceBulk', () => {
it('should throw an error for an empty body', async () => {
req.body = {}
const result = await electrumxRoute.balanceBulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'addresses needs to be an array',
'Proper error message'
)
})
it('should error on non-array single address', async () => {
req.body = {
address: 'qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'
}
const result = await electrumxRoute.balanceBulk(req, res)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'addresses needs to be an array',
'Proper error message'
)
})
it('should throw an error for an invalid address', async () => {
req.body = {
addresses: ['02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c']
}
const result = await electrumxRoute.balanceBulk(req, res)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(
result.error,
'Invalid BCH address',
'Proper error message'
)
})
it('should throw 400 error if addresses array is too large', async () => {
const testArray = []
for (var i = 0; i < 25; i++) testArray.push('')
req.body.addresses = testArray
const result = await electrumxRoute.balanceBulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'Array too large')
})
it('should detect a network mismatch', async () => {
req.body = {
addresses: ['bchtest:qq89kjkeqz9mngp8kl3dpmu43y2wztdjqu500gn4c4']
}
const result = await electrumxRoute.balanceBulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 400, 'HTTP status code 400 expected.')
assert.include(result.error, 'Invalid network', 'Proper error message')
})
it('should get details for a single address', async () => {
req.body = {
addresses: ['bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7']
}
// Mock the Insight URL for unit tests.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox
.stub(electrumxRoute, '_balanceFromElectrumx')
.resolves(mockData.balance)
}
// Call the details API.
const result = await electrumxRoute.balanceBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'balances')
assert.isArray(result.balances)
assert.property(result.balances[0], 'address')
assert.property(result.balances[0], 'balance')
assert.property(result.balances[0].balance, 'confirmed')
assert.property(result.balances[0].balance, 'unconfirmed')
})
it('should get utxos for multiple addresses', async () => {
req.body = {
addresses: [
'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf',
'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
]
}
// Mock the Insight URL for unit tests.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox
.stub(electrumxRoute, '_balanceFromElectrumx')
.resolves(mockData.balance)
}
// Call the details API.
const result = await electrumxRoute.balanceBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.isArray(result.balances)
assert.equal(result.balances.length, 2, '2 outputs for 2 inputs')
})
})
describe('#_transactionsFromElectrumx', () => {
it('should throw error for invalid address', async () => {
try {