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