mirror of
https://github.com/fullstack-cash/bch-api.git
synced 2026-09-21 16:52:04 -07:00
fix(v5 electrumx): Added first unit and integration tests for new electrumx route
This commit is contained in:
+163
-297
@@ -34,6 +34,8 @@ class Electrum {
|
||||
_this.bchjs = bchjs
|
||||
// _this.bitcore = bitcore
|
||||
|
||||
_this.fulcrumApi = 'http://fulcrum-api.fullstackbch.nl/v1/'
|
||||
|
||||
// _this.electrumx = new ElectrumCash(
|
||||
// 'bch-api',
|
||||
// '1.4.1',
|
||||
@@ -48,6 +50,8 @@ class Electrum {
|
||||
|
||||
_this.router = router
|
||||
_this.router.get('/', _this.root)
|
||||
_this.router.get('/balance/:address', _this.getBalance)
|
||||
// _this.router.post('/balance', _this.balanceBulk)
|
||||
// _this.router.get('/utxos/:address', _this.getUtxos)
|
||||
// _this.router.post('/utxos', _this.utxosBulk)
|
||||
// _this.router.get('/tx/data/:txid', _this.getTransactionDetails)
|
||||
@@ -55,105 +59,160 @@ class Electrum {
|
||||
// _this.router.post('/tx/broadcast', _this.broadcastTransaction)
|
||||
// _this.router.get('/block/headers/:height', _this.getBlockHeaders)
|
||||
// _this.router.post('/block/headers', _this.blockHeadersBulk)
|
||||
// _this.router.get('/balance/:address', _this.getBalance)
|
||||
// _this.router.post('/balance', _this.balanceBulk)
|
||||
// _this.router.get('/transactions/:address', _this.getTransactions)
|
||||
// _this.router.post('/transactions', _this.transactionsBulk)
|
||||
// _this.router.get('/unconfirmed/:address', _this.getMempool)
|
||||
// _this.router.post('/unconfirmed', _this.mempoolBulk)
|
||||
}
|
||||
|
||||
// Initializes a connection to electrum servers.
|
||||
// async connect () {
|
||||
/**
|
||||
* @api {get} /electrumx/balance/{addr} Get balance for a single address.
|
||||
* @apiName Balance for a single address
|
||||
* @apiGroup ElectrumX / Fulcrum
|
||||
* @apiDescription Returns an object with confirmed and unconfirmed balance associated with an address.
|
||||
*
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -X GET "https://api.fullstack.cash/v4/electrumx/balance/bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3" -H "accept: application/json"
|
||||
*
|
||||
*/
|
||||
// GET handler for single balance
|
||||
async getBalance (req, res, next) {
|
||||
try {
|
||||
const address = req.params.address
|
||||
|
||||
// Reject if address is an array.
|
||||
if (Array.isArray(address)) {
|
||||
res.status(400)
|
||||
return res.json({
|
||||
success: false,
|
||||
error: 'address can not be an array. Use POST for bulk upload.'
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure the address is in cash address format.
|
||||
const cashAddr = _this.bchjs.Address.toCashAddress(address)
|
||||
|
||||
// Prevent a common user error. Ensure they are using the correct network address.
|
||||
const networkIsValid = _this.routeUtils.validateNetwork(cashAddr)
|
||||
if (!networkIsValid) {
|
||||
res.status(400)
|
||||
return res.json({
|
||||
success: false,
|
||||
error:
|
||||
'Invalid network. Trying to use a testnet address on mainnet, or vice versa.'
|
||||
})
|
||||
}
|
||||
|
||||
wlogger.debug(
|
||||
'Executing electrumx/getBalance with this address: ',
|
||||
cashAddr
|
||||
)
|
||||
|
||||
const response = await this.axios.get(
|
||||
`${this.fulcrumApi}electrumx/balance/${address}`
|
||||
)
|
||||
|
||||
res.status(200)
|
||||
return res.json(response.data)
|
||||
} catch (err) {
|
||||
// Write out error to error log.
|
||||
wlogger.error('Error in elecrumx.js/getBalance().', err)
|
||||
|
||||
return _this.errorHandler(err, res)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @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/v4/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('Attempting to connect to ElectrumX server...')
|
||||
// let addresses = req.body.addresses
|
||||
//
|
||||
// // console.log('_this.electrumx: ', _this.electrumx)
|
||||
// // 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.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// // Return immediately if a connection has already been established.
|
||||
// if (_this.isReady) return true
|
||||
// // Enforce array size rate limits
|
||||
// if (!_this.routeUtils.validateArraySize(req, addresses)) {
|
||||
// res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
|
||||
// return res.json({
|
||||
// error: 'Array too large.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// // Connect to the server.
|
||||
// await _this.electrumx.connect()
|
||||
// wlogger.debug(
|
||||
// 'Executing electrumx.js/balanceBulk with these addresses: ',
|
||||
// addresses
|
||||
// )
|
||||
//
|
||||
// // Set the connection flag.
|
||||
// _this.isReady = true
|
||||
// // Validate each element in the address array.
|
||||
// for (let i = 0; i < addresses.length; i++) {
|
||||
// const thisAddress = addresses[i]
|
||||
//
|
||||
// // Periodically check the connection. If it's not connected, attempt to
|
||||
// // reconnect.
|
||||
// _this.reconnectIntervalHandle = setInterval(async function () {
|
||||
// const status = _this.electrumx.connection.status
|
||||
// // console.log(`Electrumx status: ${status}`)
|
||||
//
|
||||
// // 1 = connected. If we're not connected, attemp to reconnect.
|
||||
// if (status !== 1) {
|
||||
// wlogger.info(`Electrumx not connectes. Status: ${status}`)
|
||||
// wlogger.info('Attempting to reconnect...')
|
||||
// await _this.electrumx.connect()
|
||||
// wlogger.info('...reconnected.')
|
||||
// // 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}`
|
||||
// })
|
||||
// }
|
||||
// }, 30000)
|
||||
//
|
||||
// console.log('...Successfully connected to ElectrumX server.')
|
||||
// // 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.`
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // console.log(`_this.isReady: ${_this.isReady}`)
|
||||
// return _this.isReady
|
||||
// // 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) {
|
||||
// console.log('err: ', err)
|
||||
// wlogger.error('Error in electrumx.js/connect(): ', err)
|
||||
// // throw err
|
||||
// wlogger.error('Error in electrumx.js/balanceBulk().', err)
|
||||
//
|
||||
// return _this.errorHandler(err, res)
|
||||
// }
|
||||
// }
|
||||
|
||||
// Disconnect from the ElectrumX server.
|
||||
// async disconnect () {
|
||||
// try {
|
||||
// // Return immediately if the isReady flag is false.
|
||||
// if (!_this.isReady) return true
|
||||
//
|
||||
// // Disable the reconnect timer.
|
||||
// clearInterval(_this.reconnectIntervalHandle)
|
||||
//
|
||||
// // Disconnect from the server.
|
||||
// await _this.electrumx.disconnect()
|
||||
//
|
||||
// // Clear the isReady flag.
|
||||
// _this.isReady = false
|
||||
//
|
||||
// // Return true to signal that the disconnection happened successfully.
|
||||
// return true
|
||||
// } catch (err) {
|
||||
// // console.log(`err: `, err)
|
||||
// wlogger.error('Error in electrumx.js/disconnect()')
|
||||
// throw err
|
||||
// }
|
||||
// }
|
||||
|
||||
// DRY error handler.
|
||||
errorHandler (err, res) {
|
||||
// Attempt to decode the error message.
|
||||
const { msg, status } = _this.routeUtils.decodeError(err)
|
||||
if (msg) {
|
||||
res.status(status)
|
||||
return res.json({ success: false, 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)
|
||||
return res.json({ error: util.inspect(err) })
|
||||
}
|
||||
|
||||
// Root API endpoint. Simply acknowledges that it exists.
|
||||
root (req, res, next) {
|
||||
return res.json({ status: 'electrumx' })
|
||||
}
|
||||
|
||||
// Returns a promise that resolves to UTXO data for an address. Expects input
|
||||
// to be a cash address, and input validation to have already been done by
|
||||
// parent, calling function.
|
||||
@@ -765,199 +824,6 @@ class Electrum {
|
||||
// }
|
||||
// }
|
||||
|
||||
// Returns a promise that resolves to a balance for an address. Expects input
|
||||
// to be a cash address, and input validation to have already been done by
|
||||
// parent, calling function.
|
||||
// async _balanceFromElectrumx (address) {
|
||||
// try {
|
||||
// // Convert the address to a scripthash.
|
||||
// const scripthash = _this.addressToScripthash(address)
|
||||
//
|
||||
// if (!_this.isReady) {
|
||||
// throw new Error(
|
||||
// 'ElectrumX server connection is not ready. Call await connectToServer() first.'
|
||||
// )
|
||||
// }
|
||||
//
|
||||
// // Query the address balance from the ElectrumX server.
|
||||
// const electrumResponse = await _this.electrumx.request(
|
||||
// 'blockchain.scripthash.get_balance',
|
||||
// scripthash
|
||||
// )
|
||||
// // console.log(
|
||||
// // `electrumResponse: ${JSON.stringify(electrumResponse, null, 2)}`
|
||||
// // )
|
||||
//
|
||||
// return electrumResponse
|
||||
// } catch (err) {
|
||||
// // console.log('err1: ', err)
|
||||
//
|
||||
// // Write out error to error log.
|
||||
// wlogger.error('Error in elecrumx.js/_utxosFromElectrumx(): ', err)
|
||||
// throw err
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* @api {get} /electrumx/balance/{addr} Get balance for a single address.
|
||||
* @apiName Balance for a single address
|
||||
* @apiGroup ElectrumX / Fulcrum
|
||||
* @apiDescription Returns an object with confirmed and unconfirmed balance associated with an address.
|
||||
*
|
||||
*
|
||||
* @apiExample Example usage:
|
||||
* curl -X GET "https://api.fullstack.cash/v4/electrumx/balance/bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3" -H "accept: application/json"
|
||||
*
|
||||
*/
|
||||
// GET handler for single balance
|
||||
// async getBalance (req, res, next) {
|
||||
// try {
|
||||
// const address = req.params.address
|
||||
//
|
||||
// // Reject if address is an array.
|
||||
// if (Array.isArray(address)) {
|
||||
// res.status(400)
|
||||
// return res.json({
|
||||
// success: false,
|
||||
// error: 'address can not be an array. Use POST for bulk upload.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// // Ensure the address is in cash address format.
|
||||
// const cashAddr = _this.bchjs.Address.toCashAddress(address)
|
||||
//
|
||||
// // Prevent a common user error. Ensure they are using the correct network address.
|
||||
// const networkIsValid = _this.routeUtils.validateNetwork(cashAddr)
|
||||
// if (!networkIsValid) {
|
||||
// res.status(400)
|
||||
// return res.json({
|
||||
// success: false,
|
||||
// error:
|
||||
// 'Invalid network. Trying to use a testnet address on mainnet, or vice versa.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// wlogger.debug(
|
||||
// 'Executing electrumx/getBalance with this address: ',
|
||||
// cashAddr
|
||||
// )
|
||||
//
|
||||
// // Get data from ElectrumX server.
|
||||
// const electrumResponse = await _this._balanceFromElectrumx(cashAddr)
|
||||
// // console.log(`_utxosFromElectrumx(): ${JSON.stringify(electrumResponse, null, 2)}`)
|
||||
//
|
||||
// // Pass the error message if ElectrumX reports an error.
|
||||
// if (Object.prototype.hasOwnProperty.call(electrumResponse, 'code')) {
|
||||
// res.status(400)
|
||||
// return res.json({
|
||||
// success: false,
|
||||
// message: electrumResponse.message
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// res.status(200)
|
||||
// return res.json({
|
||||
// success: true,
|
||||
// balance: electrumResponse
|
||||
// })
|
||||
// } catch (err) {
|
||||
// // Write out error to error log.
|
||||
// wlogger.error('Error in elecrumx.js/getBalance().', err)
|
||||
//
|
||||
// return _this.errorHandler(err, res)
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* @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/v4/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 {
|
||||
// let addresses = req.body.addresses
|
||||
//
|
||||
// // 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.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// // Enforce array size rate limits
|
||||
// if (!_this.routeUtils.validateArraySize(req, addresses)) {
|
||||
// res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
|
||||
// return res.json({
|
||||
// error: 'Array too large.'
|
||||
// })
|
||||
// }
|
||||
//
|
||||
// wlogger.debug(
|
||||
// 'Executing electrumx.js/balanceBulk with these addresses: ',
|
||||
// addresses
|
||||
// )
|
||||
//
|
||||
// // 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/balanceBulk().', err)
|
||||
//
|
||||
// return _this.errorHandler(err, res)
|
||||
// }
|
||||
// }
|
||||
|
||||
// Returns a promise that resolves an array of transaction history for an
|
||||
// address. Expects input to be a cash address, and input validation to have
|
||||
// already been done by parent, calling function.
|
||||
@@ -1344,30 +1210,30 @@ class Electrum {
|
||||
// }
|
||||
// }
|
||||
|
||||
// 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 = address.isPayToPublicKeyHash()
|
||||
// ? _this.bitcore.Script.buildPublicKeyHashOut(address)
|
||||
// : _this.bitcore.Script.buildScriptHashOut(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
|
||||
// }
|
||||
// }
|
||||
// DRY error handler.
|
||||
errorHandler (err, res) {
|
||||
// Attempt to decode the error message.
|
||||
const { msg, status } = _this.routeUtils.decodeError(err)
|
||||
if (msg) {
|
||||
res.status(status)
|
||||
return res.json({ success: false, 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)
|
||||
return res.json({ error: util.inspect(err) })
|
||||
}
|
||||
|
||||
// Root API endpoint. Simply acknowledges that it exists.
|
||||
root (req, res, next) {
|
||||
return res.json({ status: 'electrumx' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Electrum
|
||||
|
||||
Reference in New Issue
Block a user