Compare commits

...
53 Commits
Author SHA1 Message Date
Chris Troutner 4ec36358ad Merge pull request #72 from Permissionless-Software-Foundation/ct-unstable
Big change in SLP validate output
2020-12-05 17:50:51 -08:00
Chris Troutner 19b40c54e7 feat(validateSingle): Returning null instead of false as default return value 2020-12-05 17:47:46 -08:00
Chris Troutner 3e09b63a55 Added unit test for validateBulk() 2020-12-05 17:19:14 -08:00
Chris Troutner 9580a30ba5 feat(validateBulk): Changed output. Passing true, null, and false values 2020-12-05 16:55:21 -08:00
Chris Troutner af47a3a37f Merge pull request #71 from Permissionless-Software-Foundation/ct-unstable
SLPDB Whitelist Validate
2020-12-05 11:04:35 -08:00
Chris Troutner d61ea0831a Testing new validation calls against BCHN and BCHA 2020-12-05 11:02:44 -08:00
Chris Troutner f2c0cd6feb feat(validate3Bulk): Adding bulk SLP tx validtion for whitelist endpoint 2020-12-05 09:48:05 -08:00
Chris Troutner d93d20321d feat(validate3Single): Adding third SLP validation option using whitelist server 2020-12-05 09:31:38 -08:00
Chris Troutner ff1c37ddb6 fix(validateSingle): Added unit tests for /slp/validateSingle 2020-12-05 08:46:22 -08:00
Chris Troutner a260f7506a Merge pull request #69 from Permissionless-Software-Foundation/ct-unstable
fix(whitelist): Adusting the domain names on the whitelist
2020-12-03 14:19:45 -08:00
Chris Troutner 9684441d92 fix(whitelist): Adusting the domain names on the whitelist 2020-12-03 14:17:28 -08:00
Chris Troutner e793c2a8a9 Merge pull request #68 from Permissionless-Software-Foundation/ct-unstable
fix(txDetails): Adding additional metadata to GET slp/txDetails
2020-11-29 17:59:10 -08:00
Chris Troutner 1bf8e59097 fix(txDetails): Adding additional metadata to GET slp/txDetails 2020-11-29 17:56:22 -08:00
Chris Troutner 105ecd6305 Merge pull request #67 from josephroyking/psf-add-inputs-to-txDetails
Psf add inputs to tx details
2020-11-29 17:51:13 -08:00
josephroyking 314040453b Support unconfirmed slp txs 2020-11-25 15:31:59 -08:00
josephroyking cbcf5c1d2b Add tx input details to slp/txDetails endpoint 2020-11-25 10:56:10 -08:00
Chris Troutner e881b68ca5 Merge pull request #65 from Permissionless-Software-Foundation/ct-unstable
ix(electrumx): Fixed connect/disconnect bug that was preventing tests
2020-11-21 11:39:05 -08:00
Chris Troutner f54c69a664 Fixing test typo 2020-11-21 11:35:01 -08:00
Chris Troutner 319281c096 fix(electrumx): Fixed connect/disconnect bug that was preventing tests 2020-11-21 11:29:18 -08:00
Chris Troutner 7dee8c0604 Merge branch 'master' into ct-unstable 2020-11-21 11:15:41 -08:00
Chris Troutner efbcbc5deb linting 2020-11-21 11:15:33 -08:00
Chris Troutner c742518612 Merge pull request #64 from Permissionless-Software-Foundation/ct-unstable
fix(electrumx): Automatically reconnecting when Electrumx disconnects
2020-11-20 20:53:40 -08:00
Chris Troutner 6a0ed46413 fix(electrumx): Automatically reconnecting when Electrumx disconnects 2020-11-20 20:52:22 -08:00
Chris Troutner 5ea71bc89b Updating default Docker run script 2020-11-20 08:36:34 -08:00
Chris Troutner 84701e90dc Merge pull request #63 from Permissionless-Software-Foundation/ct-unstable
fix(price): Fixing bug in new price endpoint
2020-11-17 14:29:22 -08:00
Chris Troutner 34ed5ddc4c fix(price): Fixing bug in new price endpoint 2020-11-17 14:27:42 -08:00
Chris Troutner 9a8cd4b664 Merge pull request #62 from Permissionless-Software-Foundation/ct-unstable
fix(price): Adding Coinex price feed for BCHA
2020-11-17 14:00:37 -08:00
Chris Troutner 2a0b06ca96 fix(price): Adding Coinex price feed for BCHA 2020-11-17 13:48:10 -08:00
Chris Troutner 9c70fc5007 Merge pull request #61 from Permissionless-Software-Foundation/ct-unstable
fix(whitelist): Adding splitbch.com to the whitelist
2020-11-14 17:39:41 -08:00
Chris Troutner b24b659124 fix(whitelist): Adding splitbch.com to the whitelist 2020-11-14 17:36:38 -08:00
Chris Troutner 7ad5acef34 Merge pull request #60 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Setting anonymous rate limits to a constant
2020-11-12 09:11:48 -08:00
Chris Troutner 304a3f1d5a fix(rate limits): Setting anonymous rate limits to a constant 2020-11-12 09:10:35 -08:00
Chris Troutner 86a58e9ff3 Merge pull request #59 from Permissionless-Software-Foundation/ct-unstable
fix(auth): Fixing typo that was breaking basic authentication
2020-11-11 19:58:11 -08:00
Chris Troutner d7d722b27b Merge branch 'master' into ct-unstable 2020-11-11 19:55:58 -08:00
Chris Troutner d439165dd2 fix(auth): Fixing typo that was breaking basic authentication 2020-11-11 19:55:15 -08:00
Chris Troutner 65356051f8 Merge pull request #58 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Adding local server back to whitelist
2020-11-11 19:16:07 -08:00
Chris Troutner 9728b64edb fix(rate limits): Adding local server back to whitelist 2020-11-11 18:59:48 -08:00
Chris Troutner 7e71d355ba Merge pull request #57 from Permissionless-Software-Foundation/ct-unstable
Basic Authentication
2020-11-11 17:53:38 -08:00
Chris Troutner fe9f40e847 linting 2020-11-11 17:52:19 -08:00
Chris Troutner 28f0a1de56 feat(Basic Authentication): Adding back in for controlling access 2020-11-11 14:56:24 -08:00
Chris Troutner b8589a54aa Trying to reinstate basic auth 2020-11-11 07:48:40 -08:00
Chris Troutner 0d05803462 Update README 2020-11-08 19:19:21 -08:00
Chris Troutner 69d125ad24 fixing README 2020-11-08 17:30:55 -08:00
Chris Troutner 7631a25f4b Merge pull request #56 from Permissionless-Software-Foundation/ct-unstable
Removing Blockbook documentation
2020-11-08 17:26:39 -08:00
Chris Troutner f41f9d33c8 feat(blockbook): Removing Blockbook documentation 2020-11-08 17:25:05 -08:00
Chris Troutner 3475255444 Updating diagram 2020-11-08 17:22:57 -08:00
Chris Troutner bcc5c95bd6 Updating README 2020-11-08 17:20:58 -08:00
Chris Troutner 15fe66bdf3 Merge branch 'master' into ct-unstable 2020-11-08 17:19:43 -08:00
Chris Troutner 8ce0209e9a Updating README 2020-11-08 17:19:30 -08:00
Chris Troutner c7c19d1c2b Merge pull request #55 from Permissionless-Software-Foundation/ct-unstable
Updating README
2020-11-08 17:17:15 -08:00
Chris Troutner f36146ef24 Updating README 2020-11-08 17:15:53 -08:00
Chris Troutner edae956742 Updating README 2020-11-08 17:13:03 -08:00
Chris Troutner 3f2890661c Updating README 2020-11-08 17:04:17 -08:00
21 changed files with 1433 additions and 320 deletions
+20 -25
View File
@@ -1,19 +1,12 @@
# bch-api
This is a node.js JavaScript REST API server using Express.js. The purpose of this code is to create a REST API server that provides a common interface for working with a Bitcoin Cash full node and various indexers. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) to learn about the 'Cash Stack'. Visit [FullStack.cash](https://fullstack.cash), sign up for a free account, and use this REST API right away with the [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js) JavaScript library.
[![Build Status](https://travis-ci.org/christroutner/bch-api.svg?branch=master)](https://travis-ci.org/christroutner/bch-api)
This repository is intended to be paired with [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js), an npm JavaScript library for building Bitcoin Cash apps.
This is a fork and alternative implementation of
the [rest.bitcoin.com](https://github.com/Bitcoin-com/rest.bitcoin.com) repository.
The purpose of this code is to create a REST API server that provides a common
interface for working with a Bitcoin Cash full node and various indexers. See [this article](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer) to learn about the 'Cash Stack'. Visit [FullStack.cash](https://fullstack.cash), sign up for a free account, and use this REST API right away with the [bch-js](https://github.com/christroutner/bch-js) JavaScript library.
![Cash Stack Network Diagram](./generic-network-diagram.png)
This repository is intended to be paired with [bch-js](https://github.com/christroutner/bch-js),
an npm JavaScript library, and an alternative implementation
of [BITBOX SDK](https://github.com/Bitcoin-com/bitbox-sdk).
Both bch-api and bch-js are part of the
[full stack of BCH software](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
Both bch-api and bch-js are part of the 'Cash Stack' [full stack of BCH software](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
- [API Documentation](https://fullstack.cash/documentation)
- [Example Code](https://fullstack.cash/examples)
@@ -24,32 +17,29 @@ Have questions? Need help? Join our community support:
## Features
The following features set this repository apart from rest.bitcoin.com:
- Address balance and UTXO queries use the [Blockbook](https://github.com/trezor/blockbook)
indexer instead of Insight.
- Fine grain access is controlled with a JWT token using
[this back end auth server](https://github.com/Permissionless-Software-Foundation/jwt-bch-api) and [this front end](https://github.com/Permissionless-Software-Foundation/jwt-bch-frontend).
- Default rate limits are set to 3 RPM for anonymous connections, 10 RPM for [free accounts](https://fullstack.cash/pricing), up to 100 RPM if a full-access JWT token is used.
[this back end auth server](https://github.com/Permissionless-Software-Foundation/jwt-bch-api) and [this front end](https://github.com/Permissionless-Software-Foundation/jwt-bch-frontend). Can be used to monetize access to the REST API.
- Typescript removed and ES8 JavaScript used instead.
- npm audit run on all dependencies.
- [Greenkeeper](https://greenkeeper.io/) implemented for automatic dependency management
and security updates.
## Live Demo
You can test a live demo of the REST API by running the
[bch-js examples](https://github.com/Permissionless-Software-Foundation/bch-js-examples).
Rate limits are 3 requests per minute, but you can increase them to 10 with a [free account](https://fullstack.cash/pricing).
This is fast enough to try out the examples
but these servers are not intended as a freemium service. You can run your own
REST server by purchasing the hard drive at [bchjs.cash](https://bchjs.cash).
Rate limits are 20 requests per minute, but you can increase them to 100 with a [paid account](https://fullstack.cash/pricing).
You can bootstrap your own REST API server by downloading and installing the infrastructure listed on the [CashStrap](https://fullstack.cash/cashstrap) page.
- Mainnet REST API server: https://api.fullstack.cash/v3/
- Testnet REST API server: https://tapi.fullstack.cash/v3/
### Configure bch-js
The live servers can be used by [bch-js](https://github.com/Permissionless-Software-Foundation/bch-js) by settings the `restURL` config property to one of these servers:
- BCHN Mainnet REST API server: https://bchn.fullstack.cash/v3/
- ABC Mainnet REST API server: https://abc.fullstack.cash/v3/
- Testnet3 REST API server: https://testnet3.fullstack.cash/v3/
- Check server status: https://metrics.fullstack.cash
## Installation
There are two installation paths, depending if you want a *development* or
*production* environment. You'll also need to set up the underlying infrastructure
described [this page](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
described on [this page](https://troutsblog.com/research/bitcoin-cash/how-to-bch-full-stack-developer).
This code targets the Ubuntu 18.04 LTS Linux OS.
@@ -58,7 +48,7 @@ This is a standard node.js project. The installation is as follows:
- Clone this repository:
`git clone https://github.com/christroutner/bch-api && cd bch-api`
`git clone https://github.com/Permissionless-Software-Foundation/bch-api && cd bch-api`
- Install dependencies:
@@ -93,5 +83,10 @@ installation.
Have questions? Need help? Join our community support
[Telegram channel](https://t.me/bch_js_toolkit)
## IPFS
Copies of this repository will occasionally be uploaded and hosted on [IPFS](https://ipfs.io):
- v1.15.4: QmSAerFmDJm6KQp2HC8jsRR5MdL5X39hoUsJYvWNDvrD8m
## License
[MIT](./LICENSE.md)
+11 -1
View File
@@ -17,11 +17,21 @@ export BLOCKBOOK_URL=https://172.17.0.1:9131/
# Allow node.js to make network calls to https using self-signed certificate.
export NODE_TLS_REJECT_UNAUTHORIZED=0
# Redis DB
# Mainnet Fulcrum / ElectrumX
export FULCRUM_URL=172.17.0.1
export FULCRUM_PORT=50002
# Redis DB - Used for rate limiting
export REDIS_PORT=6379
export REDIS_HOST=172.17.0.1
# JWT Token Secret
export TOKENSECRET=somelongsecretvalue
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# slp-api alternative SLP validator.
export SLP_API_URL=http://10.0.0.5:5001/
npm start
+10
View File
@@ -14,6 +14,10 @@ export BLOCKBOOK_URL=https://172.17.0.1:19131/
# Allow node.js to make network calls to https using self-signed certificate.
export NODE_TLS_REJECT_UNAUTHORIZED=0
# Mainnet Fulcrum / ElectrumX
export FULCRUM_URL=172.17.0.1
export FULCRUM_PORT=50002
# Redis DB
export REDIS_PORT=6380
export REDIS_HOST=172.17.0.1
@@ -21,4 +25,10 @@ export REDIS_HOST=172.17.0.1
# JWT Token Secret
export TOKENSECRET=somelongsecretvalue
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# slp-api alternative SLP validator.
export SLP_API_URL=http://10.0.0.5:5001/
npm start
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+2 -1
View File
@@ -17,7 +17,8 @@
"test": "npm run lint && npm run test-v3",
"lint": "standard --env mocha --fix",
"test-v3": "export NETWORK=mainnet && nyc --reporter=text mocha --timeout 60000 test/v3/",
"test:temp": "export NETWORK=mainnet && export TEST=integration && mocha --timeout 25000 test/v3/encryption.js",
"test:temp:integration": "export NETWORK=mainnet && export TEST=integration && mocha --timeout 25000 test/v3/integration/price.js",
"test:temp:unit": "export NETWORK=mainnet && mocha -g '#validateBulk' --exit test/v3/",
"test:integration": "mocha test/v3/integration",
"test:integration:slpdb": "mocha --timeout 25000 -g '#validate2Single' test/v3/integration/slp*.js",
"coverage": "nyc report --reporter=text-lcov | coveralls",
+55 -49
View File
@@ -22,9 +22,9 @@
'use strict'
const passport = require('passport')
// const BasicStrategy = require('passport-http').BasicStrategy
const BasicStrategy = require('passport-http').BasicStrategy
const AnonymousStrategy = require('passport-anonymous')
// const wlogger = require('../util/winston-logging')
const wlogger = require('../util/winston-logging')
// Used for debugging and iterrogating JS objects.
const util = require('util')
@@ -33,9 +33,11 @@ util.inspect.defaultOptions = { depth: 1 }
// let _this
// Set default rate limit value for testing
// const PRO_PASSES = process.env.PRO_PASS ? process.env.PRO_PASS : 'BITBOX'
const PRO_PASSES = process.env.PRO_PASS
? process.env.PRO_PASS
: 'testpassword'
// Convert the pro-tier password string into an array split by ':'.
// const PRO_PASS = PRO_PASSES.split(':')
const PRO_PASS = PRO_PASSES.split(':')
// wlogger.verbose(`PRO_PASS set to: ${PRO_PASS}`)
@@ -47,56 +49,60 @@ class AuthMW {
// Initialize passport for 'anonymous' authentication.
passport.use(new AnonymousStrategy())
console.log(`PRO_PASS: ${JSON.stringify(PRO_PASS, null, 2)}`)
// Initialize passport for 'basic' authentication.
// passport.use(
// new BasicStrategy({ passReqToCallback: true }, function (
// req,
// username,
// password,
// done
// ) {
// // console.log(`req: ${util.inspect(req)}`)
// // console.log(`username: ${username}`)
// // console.log(`password: ${password}`)
//
// // Create the req.locals property if it does not yet exist.
// if (!req.locals) {
// req.locals = {
// // default values
// proLimit: false,
// apiLevel: 0
// }
// }
//
// // Set pro-tier rate limit to flag to false by default.
// req.locals.proLimit = false
//
// // Evaluate the username and password and set the rate limit accordingly.
// // if (username === "BITBOX" && password === PRO_PASS) {
// if (username === 'BITBOX') {
// for (let i = 0; i < PRO_PASS.length; i++) {
// const thisPass = PRO_PASS[i]
//
// if (password === thisPass) {
// wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
//
// // Success
// req.locals.proLimit = true
// break
// }
// }
// }
//
// // console.log(`req.locals: ${util.inspect(req.locals)}`)
//
// return done(null, true)
// })
// )
passport.use(
new BasicStrategy({ passReqToCallback: true }, function (
req,
username,
password,
done
) {
// console.log(`req: ${util.inspect(req)}`)
// console.log(`username: ${username}`)
// console.log(`password: ${password}`)
// Create the req.locals property if it does not yet exist.
if (!req.locals) {
req.locals = {
// default values
proLimit: false,
apiLevel: 0
}
}
// Set pro-tier rate limit to flag to false by default.
req.locals.proLimit = false
// Evaluate the username and password and set the rate limit accordingly.
// if (username === "BITBOX" && password === PRO_PASS) {
if (username === 'fullstackcash') {
for (let i = 0; i < PRO_PASS.length; i++) {
const thisPass = PRO_PASS[i]
if (password === thisPass) {
wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
// Success
req.locals.proLimit = true
console.log(`User ${req.ip} authenticated using Basic Auth`)
break
}
}
}
// console.log(`req.locals: ${util.inspect(req.locals)}`)
return done(null, true)
})
)
}
// Middleware called by the route.
mw () {
return passport.authenticate(['anonymous'], {
console.log('Initializing passport')
return passport.authenticate(['basic', 'anonymous'], {
session: false
})
}
+78 -71
View File
@@ -12,10 +12,12 @@
'use strict'
const jwt = require('jsonwebtoken')
const wlogger = require('../util/winston-logging')
const config = require('../../config')
const jwt = require('jsonwebtoken')
const ANON_LIMITS = 50
// Redis
const redisOptions = {
@@ -111,76 +113,81 @@ class RateLimits {
}
// Default value is 50 points per request = 20 RPM
let rateLimit = 50
let rateLimit = ANON_LIMITS
// Code here for the rate limiter is adapted from this example:
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
try {
// The resource being consumed: full node, indexer, SLPDB, etc.
const resource = _this.getResource(req.url)
wlogger.debug(`resource: ${resource}`)
// Only evaluate the JWT token if the user is not using Basic Authentication.
if (!req.locals.proLimit) {
// Code here for the rate limiter is adapted from this example:
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
try {
// The resource being consumed: full node, indexer, SLPDB, etc.
const resource = _this.getResource(req.url)
wlogger.debug(`resource: ${resource}`)
let key = userId || req.ip
res.locals.key = key // Feedback for tests.
let key = userId || req.ip
res.locals.key = key // Feedback for tests.
// const pointsToConsume = userId ? 1 : 30
decoded.resource = resource
let pointsToConsume = _this.calcPoints(decoded)
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
// Retrieve the origin.
let origin = req.get('origin')
// Handle calls coming from the intranet.
if (origin === undefined && key.indexOf('10.0.0.5') > -1) {
origin = 'slp-api'
}
wlogger.info(`origin: ${origin}`)
// If the request originates from one of the approved wallet apps, then
// apply paid-access rate limits.
if (
origin &&
(origin.toString().indexOf('wallet.fullstack.cash') > -1 ||
origin.toString().indexOf('sandbox.fullstack.cash') > -1 ||
origin === 'slp-api')
) {
pointsToConsume = 10
// const pointsToConsume = userId ? 1 : 30
decoded.resource = resource
let pointsToConsume = _this.calcPoints(decoded)
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
// Retrieve the origin.
let origin = req.get('origin')
// Handle calls coming from the intranet.
if (origin === undefined && key.indexOf('10.0.0.5') > -1) {
origin = 'slp-api'
}
wlogger.info(`origin: ${origin}`)
// If the request originates from one of the approved wallet apps, then
// apply paid-access rate limits.
if (
origin &&
(origin.toString().indexOf('fullstack.cash') > -1 ||
origin.toString().indexOf('splitbch.com') > -1 ||
origin.toString().indexOf('slp-api') > -1)
) {
pointsToConsume = 10
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
// For internal calls, increase rate limits to as fast as possible.
if (
// Comment out the line below when running bch-js e2e rate limit tests.
key.toString().indexOf('::ffff:127.0.0.1') > -1 ||
// Do not comment out this line.
key.toString().indexOf('172.17.') > -1
) {
pointsToConsume = 1
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
wlogger.info(
`User ${key} consuming ${pointsToConsume} point for resource ${resource}.`
)
rateLimit = Math.floor(1000 / pointsToConsume)
// Update the key so that rate limits track both the user and the resource.
key = `${key}-${resource}`
await _this.rateLimiter.consume(key, pointsToConsume)
} catch (err) {
// console.log('err: ', err)
// Used for returning data for tests.
res.locals.rateLimitTriggered = true
// console.log('res.locals: ', res.locals)
// Rate limited was triggered
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: `Too many requests. Your limits are currently ${rateLimit} requests per minute. Increase rate limits at https://fullstack.cash`
})
}
// For internal calls, increase rate limits to as fast as possible.
if (
key.toString().indexOf('172.17.') > -1 ||
key.toString().indexOf('::ffff:127.0.0.1') > -1
) {
pointsToConsume = 1
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
wlogger.info(
`User ${key} consuming ${pointsToConsume} point for resource ${resource}.`
)
rateLimit = Math.floor(1000 / pointsToConsume)
// Update the key so that rate limits track both the user and the resource.
key = `${key}-${resource}`
await _this.rateLimiter.consume(key, pointsToConsume)
} catch (err) {
// console.log('err: ', err)
// Used for returning data for tests.
res.locals.rateLimitTriggered = true
// console.log('res.locals: ', res.locals)
// Rate limited was triggered
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: `Too many requests. Your limits are currently ${rateLimit} requests per minute. Increase rate limits at https://fullstack.cash`
})
}
} catch (err) {
wlogger.error('Error in route-ratelimit.js/newRateLimit(): ', err)
@@ -193,7 +200,7 @@ class RateLimits {
// Calculates the points consumed, based on the jwt information and the route
// requested.
calcPoints (jwtInfo) {
let retVal = 50 // By default, use anonymous tier.
let retVal = ANON_LIMITS // By default, use anonymous tier.
try {
// console.log(`jwtInfo: ${JSON.stringify(jwtInfo, null, 2)}`)
@@ -212,12 +219,12 @@ class RateLimits {
if (level40Routes.includes(resource)) {
if (apiLevel >= 40) retVal = 10
// else if (apiLevel >= 10) retVal = 10
else retVal = 50
else retVal = ANON_LIMITS
// Normal indexer routes
} else if (level30Routes.includes(resource)) {
if (apiLevel >= 30) retVal = 10
else retVal = 50
else retVal = ANON_LIMITS
// Full node tier
} else if (apiLevel >= 20) {
@@ -225,7 +232,7 @@ class RateLimits {
// Free tier, full node only.
} else {
retVal = 50
retVal = ANON_LIMITS
}
}
@@ -233,7 +240,7 @@ class RateLimits {
} catch (err) {
wlogger.error('Error in route-ratelimit.js/calcPoints()')
// throw err
retVal = 50
retVal = ANON_LIMITS
}
return retVal
-70
View File
@@ -96,18 +96,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/balance/{addr} Get balance for a single address.
* @apiName Balance for a single address
* @apiGroup Blockbook
* @apiDescription Returns an object with balance and details about an address.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/balance/bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf" -H "accept: application/json"
*
*/
// GET handler for single balance
async balanceSingle (req, res, next) {
try {
const address = req.params.address
@@ -165,18 +153,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/balance Get balance for an array of addresses.
* @apiName Balance for an array of addresses
* @apiGroup Blockbook
* @apiDescription Return balances and details for an array of addresses.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/balance" -H "accept: application/json" -H "Content-Type: application/json" -d '{"addresses":["bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf","bitcoincash:qrdka2205f4hyukutc2g0s6lykperc8nsu5u2ddpqf"]}'
*
*
*/
// POST handler for bulk queries on address details
async balanceBulk (req, res, next) {
try {
@@ -284,17 +260,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/utxos/{addr} Get utxos for a single address.
* @apiName UTXOs for a single address
* @apiGroup Blockbook
* @apiDescription Returns an object with UTXOs associated with an address.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/utxos/bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3" -H "accept: application/json"
*
*/
// GET handler for single balance
async utxosSingle (req, res, next) {
try {
@@ -352,18 +317,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/utxos Get UTXOs for an array of addresses.
* @apiName UTXOs for an array of addresses
* @apiGroup Blockbook
* @apiDescription Return UTXOs associate with an array of addresses.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/utxos" -H "accept: application/json" -H "Content-Type: application/json" -d '{"addresses":["bitcoincash:qr69kyzha07dcecrsvjwsj4s6slnlq4r8c30lxnur3","bitcoincash:qzy8wnj0dz927eu6kvh8v2pqsr5w8jh33ys757tdtq"]}'
*
*
*/
// POST handler for bulk queries on address utxos
async utxosBulk (req, res, next) {
try {
@@ -461,17 +414,6 @@ class Blockbook {
}
}
/**
* @api {get} /blockbook/tx/{txid} Get details for a single transaction.
* @apiName Details for a single transaction
* @apiGroup Blockbook
* @apiDescription Returns an object with details for a single transaction
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/blockbook/tx/6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d" -H "accept: application/json"
*
*/
// GET handler for single transaction details.
async txSingle (req, res, next) {
try {
@@ -514,18 +456,6 @@ class Blockbook {
}
}
/**
* @api {post} /blockbook/tx Get details for an array of transactions.
* @apiName Details for an array of transactions
* @apiGroup Blockbook
* @apiDescription Return details for an array of transactions.
* Limited to 20 items per request.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/blockbook/tx" -H "accept: application/json" -H "Content-Type: application/json" -d '{"txids":["6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d","6181c669614fa18039a19b23eb06806bfece1f7514ab457c3bb82a40fe171a6d"]}'
*
*
*/
// POST handler for bulk queries on tx details
async txBulk (req, res, next) {
try {
+18
View File
@@ -79,6 +79,21 @@ class Electrum {
// Set the connection flag.
_this.isReady = true
// 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.')
}
}, 30000)
console.log('...Successfully connected to ElectrumX server.')
// console.log(`_this.isReady: ${_this.isReady}`)
@@ -96,6 +111,9 @@ class Electrum {
// 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()
+39 -2
View File
@@ -24,11 +24,14 @@ class Price {
this.routeUtils = routeUtils
this.priceUrl = 'https://api.coinbase.com/v2/exchange-rates?currency=BCH'
this.coinexPriceUrl =
'https://api.coinex.com/v1/market/ticker?market=bchausdt'
this.router = express.Router()
this.router.get('/', _this.root)
this.router.get('/usd', _this.getUSD)
this.router.get('/rates', _this.getBCHRate)
this.router.get('/bchausd', _this.getBCHAUSD)
}
// DRY error handler.
@@ -53,7 +56,7 @@ class Price {
* @api {get} /price/usd Get the USD price of BCH
* @apiName Get the USD price of BCH
* @apiGroup Price
* @apiDescription Get the USD price of BCH
* @apiDescription Get the USD price of BCH from Coinbase.
*
*
* @apiExample Example usage:
@@ -85,7 +88,7 @@ class Price {
* @api {get} /price/usd Get rates for several different currencies
* @apiName Get rates for several different currencies
* @apiGroup Price
* @apiDescription Get rates for several different currencies
* @apiDescription Get rates for several different currencies from Coinbase.
*
*
* @apiExample Example usage:
@@ -113,6 +116,40 @@ class Price {
return _this.errorHandler(err, res)
}
}
/**
* @api {get} /price/bchausd Get the USD price of BCHA
* @apiName Get the USD price of BCHA
* @apiGroup Price
* @apiDescription Get the USD price of BCHA from Coinex.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/price/bchausd" -H "accept: application/json"
*
*/
async getBCHAUSD (req, res, next) {
try {
// Request options
const opt = {
method: 'get',
baseURL: _this.coinexPriceUrl,
timeout: 15000
}
const response = await axios.request(opt)
// console.log(`response.data: ${JSON.stringify(response.data, null, 2)}`)
const price = Number(response.data.data.ticker.last)
return res.json({ usd: price })
} catch (err) {
// Write out error to error log.
wlogger.error('Error in price.js/getBCHAUSD().', err)
return _this.errorHandler(err, res)
}
}
}
module.exports = Price
+326 -8
View File
@@ -74,6 +74,9 @@ class Slp {
_this.router.post('/validateTxid', _this.validateBulk)
_this.router.get('/validateTxid/:txid', _this.validateSingle)
_this.router.get('/validateTxid2/:txid', _this.validate2Single)
_this.router.get('/validateTxid3/:txid', _this.validate3Single)
_this.router.post('/validateTxid3', _this.validate3Bulk)
_this.router.get('/whitelist', _this.getSlpWhitelist)
_this.router.get('/txDetails/:txid', _this.txDetails)
_this.router.get('/tokenStats/:tokenId', _this.tokenStats)
_this.router.get(
@@ -987,6 +990,7 @@ class Slp {
const s = JSON.stringify(query)
const b64 = Buffer.from(s).toString('base64')
const url = `${process.env.SLPDB_URL}q/${b64}`
// console.log('url: ', url)
const options = _this.generateCredentials()
@@ -1002,7 +1006,7 @@ class Slp {
let formattedTokens = []
// Combine the arrays. Why? Generally there is nothing in the u array.
// Combine the confirmed and unconfirmed collections.
const concatArray = tokenRes.data.c.concat(tokenRes.data.u)
const tokenIds = []
@@ -1024,12 +1028,15 @@ class Slp {
})
// If a user-provided txid doesn't exist in the data, add it with
// valid:false property.
// valid:null property.
// 'null' indicates that SLPDB does not know about the transaction. It
// either has not seen it or has not processed it yet. A determination
// can not be made.
txids.forEach((txid) => {
if (!tokenIds.includes(txid)) {
formattedTokens.push({
txid: txid,
valid: false
valid: null
})
}
})
@@ -1052,8 +1059,21 @@ class Slp {
formattedTokens = newOutput
}
// Put the output array in the same order as the input array.
const outAry = []
for (let i = 0; i < txids.length; i++) {
const thisTxid = txids[i]
// Need to use Array.find() because the returned output array is out
// of order with respect to the txid input array.
const output = formattedTokens.find((elem) => elem.txid === thisTxid)
// console.log(`output: ${JSON.stringify(output, null, 2)}`)
outAry.push(output)
}
res.status(200)
return res.json(formattedTokens)
return res.json(outAry)
} catch (err) {
wlogger.error('Error in slp.ts/validateBulk().', err)
@@ -1110,11 +1130,12 @@ class Slp {
}
// Get data from SLPDB.
const tokenRes = await _this.axios.request(opt)
// console.log(`tokenRes.data: ${JSON.stringify(tokenRes.data, null, 2)}`)
// Default return value.
let result = {
txid: txid,
valid: false
valid: null
}
// Build result.
@@ -1132,7 +1153,7 @@ class Slp {
res.status(200)
return res.json(result)
} catch (err) {
wlogger.error('Error in slp.ts/validateSingle().', err)
wlogger.error('Error in slp.js/validateSingle().', err)
return _this.errorHandler(err, res)
}
@@ -1199,6 +1220,284 @@ class Slp {
}
}
/**
* @api {get} /slp/whitelist SLP token whitelist.
* @apiName SLP token whitelist
* @apiGroup SLP
* @apiDescription Get tokens that are on the whitelist.
* SLPDB is typically used to validate SLP transactions. It can become unstable
* during periods of high network usage. A second SLPDB has been implemented
* that is much more stable, because it only tracks a whitelist of SLP tokens.
* This endpoint will return information on the SLP tokens that are included
* in that whitelist.
*
* For tokens on the whitelist, the /slp/validateTxid3 endpoints can be used.
*
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/slp/whitelist" -H "accept:application/json"
*
*/
async getSlpWhitelist (req, res, next) {
try {
const list = [
{
name: 'USDH',
tokenId:
'c4b0d62156b3fa5c8f3436079b5394f7edc1bef5dc1cd2f9d0c4d46f82cca479'
},
{
name: 'SPICE',
tokenId:
'4de69e374a8ed21cbddd47f2338cc0f479dc58daa2bbe11cd604ca488eca0ddf'
},
{
name: 'PSF',
tokenId:
'38e97c5d7d3585a2cbf3f9580c82ca33985f9cb0845d4dcce220cb709f9538b0'
},
{
name: 'TROUT',
tokenId:
'a4fb5c2da1aa064e25018a43f9165040071d9e984ba190c222a7f59053af84b2'
},
{
name: 'PSFTEST',
tokenId:
'd0ef4de95b78222bfee2326ab11382f4439aa0855936e2fe6ac129a8d778baa0'
}
]
res.status(200)
return res.json(list)
} catch (err) {
wlogger.error('Error in slp.ts/whitelist().', err)
return _this.errorHandler(err, res)
}
}
/**
* @api {get} /slp/validateTxid3/{txid} Validate single SLP transaction by txid.
* @apiName Validate single SLP transaction by txid.
* @apiGroup SLP
* @apiDescription Alternative validation for tokens on the whitelist
* This endpoint is exactly the same as /slp/validateTxid/{txid} but it uses
* a different SLPDB. This server only indexes the SLP tokens that are on the
* whitelist. You can see which tokens are on the whitelist by calling the
* /slp/whitelist endpoint.
*
* @apiExample Example usage:
* curl -X GET "https://api.fullstack.cash/v3/slp/validateTxid3/f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a" -H "accept:application/json"
*
*
*/
async validate3Single (req, res, next) {
try {
const txid = req.params.txid
// Validate input
if (!txid || txid === '') {
res.status(400)
return res.json({ error: 'txid can not be empty' })
}
wlogger.debug('Executing slp/validate/:txid with this txid: ', txid)
const query = {
v: 3,
q: {
db: ['c', 'u'],
find: {
'tx.h': txid
},
limit: 300,
project: { 'slp.valid': 1, 'tx.h': 1, 'slp.invalidReason': 1 }
}
}
const options = _this.generateCredentials()
const s = JSON.stringify(query)
const b64 = Buffer.from(s).toString('base64')
const url = `${process.env.SLPDB_WHITELIST_URL}q/${b64}`
const opt = {
method: 'get',
baseURL: url,
headers: options.headers,
timeout: options.timeout
}
// Get data from SLPDB.
const tokenRes = await _this.axios.request(opt)
// console.log(`tokenRes.data: ${JSON.stringify(tokenRes.data, null, 2)}`)
// Default return value.
let result = {
txid: txid,
valid: null
}
// Build result.
const concatArray = tokenRes.data.c.concat(tokenRes.data.u)
if (concatArray.length > 0) {
result = {
txid: concatArray[0].tx.h,
valid: concatArray[0].slp.valid
}
if (!result.valid) {
result.invalidReason = concatArray[0].slp.invalidReason
}
}
res.status(200)
return res.json(result)
} catch (err) {
wlogger.error('Error in slp.js/validate3Single().', err)
return _this.errorHandler(err, res)
}
}
/**
* @api {post} /slp/validateTxid3/ Validate multiple SLP transactions by txid.
* @apiName Validate multiple SLP transactions by txid.
* @apiGroup SLP
* @apiDescription Alternative validation for tokens on the whitelist
* This endpoint is exactly the same as /slp/validateTxid but it uses
* a different SLPDB. This server only indexes the SLP tokens that are on the
* whitelist. You can see which tokens are on the whitelist by calling the
* /slp/whitelist endpoint.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/slp/validateTxid3" -H "accept:application/json" -H "Content-Type: application/json" -d '{"txids":["f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a","fb0eeaa501a6e1acb721669c62a3f70741f48ae0fd7f4b8e1d72088785c51952"]}'
*
*
*/
async validate3Bulk (req, res, next) {
try {
const txids = req.body.txids
// Reject if txids is not an array.
if (!Array.isArray(txids)) {
res.status(400)
return res.json({ error: 'txids needs to be an array' })
}
// Enforce array size rate limits
if (!_this.routeUtils.validateArraySize(req, txids)) {
res.status(429) // https://github.com/Bitcoin-com/rest.bitcoin.com/issues/330
return res.json({
error: 'Array too large.'
})
}
wlogger.debug('Executing slp/validate with these txids: ', txids)
const query = {
v: 3,
q: {
db: ['c', 'u'],
find: {
'tx.h': { $in: txids }
},
limit: 300,
project: { 'slp.valid': 1, 'tx.h': 1, 'slp.invalidReason': 1 }
}
}
const s = JSON.stringify(query)
const b64 = Buffer.from(s).toString('base64')
const url = `${process.env.SLPDB_WHITELIST_URL}q/${b64}`
// console.log('url: ', url)
const options = _this.generateCredentials()
// Get data from SLPDB.
const opt = {
method: 'get',
baseURL: url,
headers: options.headers,
timeout: options.timeout
}
const tokenRes = await _this.axios.request(opt)
// console.log(`tokenRes.data: ${JSON.stringify(tokenRes.data, null, 2)}`)
let formattedTokens = []
// Combine the arrays. Why? Generally there is nothing in the u array.
const concatArray = tokenRes.data.c.concat(tokenRes.data.u)
const tokenIds = []
if (concatArray.length > 0) {
concatArray.forEach((token) => {
tokenIds.push(token.tx.h) // txid
const validationResult = {
txid: token.tx.h,
valid: token.slp.valid
}
// If the txid is invalid, add the reason it's invalid.
if (!validationResult.valid) {
validationResult.invalidReason = token.slp.invalidReason
}
formattedTokens.push(validationResult)
})
// If a user-provided txid doesn't exist in the data, add it with
// valid:null property.
// 'null' indicates that SLPDB does not know about the transaction. It
// either has not seen it or has not processed it yet. A determination
// can not be made.
txids.forEach((txid) => {
if (!tokenIds.includes(txid)) {
formattedTokens.push({
txid: txid,
valid: null
})
}
})
}
// Catch a corner case of repeated txids. SLPDB will remove redundent TXIDs,
// which will cause the output array to be smaller than the input array.
if (txids.length > formattedTokens.length) {
const newOutput = []
for (let i = 0; i < txids.length; i++) {
const thisTxid = txids[i]
// Find the element that matches the current txid.
const elem = formattedTokens.filter((x) => x.txid === thisTxid)
newOutput.push(elem[0])
}
// Replace the original output object with the new output object.
formattedTokens = newOutput
}
// Put the output array in the same order as the input array.
const outAry = []
for (let i = 0; i < txids.length; i++) {
const thisTxid = txids[i]
// Need to use Array.find() because the returned output array is out
// of order with respect to the txid input array.
const output = formattedTokens.find((elem) => elem.txid === thisTxid)
// console.log(`output: ${JSON.stringify(output, null, 2)}`)
outAry.push(output)
}
res.status(200)
return res.json(outAry)
} catch (err) {
wlogger.error('Error in slp.js/validate3Bulk().', err)
return _this.errorHandler(err, res)
}
}
/**
* @api {get} /slp/txDetails/{txid} SLP transaction details.
* @apiName SLP transaction details.
@@ -1251,7 +1550,9 @@ class Slp {
const tokenRes = await _this.axios.request(opt)
// console.log(`tokenRes: ${util.inspect(tokenRes)}`)
if (tokenRes.data.c.length === 0) {
// Return 'not found' error if both the confirmed and unconfirmed
// collections are empty.
if (tokenRes.data.c.length === 0 && tokenRes.data.u.length === 0) {
res.status(404)
return res.json({ error: 'TXID not found' })
}
@@ -1437,12 +1738,29 @@ class Slp {
sendOutputs.push(string.toString())
})
// Because you are not using Insight API indexer, you do not get the
// sending addresses from an indexer or from the node.
// However, they are available from the SLPDB output.
const tokenInputs = transaction.in
// Collect the input addresses
const sendInputs = []
for (let i = 0; i < tokenInputs.length; i += 1) {
const tokenInput = tokenInputs[i]
const sendInput = {}
sendInput.address = tokenInput.e.a
sendInputs.push(sendInput)
}
const obj = {
tokenInfo: {
versionType: transaction.slp.detail.versionType,
tokenName: transaction.slp.detail.name,
tokenTicker: transaction.slp.detail.symbol,
transactionType: transaction.slp.detail.transactionType,
tokenIdHex: transaction.slp.detail.tokenIdHex,
sendOutputs: sendOutputs
sendOutputs: sendOutputs,
sendInputsFull: sendInputs,
sendOutputsFull: transaction.slp.detail.outputs
},
tokenIsValid: transaction.slp.valid
}
+14
View File
@@ -8,6 +8,14 @@ export NETWORK=mainnet
# SLPDB
export SLPDB_URL=http://<SLPDB IP>:12300/
export SLPDB_PASS=somelongpassword
# Use the same address as SLPDB_URL if you don't have a separate whitelist server.
export SLPDB_WHITELIST_URL=http://<SLPDB IP>:12300/
# slp-api alternative SLP validator using slp-validate:
# https://github.com/Permissionless-Software-Foundation/slp-api
export SLP_API_URL=http://10.0.0.5:5001/
# Blockbook
export BLOCKBOOK_URL=https://<Blockbook IP>:9131/
@@ -20,4 +28,10 @@ export FULCRUM_PORT=50002
export TOKENSECRET=somelongpassword
# So that bch-api can call bch-js locally.
export LOCAL_RESTURL=http://127.0.0.1:3000/v3/
# Basic Authentication password
export PRO_PASS=somerandomepassword:someotherrandompassword:aThirdPassword
npm start
+1 -1
View File
@@ -42,7 +42,7 @@ function expectRouteError (res, result, expectedError, code = 400) {
assert.equal(result.success, false)
}
describe('#ElectrumX Router', () => {
describe('#Electrumx', () => {
let req, res
let sandbox
const electrumxRoute = new ElecrumxRoute()
+5 -1
View File
@@ -821,6 +821,7 @@ describe('#BlockchainRouter', () => {
])
})
})
describe('getRawMempool()', () => {
it('should throw 503 when network issues', async () => {
// Save the existing RPC URL.
@@ -842,6 +843,7 @@ describe('#BlockchainRouter', () => {
'Error message expected'
)
})
it('returns proper error when downstream service stalls', async () => {
// Mock the timeout error.
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
@@ -856,6 +858,7 @@ describe('#BlockchainRouter', () => {
'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' })
@@ -871,7 +874,7 @@ describe('#BlockchainRouter', () => {
)
})
it('should GET /getMempoolInfo', async () => {
it('should GET /getRawMempool', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox
@@ -886,6 +889,7 @@ describe('#BlockchainRouter', () => {
// Not sure what other assertions should be made here.
})
})
describe('getMempoolEntrySingle()', () => {
it('should throw 400 if txid is empty', async () => {
const result = await uut.getMempoolEntrySingle(req, res)
+12 -1
View File
@@ -4,7 +4,7 @@
'use strict'
// const assert = require('chai').assert
const assert = require('chai').assert
// const axios = require('axios')
// Used for debugging.
@@ -29,6 +29,17 @@ describe('#price', () => {
it('should get the USD price', async () => {
const result = await price.getUSD(req, res)
console.log(`result: ${util.inspect(result)}`)
assert.isNumber(result.usd)
})
})
describe('#getBCHAUSD', () => {
it('should get the USD price of BCHA', async () => {
const result = await price.getBCHAUSD(req, res)
console.log(`result: ${util.inspect(result)}`)
assert.isNumber(result.usd)
})
})
})
+38 -40
View File
@@ -1,7 +1,6 @@
/*
This integration tests should be run against a live bch-api REST server. It
tests to ensure the rate-limits are working as expected. Adjust the values
in the tests below to match the rate limit setting in your own installation.
These tests have been deprecated. To test bch-api rate limits, run the e2e
tests in the bch-js repository.
*/
'use strict'
@@ -17,11 +16,11 @@ util.inspect.defaultOptions = { depth: 1 }
// const SERVER = `http://192.168.0.36:12400/v3/`
const SERVER = 'http://localhost:3000/v3/'
// const SERVER = 'https://api.fullstack.cash/v3/'
//
// const TEST_JWT =
// 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
const TEST_JWT =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
describe('#rate limits', () => {
describe('#JWT rate limits', () => {
it('should get control/getNetworkInfo() with no auth', async () => {
const options = {
method: 'GET',
@@ -36,25 +35,24 @@ describe('#rate limits', () => {
assert.hasAnyKeys(result.data, ['version'])
})
it('should trigger rate-limit handler if rate limits exceeds 5 request per minute', async () => {
it('should trigger rate-limit handler if rate limits exceeds 20 request per minute', async () => {
try {
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
const options = {
method: 'GET',
url: `${SERVER}control/getNetworkInfo`
}
const promises = []
for (let i = 0; i < 5; i++) {
for (let i = 0; i < 30; i++) {
const promise = axios(options)
promises.push(promise)
}
await Promise.all(promises)
assert.equal(true, false, 'Unexpected result!')
assert.fail('Unexpected result!')
} catch (err) {
// console.log(`err.response: ${util.inspect(err.response)}`)
console.log('err: ', err)
assert.equal(err.response.status, 429)
assert.include(err.response.data.error, 'Too many requests')
@@ -135,32 +133,32 @@ describe('#rate limits', () => {
// }
// })
it('should unlock pro-tier for a valid JWT token', async () => {
try {
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
const options = {
method: 'GET',
url: `${SERVER}control/`,
headers: {
Authorization: `Token ${TEST_JWT}`
}
}
const promises = []
for (let i = 0; i < 60; i++) {
const promise = axios(options)
promises.push(promise)
}
await Promise.all(promises)
// assert.equal(true, false, "Unexpected result!")
assert.equal(true, true, 'Not throwing an error is a pass!')
} catch (err) {
console.log(`err.response: ${util.inspect(err.response)}`)
assert.equal(true, false, 'Unexpected result!')
}
// Override default timeout for this test.
}).timeout(20000)
// it('should unlock pro-tier for a valid JWT token', async () => {
// try {
// // Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
// const options = {
// method: 'GET',
// url: `${SERVER}control/`,
// headers: {
// Authorization: `Token ${TEST_JWT}`
// }
// }
//
// const promises = []
// for (let i = 0; i < 60; i++) {
// const promise = axios(options)
// promises.push(promise)
// }
//
// await Promise.all(promises)
//
// // assert.equal(true, false, "Unexpected result!")
// assert.equal(true, true, 'Not throwing an error is a pass!')
// } catch (err) {
// console.log(`err.response: ${util.inspect(err.response)}`)
//
// assert.equal(true, false, 'Unexpected result!')
// }
// // Override default timeout for this test.
// }).timeout(20000)
})
+158
View File
@@ -258,4 +258,162 @@ describe('#slp', () => {
// )
// })
})
describe('#validateBulk', () => {
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
// Known invalid SLP token send of PSF tokens.
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
]
req.body.txids = txids
const result = await slp.validateBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// BCHN expected results
if (process.env.ISBCHN) {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
// Note: This should change from null to true once SLPDB finishes indexing.
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, null)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
} else {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, true)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
}
})
})
describe('#validate3Bulk', () => {
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
// Known invalid SLP token send of PSF tokens.
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
]
req.body.txids = txids
const result = await slp.validate3Bulk(req, res)
console.log(`result: ${JSON.stringify(result, null, 2)}`)
// BCHN expected results
if (process.env.ISBCHN) {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, null)
// Note: This should change from null to true once SLPDB finishes indexing.
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, null)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
} else {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, true)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
}
})
})
})
+22 -2
View File
@@ -216,6 +216,26 @@ const mockCoinbaseFeed = {
}
}
module.exports = {
mockCoinbaseFeed
const mockCoinexFeed = {
code: 0,
data: {
date: 1605649499848,
ticker: {
vol: '26717.39062407',
low: '10.4000',
open: '11.8000',
high: '19.0029',
last: '18.5000',
buy: '18.0100',
buy_amount: '200.00000000',
sell: '18.5000',
sell_amount: '47.89580474'
}
},
message: 'OK'
}
module.exports = {
mockCoinbaseFeed,
mockCoinexFeed
}
+92 -1
View File
@@ -341,6 +341,22 @@ const mockTwoRedundentTxid = {
u: []
}
const mockPsfToken = {
c: [
{
_id: '5fcaf6152898f9887902986c',
tx: {
h: 'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc'
},
slp: {
valid: true,
invalidReason: null
}
}
],
u: []
}
const mockTxHistory = [
{
tx: {
@@ -526,6 +542,78 @@ const mockTxHistory = [
}
]
const mockValidateBulk = {
c: [
{
_id: '5fcc1ae2aff6379ca5bbb213',
tx: {
h: '336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d'
},
slp: {
valid: true,
invalidReason: null
}
},
{
_id: '5fc9b4db4d54eece25b52762',
tx: {
h: 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
},
slp: {
valid: true,
invalidReason: null
}
},
{
_id: '5fc989a14d54eece25af88a6',
tx: {
h: '2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
},
slp: {
valid: false,
invalidReason: 'Token outputs are greater than valid token inputs.'
}
},
{
_id: '5fc974d14d54eece25ad5df2',
tx: {
h: '3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488'
},
slp: {
valid: true,
invalidReason: null
}
}
],
u: []
}
const mockValidate3Bulk = {
c: [
{
_id: '5fcaf60b2898f98879029754',
tx: {
h: 'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd'
},
slp: {
valid: true,
invalidReason: null
}
},
{
_id: '5fcaf5382898f988790275d0',
tx: {
h: '2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
},
slp: {
valid: false,
invalidReason: 'Token outputs are greater than valid token inputs.'
}
}
],
u: []
}
module.exports = {
mockList,
mockSingleToken,
@@ -541,5 +629,8 @@ module.exports = {
mockSingleValidTxid,
mockTwoValidTxid,
mockTwoRedundentTxid,
mockTxHistory
mockTxHistory,
mockPsfToken,
mockValidateBulk,
mockValidate3Bulk
}
+66
View File
@@ -211,4 +211,70 @@ describe('#PriceRouter', () => {
assert.property(result, 'error')
})
})
describe('#getBCHAUSD', () => {
// const getNetworkInfo = controlRoute.testableComponents.getNetworkInfo
it('should throw 500 when network issues', async () => {
uut.coinexPriceUrl = 'http://fakeurl/api/'
await uut.getBCHAUSD(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isAbove(
res.statusCode,
499,
'HTTP status code 500 or greater expected.'
)
// console.log(res)
assert.include(
res.output.error,
'Network error: Could not communicate with full node or other external service'
)
})
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.getBCHAUSD(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.getBCHAUSD(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 the USD price of BCH', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox
.stub(uut.axios, 'request')
.resolves({ data: mockData.mockCoinexFeed })
}
const result = await uut.getBCHAUSD(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isNumber(result.usd)
})
})
})
+466 -47
View File
@@ -338,7 +338,231 @@ describe('#SLP', () => {
}
})
describe('validateBulk()', () => {
describe('#validate2Single', () => {
it('should throw 400 if txid is empty', async () => {
req.params.txid = ''
const result = await slpRoute.validate2Single(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'txid can not be empty')
})
it('should invalidate a known invalid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: { isValid: false } })
}
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
req.params.txid = txid
const result = await slpRoute.validate2Single(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.isValid, false)
})
it('should validate a known valid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: { isValid: true } })
}
const txid =
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488'
req.params.txid = txid
const result = await slpRoute.validate2Single(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.isValid, true)
})
// This test can only be run as a mocked unit test. It's too inconsistent
// to run as an integration test, due to the caching built into slp-validate.
if (process.env.TEST === 'unit') {
it('should cancel if validation takes too long', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({
code: 'ECONNABORTED'
})
const txid =
'eacb1085dfa296fef6d4ae2c0f4529a1bef096dd2325bdcc6dcb5241b3bdb579'
req.params.txid = txid
const result = await slpRoute.validate2Single(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'
)
})
}
})
describe('#validateSingle', () => {
it('should throw 400 if txid is empty', async () => {
req.params.txid = ''
const result = await slpRoute.validateSingle(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'txid can not be empty')
})
it('should invalidate a known invalid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox.stub(slpRoute.axios, 'request').resolves({
data: {
c: [],
u: []
}
})
}
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
req.params.txid = txid
const result = await slpRoute.validateSingle(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.valid, null)
})
it('should validate a known valid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: mockData.mockSingleValidTxid })
}
const txid =
'77872738b6bddee6c0cbdb9509603de20b15d4f6b26602f629417aec2f5d5e8d'
req.params.txid = txid
const result = await slpRoute.validateSingle(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.valid, true)
})
if (process.env.TEST === 'unit') {
it('should cancel if validation takes too long', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({
code: 'ECONNABORTED'
})
const txid =
'eacb1085dfa296fef6d4ae2c0f4529a1bef096dd2325bdcc6dcb5241b3bdb579'
req.params.txid = txid
const result = await slpRoute.validateSingle(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'
)
})
}
})
describe('#validate3Single', () => {
it('should throw 400 if txid is empty', async () => {
req.params.txid = ''
const result = await slpRoute.validate3Single(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'txid can not be empty')
})
it('should invalidate a known invalid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox.stub(slpRoute.axios, 'request').resolves({
data: {
c: [],
u: []
}
})
}
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
req.params.txid = txid
const result = await slpRoute.validate3Single(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.valid, null)
})
it('should validate a known valid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: mockData.mockSingleValidTxid })
}
const txid =
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc'
req.params.txid = txid
const result = await slpRoute.validate3Single(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// assert.equal(result.txid, txid)
assert.equal(result.valid, true)
})
if (process.env.TEST === 'unit') {
it('should cancel if validation takes too long', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({
code: 'ECONNABORTED'
})
const txid =
'eacb1085dfa296fef6d4ae2c0f4529a1bef096dd2325bdcc6dcb5241b3bdb579'
req.params.txid = txid
const result = await slpRoute.validate3Single(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'
)
})
}
})
describe('#validateBulk()', () => {
const validateBulk = slpRoute.validateBulk
it('should throw 400 if txid array is empty', async () => {
@@ -461,77 +685,272 @@ describe('#SLP', () => {
assert.hasAllKeys(result[0], ['txid', 'valid'])
assert.equal(result.length, 2)
})
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox.stub(slpRoute.axios, 'request').resolves({
data: mockData.mockValidateBulk
})
}
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
// Known invalid SLP token send of PSF tokens.
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
]
req.body.txids = txids
const result = await validateBulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
// BCHN expected results
if (process.env.ISBCHN) {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
// Note: This should change from null to true once SLPDB finishes indexing.
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, null)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
} else {
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, true)
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, true)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
}
})
})
describe('#validate2Single', () => {
it('should throw 400 if txid is empty', async () => {
req.params.txid = ''
const result = await slpRoute.validate2Single(req, res)
describe('#validate3Bulk', () => {
const validate3Bulk = slpRoute.validate3Bulk
it('should throw 400 if txid array is empty', async () => {
const result = await validate3Bulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'txid can not be empty')
assert.include(result.error, 'txids needs to be an array')
assert.equal(res.statusCode, 400)
})
it('should invalidate a known invalid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: { isValid: false } })
}
it('should throw 400 error if array is too large', async () => {
const testArray = []
for (var i = 0; i < 25; i++) testArray.push('')
const txid =
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a'
req.body.txids = testArray
req.params.txid = txid
const result = await slpRoute.validate2Single(req, res)
const result = await validate3Bulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.hasAllKeys(result, ['error'])
assert.include(result.error, 'Array too large')
})
it('returns proper error when downstream service stalls', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({ code: 'ECONNABORTED' })
req.body.txids = [
'77872738b6bddee6c0cbdb9509603de20b15d4f6b26602f629417aec2f5d5e8d'
]
const result = await validate3Bulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.isValid, false)
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 validate a known valid TXID', async () => {
if (process.env.TEST === 'unit') {
// Mock to prevent live network connection.
sandbox
.stub(slpRoute.axios, 'request')
.resolves({ data: { isValid: true } })
}
it('returns proper error when downstream service is down', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({ code: 'ECONNREFUSED' })
const txid =
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488'
req.params.txid = txid
const result = await slpRoute.validate2Single(req, res)
req.body.txids = [
'77872738b6bddee6c0cbdb9509603de20b15d4f6b26602f629417aec2f5d5e8d'
]
const result = await validate3Bulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result.txid, txid)
assert.equal(result.isValid, true)
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 validate array with single element', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox.stub(slpRoute.axios, 'request').resolves({
data: mockData.mockPsfToken
})
}
req.body.txids = [
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc'
]
const result = await validate3Bulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isArray(result)
assert.hasAllKeys(result[0], ['txid', 'valid'])
})
it('should validate array with two elements', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox.stub(slpRoute.axios, 'request').resolves({
data: mockData.mockPsfToken
})
}
req.body.txids = [
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc',
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc'
]
const result = await validate3Bulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isArray(result)
assert.hasAllKeys(result[0], ['txid', 'valid'])
assert.equal(result.length, 2)
})
// Captures a regression bug that went out to production, captured in this
// GitHub Issue: https://github.com/Bitcoin-com/rest.bitcoin.com/issues/518
it('should return two elements if given two elements', async () => {
// Mock the RPC call for unit tests.
if (process.env.TEST === 'unit') {
sandbox.stub(slpRoute.axios, 'request').resolves({
data: mockData.mockPsfToken
})
}
req.body.txids = [
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc',
'cdfed769ef7b69e09be06d2821b88598d9a5d711b8f9bd369763c78b7a578fbc'
]
const result = await validate3Bulk(req, res)
// console.log(`result: ${util.inspect(result)}`)
assert.isArray(result)
assert.hasAllKeys(result[0], ['txid', 'valid'])
assert.equal(result.length, 2)
})
// This test can only be run as a mocked unit test. It's too inconsistent
// to run as an integration test, due to the caching built into slp-validate.
if (process.env.TEST === 'unit') {
it('should cancel if validation takes too long', async () => {
// Mock the timeout error.
sandbox.stub(slpRoute.axios, 'request').throws({
code: 'ECONNABORTED'
// This is a unit-test only test, as the results change depending on if
// its tested against the BCHN or ABC networks. There are integration tests
// for this test case in the ../integration/slp.js file.
it('should handle a mix of valid, invalid, and non-SLP txs', async () => {
// Mock the RPC call for unit tests.
sandbox.stub(slpRoute.axios, 'request').resolves({
data: mockData.mockValidate3Bulk
})
const txid =
'eacb1085dfa296fef6d4ae2c0f4529a1bef096dd2325bdcc6dcb5241b3bdb579'
const txids = [
// Malformed SLP tx
'f7e5199ef6669ad4d078093b3ad56e355b6ab84567e59ad0f08a5ad0244f783a',
// Normal TX (non-SLP)
'01cdaec2f8b311fc2d6ecc930247bd45fa696dc204ab684596e281fe1b06c1f0',
// Valid PSF SLP tx
'daf4d8b8045e7a90b7af81bfe2370178f687da0e545511bce1c9ae539eba5ffd',
// Valid SLP token not in whitelist
'3a4b628cbcc183ab376d44ce5252325f042268307ffa4a53443e92b6d24fb488',
// Token send on BCHN network.
'402c663379d9699b6e2dd38737061e5888c5a49fca77c97ab98e79e08959e019',
// Token send on ABC network.
'336bfe2168aac4c3303508a9e8548a0d33797a83b85b76a12d845c8d6674f79d',
// Known invalid SLP token send of PSF tokens.
'2bf691ad3679d928fef880b8a45b93b233f8fa0d0a92cf792313dbe77b1deb74'
]
req.params.txid = txid
const result = await slpRoute.validate2Single(req, res)
req.body.txids = txids
const result = await validate3Bulk(req, res)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isAbove(res.statusCode, 499, 'HTTP status code 503 expected.')
assert.equal(result[0].txid, txids[0])
assert.equal(result[0].valid, null)
assert.equal(result[1].txid, txids[1])
assert.equal(result[1].valid, null)
assert.equal(result[2].txid, txids[2])
assert.equal(result[2].valid, true)
assert.equal(result[3].txid, txids[3])
assert.equal(result[3].valid, null)
assert.equal(result[4].txid, txids[4])
assert.equal(result[4].valid, null)
assert.equal(result[5].txid, txids[5])
assert.equal(result[5].valid, null)
assert.equal(result[6].txid, txids[6])
assert.equal(result[6].valid, false)
assert.include(
result.error,
'Could not communicate with full node',
'Error message expected'
result[6].invalidReason,
'Token outputs are greater than valid token inputs'
)
})
}