mirror of
https://github.com/fullstack-cash/bch-api.git
synced 2026-09-22 09:12:05 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a260f7506a | ||
|
|
9684441d92 | ||
|
|
e793c2a8a9 | ||
|
|
1bf8e59097 | ||
|
|
105ecd6305 | ||
|
|
314040453b | ||
|
|
cbcf5c1d2b | ||
|
|
e881b68ca5 | ||
|
|
f54c69a664 | ||
|
|
319281c096 | ||
|
|
7dee8c0604 | ||
|
|
efbcbc5deb | ||
|
|
c742518612 | ||
|
|
6a0ed46413 | ||
|
|
5ea71bc89b | ||
|
|
84701e90dc | ||
|
|
34ed5ddc4c | ||
|
|
9a8cd4b664 | ||
|
|
2a0b06ca96 | ||
|
|
9c70fc5007 | ||
|
|
b24b659124 | ||
|
|
7ad5acef34 | ||
|
|
304a3f1d5a | ||
|
|
86a58e9ff3 | ||
|
|
d7d722b27b | ||
|
|
d439165dd2 | ||
|
|
65356051f8 | ||
|
|
9728b64edb | ||
|
|
7e71d355ba | ||
|
|
fe9f40e847 | ||
|
|
28f0a1de56 | ||
|
|
b8589a54aa | ||
|
|
0d05803462 | ||
|
|
69d125ad24 | ||
|
|
7631a25f4b | ||
|
|
f41f9d33c8 | ||
|
|
3475255444 | ||
|
|
bcc5c95bd6 | ||
|
|
15fe66bdf3 | ||
|
|
8ce0209e9a | ||
|
|
c7c19d1c2b | ||
|
|
f36146ef24 | ||
|
|
edae956742 | ||
|
|
3f2890661c |
@@ -1,19 +1,12 @@
|
|||||||
# bch-api
|
# 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.
|
||||||
|
|
||||||
[](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.
|
|
||||||
|
|
||||||
This repository is intended to be paired with [bch-js](https://github.com/christroutner/bch-js),
|
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).
|
||||||
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).
|
|
||||||
|
|
||||||
- [API Documentation](https://fullstack.cash/documentation)
|
- [API Documentation](https://fullstack.cash/documentation)
|
||||||
- [Example Code](https://fullstack.cash/examples)
|
- [Example Code](https://fullstack.cash/examples)
|
||||||
@@ -24,32 +17,29 @@ Have questions? Need help? Join our community support:
|
|||||||
## Features
|
## Features
|
||||||
The following features set this repository apart from rest.bitcoin.com:
|
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
|
- 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).
|
[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.
|
||||||
- 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.
|
|
||||||
- Typescript removed and ES8 JavaScript used instead.
|
- Typescript removed and ES8 JavaScript used instead.
|
||||||
- npm audit run on all dependencies.
|
- npm audit run on all dependencies.
|
||||||
- [Greenkeeper](https://greenkeeper.io/) implemented for automatic dependency management
|
|
||||||
and security updates.
|
|
||||||
|
|
||||||
## Live Demo
|
## Live Demo
|
||||||
You can test a live demo of the REST API by running the
|
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).
|
[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).
|
Rate limits are 20 requests per minute, but you can increase them to 100 with a [paid account](https://fullstack.cash/pricing).
|
||||||
This is fast enough to try out the examples
|
You can bootstrap your own REST API server by downloading and installing the infrastructure listed on the [CashStrap](https://fullstack.cash/cashstrap) page.
|
||||||
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).
|
|
||||||
|
|
||||||
- Mainnet REST API server: https://api.fullstack.cash/v3/
|
### Configure bch-js
|
||||||
- Testnet REST API server: https://tapi.fullstack.cash/v3/
|
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
|
- Check server status: https://metrics.fullstack.cash
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
There are two installation paths, depending if you want a *development* or
|
There are two installation paths, depending if you want a *development* or
|
||||||
*production* environment. You'll also need to set up the underlying infrastructure
|
*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.
|
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:
|
- 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:
|
- Install dependencies:
|
||||||
|
|
||||||
@@ -93,5 +83,10 @@ installation.
|
|||||||
Have questions? Need help? Join our community support
|
Have questions? Need help? Join our community support
|
||||||
[Telegram channel](https://t.me/bch_js_toolkit)
|
[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
|
## License
|
||||||
[MIT](./LICENSE.md)
|
[MIT](./LICENSE.md)
|
||||||
|
|||||||
@@ -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.
|
# Allow node.js to make network calls to https using self-signed certificate.
|
||||||
export NODE_TLS_REJECT_UNAUTHORIZED=0
|
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_PORT=6379
|
||||||
export REDIS_HOST=172.17.0.1
|
export REDIS_HOST=172.17.0.1
|
||||||
|
|
||||||
# JWT Token Secret
|
# JWT Token Secret
|
||||||
export TOKENSECRET=somelongsecretvalue
|
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
|
npm start
|
||||||
|
|||||||
@@ -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.
|
# Allow node.js to make network calls to https using self-signed certificate.
|
||||||
export NODE_TLS_REJECT_UNAUTHORIZED=0
|
export NODE_TLS_REJECT_UNAUTHORIZED=0
|
||||||
|
|
||||||
|
# Mainnet Fulcrum / ElectrumX
|
||||||
|
export FULCRUM_URL=172.17.0.1
|
||||||
|
export FULCRUM_PORT=50002
|
||||||
|
|
||||||
# Redis DB
|
# Redis DB
|
||||||
export REDIS_PORT=6380
|
export REDIS_PORT=6380
|
||||||
export REDIS_HOST=172.17.0.1
|
export REDIS_HOST=172.17.0.1
|
||||||
@@ -21,4 +25,10 @@ export REDIS_HOST=172.17.0.1
|
|||||||
# JWT Token Secret
|
# JWT Token Secret
|
||||||
export TOKENSECRET=somelongsecretvalue
|
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
|
npm start
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
+1
-1
@@ -17,7 +17,7 @@
|
|||||||
"test": "npm run lint && npm run test-v3",
|
"test": "npm run lint && npm run test-v3",
|
||||||
"lint": "standard --env mocha --fix",
|
"lint": "standard --env mocha --fix",
|
||||||
"test-v3": "export NETWORK=mainnet && nyc --reporter=text mocha --timeout 60000 test/v3/",
|
"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": "export NETWORK=mainnet && export TEST=integration && mocha --timeout 25000 test/v3/integration/price.js",
|
||||||
"test:integration": "mocha test/v3/integration",
|
"test:integration": "mocha test/v3/integration",
|
||||||
"test:integration:slpdb": "mocha --timeout 25000 -g '#validate2Single' test/v3/integration/slp*.js",
|
"test:integration:slpdb": "mocha --timeout 25000 -g '#validate2Single' test/v3/integration/slp*.js",
|
||||||
"coverage": "nyc report --reporter=text-lcov | coveralls",
|
"coverage": "nyc report --reporter=text-lcov | coveralls",
|
||||||
|
|||||||
+55
-49
@@ -22,9 +22,9 @@
|
|||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
const passport = require('passport')
|
const passport = require('passport')
|
||||||
// const BasicStrategy = require('passport-http').BasicStrategy
|
const BasicStrategy = require('passport-http').BasicStrategy
|
||||||
const AnonymousStrategy = require('passport-anonymous')
|
const AnonymousStrategy = require('passport-anonymous')
|
||||||
// const wlogger = require('../util/winston-logging')
|
const wlogger = require('../util/winston-logging')
|
||||||
|
|
||||||
// Used for debugging and iterrogating JS objects.
|
// Used for debugging and iterrogating JS objects.
|
||||||
const util = require('util')
|
const util = require('util')
|
||||||
@@ -33,9 +33,11 @@ util.inspect.defaultOptions = { depth: 1 }
|
|||||||
// let _this
|
// let _this
|
||||||
|
|
||||||
// Set default rate limit value for testing
|
// 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 ':'.
|
// 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}`)
|
// wlogger.verbose(`PRO_PASS set to: ${PRO_PASS}`)
|
||||||
|
|
||||||
@@ -47,56 +49,60 @@ class AuthMW {
|
|||||||
// Initialize passport for 'anonymous' authentication.
|
// Initialize passport for 'anonymous' authentication.
|
||||||
passport.use(new AnonymousStrategy())
|
passport.use(new AnonymousStrategy())
|
||||||
|
|
||||||
|
console.log(`PRO_PASS: ${JSON.stringify(PRO_PASS, null, 2)}`)
|
||||||
|
|
||||||
// Initialize passport for 'basic' authentication.
|
// Initialize passport for 'basic' authentication.
|
||||||
// passport.use(
|
passport.use(
|
||||||
// new BasicStrategy({ passReqToCallback: true }, function (
|
new BasicStrategy({ passReqToCallback: true }, function (
|
||||||
// req,
|
req,
|
||||||
// username,
|
username,
|
||||||
// password,
|
password,
|
||||||
// done
|
done
|
||||||
// ) {
|
) {
|
||||||
// // console.log(`req: ${util.inspect(req)}`)
|
// console.log(`req: ${util.inspect(req)}`)
|
||||||
// // console.log(`username: ${username}`)
|
// console.log(`username: ${username}`)
|
||||||
// // console.log(`password: ${password}`)
|
// console.log(`password: ${password}`)
|
||||||
//
|
|
||||||
// // Create the req.locals property if it does not yet exist.
|
// Create the req.locals property if it does not yet exist.
|
||||||
// if (!req.locals) {
|
if (!req.locals) {
|
||||||
// req.locals = {
|
req.locals = {
|
||||||
// // default values
|
// default values
|
||||||
// proLimit: false,
|
proLimit: false,
|
||||||
// apiLevel: 0
|
apiLevel: 0
|
||||||
// }
|
}
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// // Set pro-tier rate limit to flag to false by default.
|
// Set pro-tier rate limit to flag to false by default.
|
||||||
// req.locals.proLimit = false
|
req.locals.proLimit = false
|
||||||
//
|
|
||||||
// // Evaluate the username and password and set the rate limit accordingly.
|
// Evaluate the username and password and set the rate limit accordingly.
|
||||||
// // if (username === "BITBOX" && password === PRO_PASS) {
|
// if (username === "BITBOX" && password === PRO_PASS) {
|
||||||
// if (username === 'BITBOX') {
|
if (username === 'fullstackcash') {
|
||||||
// for (let i = 0; i < PRO_PASS.length; i++) {
|
for (let i = 0; i < PRO_PASS.length; i++) {
|
||||||
// const thisPass = PRO_PASS[i]
|
const thisPass = PRO_PASS[i]
|
||||||
//
|
|
||||||
// if (password === thisPass) {
|
if (password === thisPass) {
|
||||||
// wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
|
wlogger.verbose(`${req.url} called by ${password.slice(0, 6)}`)
|
||||||
//
|
|
||||||
// // Success
|
// Success
|
||||||
// req.locals.proLimit = true
|
req.locals.proLimit = true
|
||||||
// break
|
console.log(`User ${req.ip} authenticated using Basic Auth`)
|
||||||
// }
|
break
|
||||||
// }
|
}
|
||||||
// }
|
}
|
||||||
//
|
}
|
||||||
// // console.log(`req.locals: ${util.inspect(req.locals)}`)
|
|
||||||
//
|
// console.log(`req.locals: ${util.inspect(req.locals)}`)
|
||||||
// return done(null, true)
|
|
||||||
// })
|
return done(null, true)
|
||||||
// )
|
})
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Middleware called by the route.
|
// Middleware called by the route.
|
||||||
mw () {
|
mw () {
|
||||||
return passport.authenticate(['anonymous'], {
|
console.log('Initializing passport')
|
||||||
|
return passport.authenticate(['basic', 'anonymous'], {
|
||||||
session: false
|
session: false
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,10 +12,12 @@
|
|||||||
|
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
|
const jwt = require('jsonwebtoken')
|
||||||
|
|
||||||
const wlogger = require('../util/winston-logging')
|
const wlogger = require('../util/winston-logging')
|
||||||
const config = require('../../config')
|
const config = require('../../config')
|
||||||
|
|
||||||
const jwt = require('jsonwebtoken')
|
const ANON_LIMITS = 50
|
||||||
|
|
||||||
// Redis
|
// Redis
|
||||||
const redisOptions = {
|
const redisOptions = {
|
||||||
@@ -111,76 +113,81 @@ class RateLimits {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Default value is 50 points per request = 20 RPM
|
// 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:
|
// Only evaluate the JWT token if the user is not using Basic Authentication.
|
||||||
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
|
if (!req.locals.proLimit) {
|
||||||
try {
|
// Code here for the rate limiter is adapted from this example:
|
||||||
// The resource being consumed: full node, indexer, SLPDB, etc.
|
// https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
|
||||||
const resource = _this.getResource(req.url)
|
try {
|
||||||
wlogger.debug(`resource: ${resource}`)
|
// The resource being consumed: full node, indexer, SLPDB, etc.
|
||||||
|
const resource = _this.getResource(req.url)
|
||||||
|
wlogger.debug(`resource: ${resource}`)
|
||||||
|
|
||||||
let key = userId || req.ip
|
let key = userId || req.ip
|
||||||
res.locals.key = key // Feedback for tests.
|
res.locals.key = key // Feedback for tests.
|
||||||
|
|
||||||
// const pointsToConsume = userId ? 1 : 30
|
// const pointsToConsume = userId ? 1 : 30
|
||||||
decoded.resource = resource
|
decoded.resource = resource
|
||||||
let pointsToConsume = _this.calcPoints(decoded)
|
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
|
|
||||||
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
|
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) {
|
} catch (err) {
|
||||||
wlogger.error('Error in route-ratelimit.js/newRateLimit(): ', 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
|
// Calculates the points consumed, based on the jwt information and the route
|
||||||
// requested.
|
// requested.
|
||||||
calcPoints (jwtInfo) {
|
calcPoints (jwtInfo) {
|
||||||
let retVal = 50 // By default, use anonymous tier.
|
let retVal = ANON_LIMITS // By default, use anonymous tier.
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// console.log(`jwtInfo: ${JSON.stringify(jwtInfo, null, 2)}`)
|
// console.log(`jwtInfo: ${JSON.stringify(jwtInfo, null, 2)}`)
|
||||||
@@ -212,12 +219,12 @@ class RateLimits {
|
|||||||
if (level40Routes.includes(resource)) {
|
if (level40Routes.includes(resource)) {
|
||||||
if (apiLevel >= 40) retVal = 10
|
if (apiLevel >= 40) retVal = 10
|
||||||
// else if (apiLevel >= 10) retVal = 10
|
// else if (apiLevel >= 10) retVal = 10
|
||||||
else retVal = 50
|
else retVal = ANON_LIMITS
|
||||||
|
|
||||||
// Normal indexer routes
|
// Normal indexer routes
|
||||||
} else if (level30Routes.includes(resource)) {
|
} else if (level30Routes.includes(resource)) {
|
||||||
if (apiLevel >= 30) retVal = 10
|
if (apiLevel >= 30) retVal = 10
|
||||||
else retVal = 50
|
else retVal = ANON_LIMITS
|
||||||
|
|
||||||
// Full node tier
|
// Full node tier
|
||||||
} else if (apiLevel >= 20) {
|
} else if (apiLevel >= 20) {
|
||||||
@@ -225,7 +232,7 @@ class RateLimits {
|
|||||||
|
|
||||||
// Free tier, full node only.
|
// Free tier, full node only.
|
||||||
} else {
|
} else {
|
||||||
retVal = 50
|
retVal = ANON_LIMITS
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,7 +240,7 @@ class RateLimits {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
wlogger.error('Error in route-ratelimit.js/calcPoints()')
|
wlogger.error('Error in route-ratelimit.js/calcPoints()')
|
||||||
// throw err
|
// throw err
|
||||||
retVal = 50
|
retVal = ANON_LIMITS
|
||||||
}
|
}
|
||||||
|
|
||||||
return retVal
|
return retVal
|
||||||
|
|||||||
@@ -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) {
|
async balanceSingle (req, res, next) {
|
||||||
try {
|
try {
|
||||||
const address = req.params.address
|
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
|
// POST handler for bulk queries on address details
|
||||||
async balanceBulk (req, res, next) {
|
async balanceBulk (req, res, next) {
|
||||||
try {
|
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
|
// GET handler for single balance
|
||||||
async utxosSingle (req, res, next) {
|
async utxosSingle (req, res, next) {
|
||||||
try {
|
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
|
// POST handler for bulk queries on address utxos
|
||||||
async utxosBulk (req, res, next) {
|
async utxosBulk (req, res, next) {
|
||||||
try {
|
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.
|
// GET handler for single transaction details.
|
||||||
async txSingle (req, res, next) {
|
async txSingle (req, res, next) {
|
||||||
try {
|
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
|
// POST handler for bulk queries on tx details
|
||||||
async txBulk (req, res, next) {
|
async txBulk (req, res, next) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -79,6 +79,21 @@ class Electrum {
|
|||||||
// Set the connection flag.
|
// Set the connection flag.
|
||||||
_this.isReady = true
|
_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('...Successfully connected to ElectrumX server.')
|
||||||
|
|
||||||
// console.log(`_this.isReady: ${_this.isReady}`)
|
// console.log(`_this.isReady: ${_this.isReady}`)
|
||||||
@@ -96,6 +111,9 @@ class Electrum {
|
|||||||
// Return immediately if the isReady flag is false.
|
// Return immediately if the isReady flag is false.
|
||||||
if (!_this.isReady) return true
|
if (!_this.isReady) return true
|
||||||
|
|
||||||
|
// Disable the reconnect timer.
|
||||||
|
clearInterval(_this.reconnectIntervalHandle)
|
||||||
|
|
||||||
// Disconnect from the server.
|
// Disconnect from the server.
|
||||||
await _this.electrumx.disconnect()
|
await _this.electrumx.disconnect()
|
||||||
|
|
||||||
|
|||||||
+39
-2
@@ -24,11 +24,14 @@ class Price {
|
|||||||
this.routeUtils = routeUtils
|
this.routeUtils = routeUtils
|
||||||
|
|
||||||
this.priceUrl = 'https://api.coinbase.com/v2/exchange-rates?currency=BCH'
|
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 = express.Router()
|
||||||
this.router.get('/', _this.root)
|
this.router.get('/', _this.root)
|
||||||
this.router.get('/usd', _this.getUSD)
|
this.router.get('/usd', _this.getUSD)
|
||||||
this.router.get('/rates', _this.getBCHRate)
|
this.router.get('/rates', _this.getBCHRate)
|
||||||
|
this.router.get('/bchausd', _this.getBCHAUSD)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DRY error handler.
|
// DRY error handler.
|
||||||
@@ -53,7 +56,7 @@ class Price {
|
|||||||
* @api {get} /price/usd Get the USD price of BCH
|
* @api {get} /price/usd Get the USD price of BCH
|
||||||
* @apiName Get the USD price of BCH
|
* @apiName Get the USD price of BCH
|
||||||
* @apiGroup Price
|
* @apiGroup Price
|
||||||
* @apiDescription Get the USD price of BCH
|
* @apiDescription Get the USD price of BCH from Coinbase.
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
* @apiExample Example usage:
|
* @apiExample Example usage:
|
||||||
@@ -85,7 +88,7 @@ class Price {
|
|||||||
* @api {get} /price/usd Get rates for several different currencies
|
* @api {get} /price/usd Get rates for several different currencies
|
||||||
* @apiName Get rates for several different currencies
|
* @apiName Get rates for several different currencies
|
||||||
* @apiGroup Price
|
* @apiGroup Price
|
||||||
* @apiDescription Get rates for several different currencies
|
* @apiDescription Get rates for several different currencies from Coinbase.
|
||||||
*
|
*
|
||||||
*
|
*
|
||||||
* @apiExample Example usage:
|
* @apiExample Example usage:
|
||||||
@@ -113,6 +116,40 @@ class Price {
|
|||||||
return _this.errorHandler(err, res)
|
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
|
module.exports = Price
|
||||||
|
|||||||
+21
-2
@@ -1251,7 +1251,9 @@ class Slp {
|
|||||||
const tokenRes = await _this.axios.request(opt)
|
const tokenRes = await _this.axios.request(opt)
|
||||||
// console.log(`tokenRes: ${util.inspect(tokenRes)}`)
|
// 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)
|
res.status(404)
|
||||||
return res.json({ error: 'TXID not found' })
|
return res.json({ error: 'TXID not found' })
|
||||||
}
|
}
|
||||||
@@ -1437,12 +1439,29 @@ class Slp {
|
|||||||
sendOutputs.push(string.toString())
|
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 = {
|
const obj = {
|
||||||
tokenInfo: {
|
tokenInfo: {
|
||||||
versionType: transaction.slp.detail.versionType,
|
versionType: transaction.slp.detail.versionType,
|
||||||
|
tokenName: transaction.slp.detail.name,
|
||||||
|
tokenTicker: transaction.slp.detail.symbol,
|
||||||
transactionType: transaction.slp.detail.transactionType,
|
transactionType: transaction.slp.detail.transactionType,
|
||||||
tokenIdHex: transaction.slp.detail.tokenIdHex,
|
tokenIdHex: transaction.slp.detail.tokenIdHex,
|
||||||
sendOutputs: sendOutputs
|
sendOutputs: sendOutputs,
|
||||||
|
sendInputsFull: sendInputs,
|
||||||
|
sendOutputsFull: transaction.slp.detail.outputs
|
||||||
},
|
},
|
||||||
tokenIsValid: transaction.slp.valid
|
tokenIsValid: transaction.slp.valid
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,4 +20,13 @@ export FULCRUM_PORT=50002
|
|||||||
|
|
||||||
export TOKENSECRET=somelongpassword
|
export TOKENSECRET=somelongpassword
|
||||||
|
|
||||||
|
# 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/
|
||||||
|
|
||||||
|
# Basic Authentication password
|
||||||
|
export PRO_PASS=somerandomepassword:someotherrandompassword:aThirdPassword
|
||||||
|
|
||||||
npm start
|
npm start
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ function expectRouteError (res, result, expectedError, code = 400) {
|
|||||||
assert.equal(result.success, false)
|
assert.equal(result.success, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('#ElectrumX Router', () => {
|
describe('#Electrumx', () => {
|
||||||
let req, res
|
let req, res
|
||||||
let sandbox
|
let sandbox
|
||||||
const electrumxRoute = new ElecrumxRoute()
|
const electrumxRoute = new ElecrumxRoute()
|
||||||
|
|||||||
@@ -821,6 +821,7 @@ describe('#BlockchainRouter', () => {
|
|||||||
])
|
])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('getRawMempool()', () => {
|
describe('getRawMempool()', () => {
|
||||||
it('should throw 503 when network issues', async () => {
|
it('should throw 503 when network issues', async () => {
|
||||||
// Save the existing RPC URL.
|
// Save the existing RPC URL.
|
||||||
@@ -842,6 +843,7 @@ describe('#BlockchainRouter', () => {
|
|||||||
'Error message expected'
|
'Error message expected'
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('returns proper error when downstream service stalls', async () => {
|
it('returns proper error when downstream service stalls', async () => {
|
||||||
// Mock the timeout error.
|
// Mock the timeout error.
|
||||||
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
|
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNABORTED' })
|
||||||
@@ -856,6 +858,7 @@ describe('#BlockchainRouter', () => {
|
|||||||
'Error message expected'
|
'Error message expected'
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
it('returns proper error when downstream service is down', async () => {
|
it('returns proper error when downstream service is down', async () => {
|
||||||
// Mock the timeout error.
|
// Mock the timeout error.
|
||||||
sandbox.stub(uut.axios, 'request').throws({ code: 'ECONNREFUSED' })
|
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.
|
// Mock the RPC call for unit tests.
|
||||||
if (process.env.TEST === 'unit') {
|
if (process.env.TEST === 'unit') {
|
||||||
sandbox
|
sandbox
|
||||||
@@ -886,6 +889,7 @@ describe('#BlockchainRouter', () => {
|
|||||||
// Not sure what other assertions should be made here.
|
// Not sure what other assertions should be made here.
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('getMempoolEntrySingle()', () => {
|
describe('getMempoolEntrySingle()', () => {
|
||||||
it('should throw 400 if txid is empty', async () => {
|
it('should throw 400 if txid is empty', async () => {
|
||||||
const result = await uut.getMempoolEntrySingle(req, res)
|
const result = await uut.getMempoolEntrySingle(req, res)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
'use strict'
|
'use strict'
|
||||||
|
|
||||||
// const assert = require('chai').assert
|
const assert = require('chai').assert
|
||||||
// const axios = require('axios')
|
// const axios = require('axios')
|
||||||
|
|
||||||
// Used for debugging.
|
// Used for debugging.
|
||||||
@@ -29,6 +29,17 @@ describe('#price', () => {
|
|||||||
it('should get the USD price', async () => {
|
it('should get the USD price', async () => {
|
||||||
const result = await price.getUSD(req, res)
|
const result = await price.getUSD(req, res)
|
||||||
console.log(`result: ${util.inspect(result)}`)
|
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)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
/*
|
/*
|
||||||
This integration tests should be run against a live bch-api REST server. It
|
These tests have been deprecated. To test bch-api rate limits, run the e2e
|
||||||
tests to ensure the rate-limits are working as expected. Adjust the values
|
tests in the bch-js repository.
|
||||||
in the tests below to match the rate limit setting in your own installation.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'use strict'
|
'use strict'
|
||||||
@@ -17,11 +16,11 @@ util.inspect.defaultOptions = { depth: 1 }
|
|||||||
// const SERVER = `http://192.168.0.36:12400/v3/`
|
// const SERVER = `http://192.168.0.36:12400/v3/`
|
||||||
const SERVER = 'http://localhost:3000/v3/'
|
const SERVER = 'http://localhost:3000/v3/'
|
||||||
// const SERVER = 'https://api.fullstack.cash/v3/'
|
// const SERVER = 'https://api.fullstack.cash/v3/'
|
||||||
|
//
|
||||||
|
// const TEST_JWT =
|
||||||
|
// 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
|
||||||
|
|
||||||
const TEST_JWT =
|
describe('#JWT rate limits', () => {
|
||||||
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
|
|
||||||
|
|
||||||
describe('#rate limits', () => {
|
|
||||||
it('should get control/getNetworkInfo() with no auth', async () => {
|
it('should get control/getNetworkInfo() with no auth', async () => {
|
||||||
const options = {
|
const options = {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
@@ -36,25 +35,24 @@ describe('#rate limits', () => {
|
|||||||
assert.hasAnyKeys(result.data, ['version'])
|
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 {
|
try {
|
||||||
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
|
|
||||||
const options = {
|
const options = {
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
url: `${SERVER}control/getNetworkInfo`
|
url: `${SERVER}control/getNetworkInfo`
|
||||||
}
|
}
|
||||||
|
|
||||||
const promises = []
|
const promises = []
|
||||||
for (let i = 0; i < 5; i++) {
|
for (let i = 0; i < 30; i++) {
|
||||||
const promise = axios(options)
|
const promise = axios(options)
|
||||||
promises.push(promise)
|
promises.push(promise)
|
||||||
}
|
}
|
||||||
|
|
||||||
await Promise.all(promises)
|
await Promise.all(promises)
|
||||||
|
|
||||||
assert.equal(true, false, 'Unexpected result!')
|
assert.fail('Unexpected result!')
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// console.log(`err.response: ${util.inspect(err.response)}`)
|
console.log('err: ', err)
|
||||||
|
|
||||||
assert.equal(err.response.status, 429)
|
assert.equal(err.response.status, 429)
|
||||||
assert.include(err.response.data.error, 'Too many requests')
|
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 () => {
|
// it('should unlock pro-tier for a valid JWT token', async () => {
|
||||||
try {
|
// try {
|
||||||
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
|
// // Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
|
||||||
const options = {
|
// const options = {
|
||||||
method: 'GET',
|
// method: 'GET',
|
||||||
url: `${SERVER}control/`,
|
// url: `${SERVER}control/`,
|
||||||
headers: {
|
// headers: {
|
||||||
Authorization: `Token ${TEST_JWT}`
|
// Authorization: `Token ${TEST_JWT}`
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
const promises = []
|
// const promises = []
|
||||||
for (let i = 0; i < 60; i++) {
|
// for (let i = 0; i < 60; i++) {
|
||||||
const promise = axios(options)
|
// const promise = axios(options)
|
||||||
promises.push(promise)
|
// promises.push(promise)
|
||||||
}
|
// }
|
||||||
|
//
|
||||||
await Promise.all(promises)
|
// await Promise.all(promises)
|
||||||
|
//
|
||||||
// assert.equal(true, false, "Unexpected result!")
|
// // assert.equal(true, false, "Unexpected result!")
|
||||||
assert.equal(true, true, 'Not throwing an error is a pass!')
|
// assert.equal(true, true, 'Not throwing an error is a pass!')
|
||||||
} catch (err) {
|
// } catch (err) {
|
||||||
console.log(`err.response: ${util.inspect(err.response)}`)
|
// console.log(`err.response: ${util.inspect(err.response)}`)
|
||||||
|
//
|
||||||
assert.equal(true, false, 'Unexpected result!')
|
// assert.equal(true, false, 'Unexpected result!')
|
||||||
}
|
// }
|
||||||
// Override default timeout for this test.
|
// // Override default timeout for this test.
|
||||||
}).timeout(20000)
|
// }).timeout(20000)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -216,6 +216,26 @@ const mockCoinbaseFeed = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = {
|
const mockCoinexFeed = {
|
||||||
mockCoinbaseFeed
|
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
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -211,4 +211,70 @@ describe('#PriceRouter', () => {
|
|||||||
assert.property(result, 'error')
|
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)
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user