mirror of
https://github.com/fullstack-cash/bch-api.git
synced 2026-09-22 09:12:05 -07:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86a58e9ff3 | ||
|
|
d7d722b27b | ||
|
|
d439165dd2 | ||
|
|
65356051f8 | ||
|
|
9728b64edb | ||
|
|
7e71d355ba | ||
|
|
fe9f40e847 | ||
|
|
28f0a1de56 | ||
|
|
b8589a54aa | ||
|
|
0d05803462 | ||
|
|
69d125ad24 | ||
|
|
7631a25f4b | ||
|
|
f41f9d33c8 | ||
|
|
3475255444 | ||
|
|
bcc5c95bd6 | ||
|
|
15fe66bdf3 | ||
|
|
8ce0209e9a | ||
|
|
c7c19d1c2b | ||
|
|
f36146ef24 | ||
|
|
edae956742 | ||
|
|
3f2890661c | ||
|
|
46c9e00fe1 | ||
|
|
a1c19e8e0a | ||
|
|
fea8546bd2 | ||
|
|
c6d98380b1 |
@@ -25,6 +25,8 @@ start-sweet-main.sh
|
|||||||
test-sweet-main.sh
|
test-sweet-main.sh
|
||||||
test-fullstack-abc.sh
|
test-fullstack-abc.sh
|
||||||
test-fullstack-bchn.sh
|
test-fullstack-bchn.sh
|
||||||
|
start-fullstack-abc.sh
|
||||||
|
start-fullstack-bchn.sh
|
||||||
|
|
||||||
coverage
|
coverage
|
||||||
start-my-infra
|
start-my-infra
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -16,8 +16,9 @@ if [[ $GIT_BRANCH =~ "master" ]]
|
|||||||
|
|
||||||
curl -X POST http://fullstack.cash:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
|
curl -X POST http://fullstack.cash:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
|
||||||
curl -X POST http://fullstack.cash:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
|
curl -X POST http://fullstack.cash:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
|
||||||
curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
|
#curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-testnet -H "Content-Type: application/json" -d $DATA
|
||||||
curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
|
#curl -X POST http://$FREE_SERVER:9000/hooks/bch-api-mainnet -H "Content-Type: application/json" -d $DATA
|
||||||
|
curl -X POST http://$BCHN_BCHAPI:9000/hooks/bch-api-bchn -H "Content-Type: application/json" -d $DATA
|
||||||
|
|
||||||
echo "...Finished deploying to production."
|
echo "...Finished deploying to production."
|
||||||
|
|
||||||
|
|||||||
@@ -24,4 +24,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
|
||||||
|
|||||||
@@ -21,4 +21,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 |
+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
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,74 +113,80 @@ 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 = 50
|
||||||
|
|
||||||
// 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('wallet.fullstack.cash') > -1 ||
|
||||||
|
origin.toString().indexOf('sandbox.fullstack.cash') > -1 ||
|
||||||
|
origin === 'slp-api')
|
||||||
|
) {
|
||||||
|
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)
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -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)
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user