refactor(libraries): Refactored control, mining and raw transactions

This commit is contained in:
danielhumgon
2020-03-04 20:33:20 -04:00
parent 03a2284b2e
commit 161c31a397
7 changed files with 1236 additions and 946 deletions
+6 -3
View File
@@ -25,10 +25,10 @@ const jwtAuth = require('./middleware/jwt-auth')
// v3
const healthCheckV3 = require('./routes/v3/health-check')
const BlockchainV3 = require('./routes/v3/full-node/blockchain')
const controlV3 = require('./routes/v3/full-node/control')
const miningV3 = require('./routes/v3/full-node/mining')
const ControlV3 = require('./routes/v3/full-node/control')
const MiningV3 = require('./routes/v3/full-node/mining')
const networkV3 = require('./routes/v3/full-node/network')
const rawtransactionsV3 = require('./routes/v3/full-node/rawtransactions')
const RawtransactionsV3 = require('./routes/v3/full-node/rawtransactions')
const utilV3 = require('./routes/v3/util')
const slpV3 = require('./routes/v3/slp')
const xpubV3 = require('./routes/v3/xpub')
@@ -39,6 +39,9 @@ require('dotenv').config()
// Instantiate route libraries.
const blockchainV3 = new BlockchainV3()
const controlV3 = new ControlV3()
const miningV3 = new MiningV3()
const rawtransactionsV3 = new RawtransactionsV3()
const app = express()
+95 -82
View File
@@ -2,101 +2,114 @@
const express = require('express')
const router = express.Router()
// const axios = require('axios')
const routeUtils = require('../route-utils')
const axios = require('axios')
// const routeUtils = require('../route-utils')
const wlogger = require('../../../util/winston-logging')
const RouteUtils = require('../route-utils2')
const routeUtils = new RouteUtils()
// Used for processing error messages before sending them to the user.
const util = require('util')
util.inspect.defaultOptions = { depth: 1 }
router.get('/', root)
router.get('/getnetworkinfo', getNetworkInfo)
let _this
function root (req, res, next) {
return res.json({ status: 'control' })
}
class Control {
constructor () {
_this = this
this.axios = axios
this.routeUtils = routeUtils
/**
* @api {get} /control/getnetworkinfo Get Network Info
* @apiName GetNetworkInfo
* @apiGroup Control
* @apiDescription RPC call which gets basic full node information.
*
* @apiExample Example usage:
* curl -X GET "https://mainnet.bchjs.cash/v3/control/getnetworkinfo" -H "accept: application/json"
*
*/
async function getNetworkInfo (req, res, next) {
const {
BitboxHTTP,
// username,
// password,
requestConfig
} = routeUtils.setEnvVars()
this.router = router
this.router.get('/', this.root)
this.router.get('/getNetworkInfo', this.getNetworkInfo)
}
requestConfig.data.id = 'getnetworkinfo'
requestConfig.data.method = 'getnetworkinfo'
requestConfig.data.params = []
root (req, res, next) {
return res.json({ status: 'control' })
}
try {
const response = await BitboxHTTP(requestConfig)
return res.json(response.data.result)
} catch (error) {
wlogger.error('Error in control.ts/getNetworkInfo().', error)
// Write out error to error log.
// logger.error(`Error in control/getInfo: `, error)
// 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({ error: msg })
}
res.status(500)
if (error.response && error.response.data && error.response.data.error) { return res.json({ error: error.response.data.error }) }
return res.json({ error: util.inspect(error) })
return res.json({ error: util.inspect(err) })
}
/**
* @api {get} /control/getnetworkinfo Get Network Info
* @apiName GetNetworkInfo
* @apiGroup Control
* @apiDescription RPC call which gets basic full node information.
*
* @apiExample Example usage:
* curl -X GET "https://mainnet.bchjs.cash/v3/control/getnetworkinfo" -H "accept: application/json"
*
*/
async getNetworkInfo (req, res, next) {
// Axios options
const options = _this.routeUtils.getAxiosOptions()
options.data.id = 'getnetworkinfo'
options.data.method = 'getnetworkinfo'
options.data.params = []
try {
// const response = await BitboxHTTP(requestConfig)
const response = await this.axios.request(options)
return res.json(response.data.result)
} catch (error) {
wlogger.error('Error in control.ts/getNetworkInfo().', error)
return this.errorHandler(error, res)
}
}
// router.get('/getMemoryInfo', (req, res, next) => {
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"getmemoryinfo",
// method: "getmemoryinfo"
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
//
// router.get('/help', (req, res, next) => {
// BITBOX.Control.help()
// .then((result) => {
// res.json(result);
// }, (err) => { console.log(err);
// });
// });
//
// router.post('/stop', (req, res, next) => {
// BITBOX.Control.stop()
// .then((result) => {
// res.json(result);
// }, (err) => { console.log(err);
// });
// });
}
// router.get('/getMemoryInfo', (req, res, next) => {
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"getmemoryinfo",
// method: "getmemoryinfo"
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
//
// router.get('/help', (req, res, next) => {
// BITBOX.Control.help()
// .then((result) => {
// res.json(result);
// }, (err) => { console.log(err);
// });
// });
//
// router.post('/stop', (req, res, next) => {
// BITBOX.Control.stop()
// .then((result) => {
// res.json(result);
// }, (err) => { console.log(err);
// });
// });
module.exports = {
router,
testableComponents: {
root,
getNetworkInfo
}
}
module.exports = Control
+125 -149
View File
@@ -2,107 +2,102 @@
const express = require('express')
const router = express.Router()
// const axios = require('axios')
const axios = require('axios')
const RouteUtils = require('../route-utils2')
const routeUtils = new RouteUtils()
const routeUtils = require('../route-utils')
const wlogger = require('../../../util/winston-logging')
// Used to convert error messages to strings, to safely pass to users.
const util = require('util')
util.inspect.defaultOptions = { depth: 1 }
// const BitboxHTTP = axios.create({
// baseURL: process.env.RPC_BASEURL
// })
// const username = process.env.RPC_USERNAME
// const password = process.env.RPC_PASSWORD
let _this
class Mining {
constructor () {
_this = this
this.axios = axios
this.routeUtils = routeUtils
// const requestConfig = {
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: '1.0'
// }
// }
this.router = router
this.router.get('/', this.root)
this.router.get('/getMiningInfo', this.getMiningInfo)
this.router.get('/getNetworkHashPS', this.getNetworkHashPS)
}
router.get('/', root)
router.get('/getMiningInfo', getMiningInfo)
router.get('/getNetworkHashps', getNetworkHashPS)
root (req, res, next) {
return res.json({ status: 'mining' })
}
function root (req, res, next) {
return res.json({ status: 'mining' })
}
//
// router.get('/getBlockTemplate/:templateRequest', (req, res, next) => {
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"getblocktemplate",
// method: "getblocktemplate",
// params: [
// req.params.templateRequest
// ]
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
/**
* @api {get} /mining/getMiningInfo Get Mining Info.
* @apiName Mining info.
* @apiGroup Mining
* @apiDescription Returns a json object containing mining-related information.
*
*
* @apiExample Example usage:
* curl -X GET "https://mainnet.bchjs.cash/v3/mining/getMiningInfo" -H "accept: application/json"
*
*
*/
async function getMiningInfo (req, res, next) {
try {
const {
BitboxHTTP,
// username,
// password,
requestConfig
} = routeUtils.setEnvVars()
requestConfig.data.id = 'getmininginfo'
requestConfig.data.method = 'getmininginfo'
requestConfig.data.params = []
const response = await BitboxHTTP(requestConfig)
return res.json(response.data.result)
} catch (err) {
// DRY error handler.
errorHandler (err, res) {
// Attempt to decode the error message.
const { msg, status } = routeUtils.decodeError(err)
const { msg, status } = _this.routeUtils.decodeError(err)
if (msg) {
res.status(status)
return res.json({ error: msg })
}
wlogger.error('Error in mining.ts/getMiningInfo().', err)
res.status(500)
return res.json({ error: util.inspect(err) })
}
}
/**
// router.get('/getBlockTemplate/:templateRequest', (req, res, next) => {
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"getblocktemplate",
// method: "getblocktemplate",
// params: [
// req.params.templateRequest
// ]
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
/**
* @api {get} /mining/getMiningInfo Get Mining Info.
* @apiName Mining info.
* @apiGroup Mining
* @apiDescription Returns a json object containing mining-related information.
*
*
* @apiExample Example usage:
* curl -X GET "https://mainnet.bchjs.cash/v3/mining/getMiningInfo" -H "accept: application/json"
*
*
*/
async getMiningInfo (req, res, next) {
try {
const options = _this.routeUtils.getAxiosOptions()
options.data.id = 'getmininginfo'
options.data.method = 'getmininginfo'
options.data.params = []
const response = await _this.axios.request(options)
return res.json(response.data.result)
} catch (err) {
wlogger.error('Error in mining.ts/getMiningInfo().', err)
return this.errorHandler(err, res)
}
}
/**
* @api {get} /mining/getNetworkHashps?nblocks=&height= Get Estimated network hashes per second.
* @apiName Estimated network hashes per second.
* @apiGroup Mining
@@ -114,78 +109,59 @@ async function getMiningInfo (req, res, next) {
*
*
*/
async function getNetworkHashPS (req, res, next) {
try {
let nblocks = 120 // Default
let height = -1 // Default
if (req.query.nblocks) nblocks = parseInt(req.query.nblocks)
if (req.query.height) height = parseInt(req.query.height)
const {
BitboxHTTP,
// username,
// password,
requestConfig
} = routeUtils.setEnvVars()
async getNetworkHashPS (req, res, next) {
try {
let nblocks = 120 // Default
let height = -1 // Default
if (req.query.nblocks) nblocks = parseInt(req.query.nblocks)
if (req.query.height) height = parseInt(req.query.height)
requestConfig.data.id = 'getnetworkhashps'
requestConfig.data.method = 'getnetworkhashps'
requestConfig.data.params = [nblocks, height]
const options = _this.routeUtils.getAxiosOptions()
const response = await BitboxHTTP(requestConfig)
options.data.id = 'getnetworkhashps'
options.data.method = 'getnetworkhashps'
options.data.params = [nblocks, height]
return res.json(response.data.result)
} catch (err) {
// Attempt to decode the error message.
const { msg, status } = routeUtils.decodeError(err)
if (msg) {
res.status(status)
return res.json({ error: msg })
const response = await this.axios.request(options)
return res.json(response.data.result)
} catch (err) {
wlogger.error('Error in mining.ts/getNetworkHashPS().', err)
return this.errorHandler(err, res)
}
wlogger.error('Error in mining.ts/getNetworkHashPS().', err)
res.status(500)
return res.json({ error: util.inspect(err) })
}
// router.post('/submitBlock/:hex', (req, res, next) => {
// let parameters = '';
// if(req.query.parameters && req.query.parameters !== '') {
// parameters = true;
// }
//
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"submitblock",
// method: "submitblock",
// params: [
// req.params.hex,
// parameters
// ]
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
}
//
// router.post('/submitBlock/:hex', (req, res, next) => {
// let parameters = '';
// if(req.query.parameters && req.query.parameters !== '') {
// parameters = true;
// }
//
// BitboxHTTP({
// method: 'post',
// auth: {
// username: username,
// password: password
// },
// data: {
// jsonrpc: "1.0",
// id:"submitblock",
// method: "submitblock",
// params: [
// req.params.hex,
// parameters
// ]
// }
// })
// .then((response) => {
// res.json(response.data.result);
// })
// .catch((error) => {
// res.send(error.response.data.error.message);
// });
// });
module.exports = {
router,
testableComponents: {
root,
getMiningInfo,
getNetworkHashPS
}
}
module.exports = Mining
File diff suppressed because it is too large Load Diff
+44 -22
View File
@@ -11,8 +11,9 @@
const chai = require('chai')
const assert = chai.assert
const controlRoute = require('../../src/routes/v3/full-node/control')
const nock = require('nock') // HTTP mocking
const ControlRoute = require('../../src/routes/v3/full-node/control')
const uut = new ControlRoute()
const sinon = require('sinon')
let originalEnvVars // Used during transition from integration to unit tests.
@@ -26,6 +27,7 @@ util.inspect.defaultOptions = { depth: 1 }
describe('#ControlRouter', () => {
let req, res
let sandbox
before(() => {
// Save existing environment variables.
@@ -37,13 +39,6 @@ describe('#ControlRouter', () => {
}
// Set default environment variables for unit tests.
if (!process.env.TEST) process.env.TEST = 'unit'
if (process.env.TEST === 'unit') {
process.env.BITCOINCOM_BASEURL = 'http://fakeurl/api/'
process.env.RPC_BASEURL = 'http://fakeurl/api'
process.env.RPC_USERNAME = 'fakeusername'
process.env.RPC_PASSWORD = 'fakepassword'
}
})
// Setup the mocks before each test.
@@ -57,14 +52,12 @@ describe('#ControlRouter', () => {
req.body = {}
req.query = {}
// Activate nock if it's inactive.
if (!nock.isActive()) nock.activate()
sandbox = sinon.createSandbox()
})
afterEach(() => {
// Clean up HTTP mocks.
nock.cleanAll() // clear interceptor list.
nock.restore()
// Restore Sandbox
sandbox.restore()
})
after(() => {
@@ -77,10 +70,10 @@ describe('#ControlRouter', () => {
describe('#root', async () => {
// root route handler.
const root = controlRoute.testableComponents.root
// const root = controlRoute.testableComponents.root
it('should respond to GET for base route', async () => {
const result = root(req, res)
const result = uut.root(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(result.status, 'control', 'Returns static string')
@@ -88,7 +81,7 @@ describe('#ControlRouter', () => {
})
describe('#GetNetworkInfo', () => {
const getNetworkInfo = controlRoute.testableComponents.getNetworkInfo
// const getNetworkInfo = controlRoute.testableComponents.getNetworkInfo
it('should throw 500 when network issues', async () => {
// Save the existing RPC URL.
@@ -97,7 +90,7 @@ describe('#ControlRouter', () => {
// Manipulate the URL to cause a 500 network error.
process.env.RPC_BASEURL = 'http://fakeurl/api/'
await getNetworkInfo(req, res)
await uut.getNetworkInfo(req, res)
// console.log(`result: ${util.inspect(result)}`)
// Restore the saved URL.
@@ -110,16 +103,45 @@ describe('#ControlRouter', () => {
)
// assert.include(result.error, "ENOTFOUND", "Error message expected")
})
it('returns proper error when downstream service stalls', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
const result = await uut.getNetworkInfo(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('returns proper error when downstream service is down', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNREFUSED' })
const result = await uut.getNetworkInfo(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('should get info on the full node', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
nock(`${process.env.RPC_BASEURL}`)
.post(uri => uri.includes('/'))
.reply(200, { result: mockData.mockGetNetworkInfo })
sandbox
.stub(uut.axios, 'request')
.resolves({ data: { result: mockData.mockGetNetworkInfo } })
}
const result = await getNetworkInfo(req, res)
const result = await uut.getNetworkInfo(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAnyKeys(result, [
+78 -25
View File
@@ -10,8 +10,11 @@
const chai = require('chai')
const assert = chai.assert
const miningRoute = require('../../src/routes/v3/full-node/mining')
const nock = require('nock') // HTTP mocking
const MiningRoute = require('../../src/routes/v3/full-node/mining')
const uut = new MiningRoute()
// const nock = require('nock') // HTTP mocking
const sinon = require('sinon')
let originalEnvVars // Used during transition from integration to unit tests.
@@ -25,7 +28,7 @@ util.inspect.defaultOptions = { depth: 1 }
describe('#Mining', () => {
let req, res
let sandbox
before(() => {
// Save existing environment variables.
originalEnvVars = {
@@ -56,14 +59,12 @@ describe('#Mining', () => {
req.body = {}
req.query = {}
// Activate nock if it's inactive.
if (!nock.isActive()) nock.activate()
sandbox = sinon.createSandbox()
})
afterEach(() => {
// Clean up HTTP mocks.
nock.cleanAll() // clear interceptor list.
nock.restore()
// Restore Sandbox
sandbox.restore()
})
after(() => {
@@ -76,10 +77,8 @@ describe('#Mining', () => {
describe('#root', async () => {
// root route handler.
const root = miningRoute.testableComponents.root
it('should respond to GET for base route', async () => {
const result = root(req, res)
const result = uut.root(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.equal(result.status, 'mining', 'Returns static string')
@@ -87,8 +86,6 @@ describe('#Mining', () => {
})
describe('#getMiningInfo', async () => {
const getMiningInfo = miningRoute.testableComponents.getMiningInfo
it('should throw 503 when network issues', async () => {
// Save the existing RPC URL.
const savedUrl2 = process.env.RPC_BASEURL
@@ -96,7 +93,7 @@ describe('#Mining', () => {
// Manipulate the URL to cause a 500 network error.
process.env.RPC_BASEURL = 'http://fakeurl/api/'
await getMiningInfo(req, res)
await uut.getMiningInfo(req, res)
// console.log(`result: ${util.inspect(result)}`)
// Restore the saved URL.
@@ -109,16 +106,45 @@ describe('#Mining', () => {
)
// assert.include(result.error,"Network error: Could not communicate with full node","Error message expected")
})
it('returns proper error when downstream service stalls', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
const result = await uut.getMiningInfo(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('returns proper error when downstream service is down', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNREFUSED' })
const result = await uut.getMiningInfo(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('should GET mining information', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
nock(`${process.env.RPC_BASEURL}`)
.post(uri => uri.includes('/'))
.reply(200, { result: mockData.mockMiningInfo })
sandbox
.stub(uut.axios, 'request')
.resolves({ data: { result: mockData.mockMiningInfo } })
}
const result = await getMiningInfo(req, res)
const result = await uut.getMiningInfo(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, [
@@ -136,8 +162,6 @@ describe('#Mining', () => {
})
describe('#getNetworkHashPS', async () => {
const getNetworkHashPS = miningRoute.testableComponents.getNetworkHashPS
it('should throw 503 when network issues', async () => {
// Save the existing RPC URL.
const savedUrl2 = process.env.RPC_BASEURL
@@ -145,7 +169,7 @@ describe('#Mining', () => {
// Manipulate the URL to cause a 500 network error.
process.env.RPC_BASEURL = 'http://fakeurl/api/'
await getNetworkHashPS(req, res)
await uut.getNetworkHashPS(req, res)
// console.log(`result: ${util.inspect(result)}`)
// Restore the saved URL.
@@ -158,16 +182,45 @@ describe('#Mining', () => {
)
// assert.include(result.error,"Network error: Could not communicate with full node","Error message expected")
})
it('returns proper error when downstream service stalls', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
const result = await uut.getNetworkHashPS(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('returns proper error when downstream service is down', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNREFUSED' })
const result = await uut.getNetworkHashPS(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
)
})
it('should GET Network Hash per second', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
nock(`${process.env.RPC_BASEURL}`)
.post(uri => uri.includes('/'))
.reply(200, { result: 517604755.6648782 })
sandbox
.stub(uut.axios, 'request')
.resolves({ data: { result: 517604755.6648782 } })
}
const result = await getNetworkHashPS(req, res)
const result = await uut.getNetworkHashPS(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isNumber(result)
File diff suppressed because it is too large Load Diff