Compare commits

..
4 Commits
Author SHA1 Message Date
Chris Troutner 20cb48caff Merge pull request #145 from Permissionless-Software-Foundation/dh-v5-fulcrum-transactions
feat(txs): Created v5 Fulcrum /transactions endpoints in bch-api
2021-06-05 08:35:26 -07:00
Daniel Gonzalez f241aed5b2 feat(txs): Created v5 Fulcrum /transactions endpoints in bch-api 2021-06-04 21:43:45 -04:00
Chris Troutner 87c2faa6af Merge pull request #144 from Permissionless-Software-Foundation/dh-v5-fulcrum-block
feat(block): Created v5 Fulcrum /block endpoints in bch-api
2021-06-04 08:07:05 -07:00
Daniel Gonzalez 10a840f48d feat(block): Created v5 Fulcrum /block endpoints in bch-api 2021-06-02 23:43:25 -04:00
3 changed files with 719 additions and 261 deletions
+200 -245
View File
@@ -55,10 +55,10 @@ class Electrum {
this.router.get('/tx/data/:txid', this.getTransactionDetails) this.router.get('/tx/data/:txid', this.getTransactionDetails)
this.router.post('/tx/data', this.transactionDetailsBulk) this.router.post('/tx/data', this.transactionDetailsBulk)
this.router.post('/tx/broadcast', this.broadcastTransaction) this.router.post('/tx/broadcast', this.broadcastTransaction)
// this.router.get('/block/headers/:height', this.getBlockHeaders) this.router.get('/block/headers/:height', this.getBlockHeaders)
// this.router.post('/block/headers', this.blockHeadersBulk) this.router.post('/block/headers', this.blockHeadersBulk)
// this.router.get('/transactions/:address', this.getTransactions) this.router.get('/transactions/:address', this.getTransactions)
// this.router.post('/transactions', this.transactionsBulk) this.router.post('/transactions', this.transactionsBulk)
// this.router.get('/unconfirmed/:address', this.getMempool) // this.router.get('/unconfirmed/:address', this.getMempool)
// this.router.post('/unconfirmed', this.mempoolBulk) // this.router.post('/unconfirmed', this.mempoolBulk)
@@ -633,63 +633,51 @@ class Electrum {
* *
* *
* @apiExample Example usage: * @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v5/electrumx/block/header/42?count=2" -H "accept: application/json" * curl -X GET "https://api.fullstack.cash/v5/electrumx/block/headers/42?count=2" -H "accept: application/json"
* *
*/ */
// GET handler for single block headers // GET handler for single block headers
// async getBlockHeaders (req, res, next) { async getBlockHeaders (req, res, next) {
// try { try {
// const height = Number(req.params.height) const height = Number(req.params.height)
// const count = req.query.count === undefined ? 1 : Number(req.query.count) const count = req.query.count === undefined ? 1 : Number(req.query.count)
//
// // Reject if height is not a number // Reject if height is not a number
// if (Number.isNaN(height) || height < 0) { if (Number.isNaN(height) || height < 0) {
// res.status(400) res.status(400)
// return res.json({ return res.json({
// success: false, success: false,
// error: 'height must be a positive number' error: 'height must be a positive number'
// }) })
// } }
//
// // Reject if height is not a number // Reject if height is not a number
// if (Number.isNaN(count) || count < 0) { if (Number.isNaN(count) || count < 0) {
// res.status(400) res.status(400)
// return res.json({ return res.json({
// success: false, success: false,
// error: 'count must be a positive number' error: 'count must be a positive number'
// }) })
// } }
//
// wlogger.debug( wlogger.debug(
// 'Executing electrumx/getBlockHeaders with this height: ', 'Executing electrumx/getBlockHeaders with this height: ',
// height height
// ) )
//
// // Get data from ElectrumX server. const response = await _this.axios.get(
// const electrumResponse = await _this._blockHeadersFromElectrum(height, count) `${_this.fulcrumApi}electrumx/block/headers/${height}?count=${count}`
// // console.log(`_transactionDetailsFromElectrum(): ${JSON.stringify(electrumResponse, null, 2)}`) )
//
// // Pass the error message if ElectrumX reports an error. res.status(200)
// if (electrumResponse instanceof Error) { return res.json(response.data)
// res.status(400) } catch (err) {
// return res.json({ // Write out error to error log.
// success: false, wlogger.error('Error in elecrumx.js/getBlockHeader().', err)
// error: electrumResponse.message
// }) return _this.errorHandler(err, res)
// } }
// }
// res.status(200)
// return res.json({
// success: true,
// headers: electrumResponse
// })
// } catch (err) {
// // Write out error to error log.
// wlogger.error('Error in elecrumx.js/getBlockHeader().', err)
//
// return _this.errorHandler(err, res)
// }
// }
/** /**
* @api {post} /electrumx/block/headers Get block headers for an array of height + count pairs * @api {post} /electrumx/block/headers Get block headers for an array of height + count pairs
@@ -699,63 +687,50 @@ class Electrum {
* Limited to 20 items per request. * Limited to 20 items per request.
* *
* @apiExample Example usage: * @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v5/electrumx/block/headers" -H "accept: application/json" -H "Content-Type: application/json" -d '{"heights":[{ "height": 42, count: 2 }, { "height": 100, count: 5 }]}' * curl -X POST "https://api.fullstack.cash/v5/electrumx/block/headers" -H "accept: application/json" -H "Content-Type: application/json" -d '{"heights":[{ "height": 42, "count": 2 }, { "height": 100, "count": 5 }]}'
* *
*/ */
// POST handler for bulk queries on block headers // POST handler for bulk queries on block headers
// async blockHeadersBulk (req, res, next) { async blockHeadersBulk (req, res, next) {
// try { try {
// const heights = req.body.heights const heights = req.body.heights
//
// // Reject if heights is not an array. // Reject if heights is not an array.
// if (!Array.isArray(heights)) { if (!Array.isArray(heights)) {
// res.status(400) res.status(400)
// return res.json({ return res.json({
// success: false, success: false,
// error: 'heights needs to be an array. Use GET for single height.' error: 'heights needs to be an array. Use GET for single height.'
// }) })
// } }
//
// // Enforce array size rate limits // Enforce array size rate limits
// if (!_this.routeUtils.validateArraySize(req, heights)) { if (!_this.routeUtils.validateArraySize(req, heights)) {
// res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330 res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
// return res.json({ return res.json({
// success: false, success: false,
// error: 'Array too large.' error: 'Array too large.'
// }) })
// } }
//
// wlogger.debug( wlogger.debug(
// 'Executing electrumx.js/blockHeadersBulk with these txids: ', 'Executing electrumx.js/blockHeadersBulk with these txids: ',
// heights heights
// ) )
//
// // Loops through each address and creates an array of Promises, querying const response = await _this.axios.post(
// // the Electrum server in parallel. `${_this.fulcrumApi}electrumx/block/headers`,
// const transactions = heights.map(async (obj) => { { heights }
// const headers = await _this._blockHeadersFromElectrum( )
// obj.height,
// obj.count res.status(200)
// ) return res.json(response.data)
// } catch (err) {
// return { headers } wlogger.error('Error in electrumx.js/blockHeadersBulk().', err)
// })
// return _this.errorHandler(err, res)
// // Wait for all parallel Electrum requests to return. }
// const result = await Promise.all(transactions) }
//
// // Return the array of retrieved transaction details.
// res.status(200)
// return res.json({
// success: true,
// headers: result
// })
// } catch (err) {
// wlogger.error('Error in electrumx.js/blockHeadersBulk().', err)
//
// return _this.errorHandler(err, res)
// }
// }
// Returns a promise that resolves an array of transaction history for an // 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 // address. Expects input to be a cash address, and input validation to have
@@ -802,63 +777,53 @@ class Electrum {
* *
*/ */
// GET handler for single balance // GET handler for single balance
// async getTransactions (req, res, next) { async getTransactions (req, res, next) {
// try { try {
// const address = req.params.address const address = req.params.address
//
// // 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, 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.'
// }) })
// } }
//
// // Ensure the address is in cash address format. // Ensure the address is in cash address format.
// const cashAddr = _this.bchjs.Address.toCashAddress(address) const cashAddr = _this.bchjs.Address.toCashAddress(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(cashAddr) const networkIsValid = _this.routeUtils.validateNetwork(cashAddr)
// if (!networkIsValid) { if (!networkIsValid) {
// res.status(400) res.status(400)
// return res.json({ return res.json({
// success: false, 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.'
// }) })
// } }
//
// wlogger.debug( wlogger.debug(
// 'Executing electrumx/getTransactions with this address: ', 'Executing electrumx/getTransactions with this address: ',
// cashAddr cashAddr
// ) )
//
// // Get data from ElectrumX server. // Get data from ElectrumX server.
// const electrumResponse = await _this._transactionsFromElectrumx(cashAddr) const response = await _this.axios.get(
// // console.log(`_utxosFromElectrumx(): ${JSON.stringify(electrumResponse, null, 2)}`) `${_this.fulcrumApi}electrumx/transactions/${address}`
// )
// // Pass the error message if ElectrumX reports an error. // console.log('response', response, _this.fulcrumApi)
// if (Object.prototype.hasOwnProperty.call(electrumResponse, 'code')) {
// res.status(400) res.status(200)
// return res.json({ return res.json(response.data)
// success: false, } catch (err) {
// message: electrumResponse.message // Write out error to error log.
// }) wlogger.error('Error in elecrumx.js/getTransactions().', err)
// }
// return _this.errorHandler(err, res)
// res.status(200) }
// return res.json({ }
// success: true,
// transactions: electrumResponse
// })
// } catch (err) {
// // Write out error to error log.
// wlogger.error('Error in elecrumx.js/getTransactions().', err)
//
// return _this.errorHandler(err, res)
// }
// }
/** /**
* @api {post} /electrumx/transactions Get the transaction history for an array of addresses. * @api {post} /electrumx/transactions Get the transaction history for an array of addresses.
@@ -873,82 +838,72 @@ class Electrum {
* *
*/ */
// POST handler for bulk queries on transaction histories for addresses. // POST handler for bulk queries on transaction histories for addresses.
// async transactionsBulk (req, res, next) { async transactionsBulk (req, res, next) {
// try { try {
// let addresses = req.body.addresses const addresses = req.body.addresses
//
// // Reject if addresses is not an array. // Reject if addresses is not an array.
// if (!Array.isArray(addresses)) { if (!Array.isArray(addresses)) {
// res.status(400) res.status(400)
// return res.json({ return res.json({
// error: 'addresses needs to be an array. Use GET for single address.' success: false,
// }) error: 'addresses needs to be an array. Use GET for single address.'
// } })
// }
// // Enforce array size rate limits
// if (!_this.routeUtils.validateArraySize(req, addresses)) { // Enforce array size rate limits
// res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330 if (!_this.routeUtils.validateArraySize(req, addresses)) {
// return res.json({ res.status(400) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
// error: 'Array too large.' return res.json({
// }) success: false,
// } error: 'Array too large.'
// })
// wlogger.debug( }
// 'Executing electrumx.js/transactionsBulk with these addresses: ',
// addresses wlogger.debug(
// ) 'Executing electrumx.js/transactionsBulk with these addresses: ',
// addresses
// // Validate each element in the address array. )
// for (let i = 0; i < addresses.length; i++) {
// const thisAddress = addresses[i] // Validate each element in the address array.
// for (let i = 0; i < addresses.length; i++) {
// // Ensure the input is a valid BCH address. const thisAddress = addresses[i]
// try {
// _this.bchjs.Address.toLegacyAddress(thisAddress) // Ensure the input is a valid BCH address.
// } catch (err) { try {
// res.status(400) _this.bchjs.Address.toLegacyAddress(thisAddress)
// return res.json({ } catch (err) {
// error: `Invalid BCH address. Double check your address is valid: ${thisAddress}` res.status(400)
// }) return res.json({
// } success: false,
// 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) // Prevent a common user error. Ensure they are using the correct network address.
// return res.json({ const networkIsValid = _this.routeUtils.validateNetwork(thisAddress)
// error: `Invalid network for address ${thisAddress}. Trying to use a testnet address on mainnet, or vice versa.` if (!networkIsValid) {
// }) res.status(400)
// } return res.json({
// } success: false,
// 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 transactions = await _this._transactionsFromElectrumx(address) const response = await _this.axios.post(
// `${_this.fulcrumApi}electrumx/transactions/`,
// return { { addresses }
// transactions, )
// address
// } res.status(200)
// }) return res.json(response.data)
// } catch (err) {
// // Wait for all parallel Insight requests to return. wlogger.error('Error in electrumx.js/transactionsBulk().', err)
// const result = await Promise.all(addresses)
// return _this.errorHandler(err, res)
// // Return the array of retrieved address information. }
// res.status(200) }
// return res.json({
// success: true,
// transactions: result
// })
// } catch (err) {
// wlogger.error('Error in electrumx.js/transactionsBulk().', err)
//
// return _this.errorHandler(err, res)
// }
// }
// Returns a promise that resolves to unconfirmed UTXO data (mempool) for an address. // Returns a promise that resolves to unconfirmed UTXO data (mempool) for an address.
// Expects input to be a cash address, and input validation to have // Expects input to be a cash address, and input validation to have
+486 -15
View File
@@ -752,22 +752,7 @@ describe('#Electrumx', () => {
assert.property(result, 'error') assert.property(result, 'error')
assert.include(result.error, 'Test error') assert.include(result.error, 'Test error')
}) })
/* it('should pass errors from electrum-cash to user', async () => {
req.body.txids = [
'02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c',
'02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'
]
// Call the details API.
const result = await electrumxRoute.transactionDetailsBulk(req, res)
console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Test error')
}) */
it('should get details for an array of tx', async () => { it('should get details for an array of tx', async () => {
req.body.txids = [ req.body.txids = [
'a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d' 'a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d'
@@ -877,6 +862,492 @@ describe('#Electrumx', () => {
}) })
}) })
describe('#getBlockHeaders', () => {
it('should throw 400 if height is empty', async () => {
const result = await electrumxRoute.getBlockHeaders(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, 'height must be a positive number')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 if height is not a number', async () => {
req.params.height = 'wrong type'
const result = await electrumxRoute.getBlockHeaders(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, 'height must be a positive number')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 if height is negative', async () => {
req.params.height = -1
const result = await electrumxRoute.getBlockHeaders(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, 'height must be a positive number')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 if count is not a number', async () => {
req.params.height = 2
req.query.count = 'wrong type'
const result = await electrumxRoute.getBlockHeaders(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, 'count must be a positive number')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 if count is negative', async () => {
req.params.height = 2
req.query.count = -1
const result = await electrumxRoute.getBlockHeaders(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, 'count must be a positive number')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should pass errors from electrum-cash to user', async () => {
req.params.height = 99999999999999
req.query.count = 99999999999999
// Mock unit tests to prevent live network calls.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox.stub(electrumxRoute.axios, 'get').resolves({
data: { success: false, error: { error: 'Invalid height' } }
})
}
// Call the details API.
const result = await electrumxRoute.getBlockHeaders(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error.error, 'Invalid height')
})
it('should handle error', async () => {
req.params.height = 42
req.query.count = 2
// Force error
sandbox.stub(electrumxRoute.axios, 'get').throws(new Error('Test error'))
// Call the details API.
const result = await electrumxRoute.getBlockHeaders(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Test error')
})
it('should get headers for a single block height with count 2', async () => {
req.params.height = 42
req.query.count = 2
// Mock unit tests to prevent live network calls.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox.stub(electrumxRoute.axios, 'get').resolves({
data: { success: true, headers: mockData.blockHeaders }
})
}
// Call the details API.
const result = await electrumxRoute.getBlockHeaders(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'headers')
assert.isArray(result.headers)
assert.deepEqual(result.headers, mockData.blockHeaders)
})
})
describe('#blockHeadersBulk', () => {
it('should throw 400 for an empty body', async () => {
const result = await electrumxRoute.blockHeadersBulk(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, 'heights needs to be an array')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should NOT throw 400 error for an invalid height', async () => {
req.body = {
heights: [{ height: -10, count: 2 }]
}
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox.stub(electrumxRoute.axios, 'post').resolves({
data: { success: true, headers: [{ headers: {} }] }
})
}
const result = await electrumxRoute.blockHeadersBulk(req, res)
console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 200, 'Expect 200 status code')
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'headers')
assert.isArray(result.headers)
assert.property(result.headers[0], 'headers')
})
it('should throw 400 error if heights array is too large', async () => {
const testArray = []
for (var i = 0; i < 25; i++) testArray.push('')
req.body.heights = testArray
const result = await electrumxRoute.blockHeadersBulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.property(result, 'error')
assert.include(result.error, 'Array too large')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should handle error', async () => {
req.body = {
heights: [
{ height: 42, count: 2 },
{ height: 42, count: 2 }
]
}
// Force error
sandbox.stub(electrumxRoute.axios, 'post').throws(new Error('Test error'))
// Call the details API.
const result = await electrumxRoute.blockHeadersBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Test error')
})
it('should get block heights', async () => {
req.body = {
heights: [
{ height: 42, count: 2 },
{ height: 42, count: 2 }
]
}
// Mock unit tests to prevent live network calls.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox
.stub(electrumxRoute.axios, 'post')
.resolves({ data: mockData.blockHeadersBulk })
}
// Call the details API.
const result = await electrumxRoute.blockHeadersBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'headers')
assert.isArray(result.headers)
assert.property(result.headers[0], 'headers')
})
})
describe('#getTransactions', () => {
it('should throw 400 if address is empty', async () => {
const result = await electrumxRoute.getTransactions(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 422, 'Expect 422 status code')
assert.property(result, 'error')
assert.include(result.error, 'Unsupported address format')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 on array input', async () => {
req.params.address = ['qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c']
const result = await electrumxRoute.getTransactions(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, '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.getTransactions(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(res.statusCode, 422, 'Expect 422 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.getTransactions(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 pass errors from electrum-cash to user', async () => {
// Address has invalid checksum.
req.params.address =
'bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur2'
// Call the details API.
const result = await electrumxRoute.getTransactions(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Unsupported address format')
})
it('should get transaction for a single address', async () => {
req.params.address =
'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7'
// Mock unit tests to prevent live network calls.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox.stub(electrumxRoute.axios, 'get').resolves({
data: { success: true, transactions: mockData.transactions }
})
}
// Call the details API.
const result = await electrumxRoute.getTransactions(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'transactions')
assert.isArray(result.transactions)
assert.property(result.transactions[0], 'height')
assert.property(result.transactions[0], 'tx_hash')
})
})
describe('#transactionsBulk', () => {
it('should throw 400 if addresses is empty', async () => {
const result = await electrumxRoute.transactionsBulk(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, 'addresses needs to be an array')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw 400 if input provided is not array', async () => {
req.body.addresses = 'qzs02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c'
const result = await electrumxRoute.transactionsBulk(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, 'addresses needs to be an array')
assert.property(result, 'success')
assert.equal(result.success, false)
})
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.transactionsBulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.property(result, 'error')
assert.include(result.error, 'Array too large')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should throw an error for an invalid address', async () => {
req.body.addresses = ['02v05l7qs5s24srqju498qu55dwuj0cx5ehjm2c']
const result = await electrumxRoute.transactionsBulk(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 BCH address')
assert.property(result, 'success')
assert.equal(result.success, false)
})
it('should detect a network mismatch', async () => {
req.body.addresses = [
'bchtest:qq89kjkeqz9mngp8kl3dpmu43y2wztdjqu500gn4c4'
]
const result = await electrumxRoute.transactionsBulk(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 pass errors from electrum-cash to user', async () => {
// Address has invalid checksum.
req.body.addresses = [
'bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur2'
]
// Call the details API.
const result = await electrumxRoute.transactionsBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Invalid BCH address')
})
it('should handle error', async () => {
req.body.addresses = [
'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
]
// Force error
sandbox.stub(electrumxRoute.axios, 'post').throws(new Error('Test error'))
// Call the details API.
const result = await electrumxRoute.transactionsBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, false)
assert.property(result, 'error')
assert.include(result.error, 'Test error')
})
it('should get transaction for an array of addresses', async () => {
req.body.addresses = [
'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7',
'bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf'
]
// Mock unit tests to prevent live network calls.
if (process.env.TEST === 'unit') {
electrumxRoute.isReady = true // Force flag.
sandbox
.stub(electrumxRoute.axios, 'post')
.resolves({ data: mockData.transactionsBulk })
}
// Call the details API.
const result = await electrumxRoute.transactionsBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'transactions')
assert.isArray(result.transactions)
assert.property(result.transactions[0], 'transactions')
assert.isArray(result.transactions[0].transactions)
assert.property(result.transactions[0].transactions[0], 'height')
assert.property(result.transactions[0].transactions[0], 'tx_hash')
})
})
// describe('#_utxosFromElectrumx', () => { // describe('#_utxosFromElectrumx', () => {
// it('should throw error for invalid address', async () => { // it('should throw error for invalid address', async () => {
// try { // try {
+33 -1
View File
@@ -176,6 +176,35 @@ const blockHeaders = [
'01000000f528fac1bcb685d0cd6c792320af0300a5ce15d687c7149548904e31000000004e8985a786d864f21e9cbb7cbdf4bc9265fe681b7a0893ac55a8e919ce035c2f85de6849ffff001d385ccb7c' '01000000f528fac1bcb685d0cd6c792320af0300a5ce15d687c7149548904e31000000004e8985a786d864f21e9cbb7cbdf4bc9265fe681b7a0893ac55a8e919ce035c2f85de6849ffff001d385ccb7c'
] ]
const blockHeadersBulk = {
success: true,
headers: [{ headers: blockHeaders }, { headers: blockHeaders }]
}
const transactions = [
{
height: 603416,
tx_hash: 'eef683d236d88e978bd406419f144057af3fe1b62ef59162941c1a9f05ded62c'
},
{
height: 646894,
tx_hash: '4c695fae636f3e8e2edc571d11756b880ccaae744390f3950d798ce7b5e25754'
}
]
const transactionsBulk = {
success: true,
transactions: [
{
transactions,
address: 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7'
},
{
transactions,
address: 'bitcoincash:qp3sn6vlwz28ntmf3wmyra7jqttfx7z6zgtkygjhc7'
}
]
}
module.exports = { module.exports = {
utxos, utxos,
utxosArray, utxosArray,
@@ -185,5 +214,8 @@ module.exports = {
txDetails, txDetails,
txDetailsBulk, txDetailsBulk,
blockHeaders, blockHeaders,
balances blockHeadersBulk,
balances,
transactions,
transactionsBulk
} }