fix(bcash): Adding scaffolding for bcash library

This commit is contained in:
Chris Troutner
2021-10-18 05:40:32 -07:00
parent e55d421f13
commit 233e210131
3 changed files with 493 additions and 433 deletions
+94 -30
View File
@@ -2,75 +2,139 @@
Electrum API route
*/
"use strict";
'use strict'
const express = require("express");
const router = express.Router();
const axios = require("axios");
const util = require("util");
const express = require('express')
const router = express.Router()
const axios = require('axios')
const util = require('util')
// const bitcore = require('bitcore-lib-cash')
// const ElectrumCash = require('electrum-cash').ElectrumClient
// const ElectrumCash = require('/home/trout/work/personal/electrum-cash/electrum.js').Client // eslint-disable-line
const wlogger = require("../../../util/winston-logging");
const config = require("../../../../config");
const wlogger = require('../../../util/winston-logging')
const config = require('../../../../config')
const RouteUtils = require("../../../util/route-utils");
const routeUtils = new RouteUtils();
const RouteUtils = require('../../../util/route-utils')
const routeUtils = new RouteUtils()
// const BCHJS = require("@psf/bch-js");
// const bchjs = new BCHJS();
let _this;
let _this
class BcashSlp {
constructor() {
this.config = config;
this.axios = axios;
this.routeUtils = routeUtils;
constructor () {
this.config = config
this.axios = axios
this.routeUtils = routeUtils
// this.bchjs = bchjs;
// _this.bitcore = bitcore
this.bcashServer = process.env.BCASH_SERVER;
this.bcashServer = process.env.BCASH_SERVER
if (!this.bcashServer) {
// console.warn('FULCRUM_API env var not set. Can not connect to Fulcrum indexer.')
throw new Error(
"BCASH_SERVER env var not set. Can not connect to bcash full node."
);
'BCASH_SERVER env var not set. Can not connect to bcash full node.'
)
}
this.router = router;
this.router.get("/", this.root);
this.router = router
this.router.get('/', this.root)
this.router.get('/utxos/:address', this.getUtxos)
}
/**
* @api {get} /bcash/utxos/{addr} Get utxos for a single address.
* @apiName UTXOs for a single address
* @apiGroup bcash
* @apiDescription Returns an object with UTXOs associated with an address.
* This UTXOs will be hydrated with token information.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v5/bcash/utxos/bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3" -H "accept: application/json"
*
*/
// GET handler for single balance
async getUtxos (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.'
})
}
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.'
})
}
// TODO: Customize this function below here for bcash, based on this gist:
// https://gist.github.com/christroutner/dcb25a895900e557d7b43341ee85fa79
wlogger.debug(
'Executing electrumx/getUtxos with this address: ',
cashAddr
)
// Get data from ElectrumX server.
const response = await _this.axios.get(
`${_this.fulcrumApi}electrumx/utxos/${address}`
)
// console.log('response', response, _this.fulcrumApi)
res.status(200)
return res.json(response.data)
} catch (err) {
// Write out error to error log.
wlogger.error('Error in elecrumx.js/getUtxos().', err)
return _this.errorHandler(err, res)
}
}
// DRY error handler.
errorHandler(err, res) {
errorHandler (err, res) {
// Attempt to decode the error message.
const { msg, status } = _this.routeUtils.decodeError(err);
const { msg, status } = _this.routeUtils.decodeError(err)
// console.log('errorHandler msg: ', msg)
// console.log('errorHandler status: ', status)
if (msg) {
res.status(status);
return res.json({ success: false, error: 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 });
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) });
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: "bcash-slp" });
root (req, res, next) {
return res.json({ status: 'bcash-slp' })
}
}
module.exports = BcashSlp;
module.exports = BcashSlp
File diff suppressed because it is too large Load Diff
+44 -48
View File
@@ -2,45 +2,45 @@
TESTS FOR THE bcash/slp.js LIBRARY
*/
"use strict";
'use strict'
const chai = require("chai");
const assert = chai.assert;
const chai = require('chai')
const assert = chai.assert
const sinon = require("sinon");
const sinon = require('sinon')
const BcashSlp = require("../../src/routes/v5/bcash/slp");
const BcashSlp = require('../../src/routes/v5/bcash/slp')
// Mocking data.
const { mockReq, mockRes } = require("./mocks/express-mocks");
const mockData = require("./mocks/electrumx-mock");
const { mockReq, mockRes } = require('./mocks/express-mocks')
// const mockData = require('./mocks/electrumx-mock')
// Used for debugging.
const util = require("util");
util.inspect.defaultOptions = { depth: 1 };
const util = require('util')
util.inspect.defaultOptions = { depth: 1 }
if (!process.env.BCASH_SERVER) process.env.BCASH_SERVER = "http://localhost";
if (!process.env.BCASH_SERVER) process.env.BCASH_SERVER = 'http://localhost'
describe("#bcash-slp", () => {
let req, res;
let sandbox;
const bcashSlp = new BcashSlp();
describe('#bcash-slp', () => {
let req, res
let sandbox
const bcashSlp = new BcashSlp()
// let electrumxRoute
before(async () => {
if (!process.env.TEST) {
process.env.TEST = "unit";
process.env.TEST = 'unit'
}
console.log(`Testing type is: ${process.env.TEST}`);
console.log(`Testing type is: ${process.env.TEST}`)
if (!process.env.NETWORK) process.env.NETWORK = "testnet";
if (!process.env.NETWORK) process.env.NETWORK = 'testnet'
// Connect to electrumx servers if this is an integration test.
// if (process.env.TEST === 'integration') {
// await electrumxRoute.connect()
// console.log('Connected to ElectrumX server')
// }
});
})
after(async () => {
// console.log(`electrumxRoute.electrumx: `, electrumxRoute.electrumx)
@@ -49,51 +49,47 @@ describe("#bcash-slp", () => {
// await electrumxRoute.disconnect()
// console.log('Disconnected from ElectrumX server')
// }
});
})
// Setup the mocks before each test.
beforeEach(() => {
// Mock the req and res objects used by Express routes.
req = mockReq;
res = mockRes;
req = mockReq
res = mockRes
// Explicitly reset the parmas and body.
req.params = {};
req.body = {};
req.query = {};
req.params = {}
req.body = {}
req.query = {}
sandbox = sinon.createSandbox();
sandbox = sinon.createSandbox()
// electrumxRoute = new ElecrumxRoute()
});
})
afterEach(() => {
sandbox.restore();
});
sandbox.restore()
})
after(() => {
//
});
})
// A wrapper for stubbing with the Sinon sandbox.
// function stubMethodForUnitTests (obj, method, value) {
// if (process.env.TEST !== 'unit') return false
//
// electrumxRoute.isReady = true // Force flag.
//
// sandbox.stub(obj, method).resolves(value)
//
// return true
// }
describe("#root", () => {
describe('#root', () => {
// root route handler.
const root = bcashSlp.root;
const root = bcashSlp.root
it("should respond to GET for base route", async () => {
const result = root(req, res);
it('should respond to GET for base route', async () => {
const result = root(req, res)
assert.equal(result.status, "bcash-slp", "Returns static string");
});
});
});
assert.equal(result.status, 'bcash-slp', 'Returns static string')
})
})
describe('#getUtxos', () => {
it('should return UTXOs for an address, hydrated with SLP info', async () => {
// TODO: Add unit tests.
assert.isOk(true)
})
})
})