Compare commits

...
24 Commits
Author SHA1 Message Date
Chris Troutner d5433ed811 Merge pull request #39 from Permissionless-Software-Foundation/6-electrum-broadcast
fix(electrumx broadcast): Added body variable. Curl example works now
2020-10-02 13:36:56 -07:00
Chris Troutner 6b2588c487 fix(electrumx broadcast): Added body variable. Curl example works now 2020-10-02 13:33:35 -07:00
Chris Troutner 4aee109223 Merge pull request #35 from Permissionless-Software-Foundation/6-electrum-broadcast
Add POST /tx/broadcast endpoint + tests
2020-10-02 11:08:37 -07:00
Chris Troutner 5f63e53a6d Merge branch 'master' into 6-electrum-broadcast 2020-10-02 08:18:23 -07:00
Chris Troutner bde809d62d Merge pull request #38 from Permissionless-Software-Foundation/ct-unstable
fix(hydrateUtxos): Adding localhost to max rate limit
2020-10-01 20:58:42 -07:00
Chris Troutner c664758654 Fixing bug 2020-10-01 20:51:01 -07:00
Chris Troutner b4823be86a fix(hydrateUtxos): Adding localhost to max rate limit 2020-10-01 20:47:04 -07:00
Chris Troutner 1c9e0858de Merge pull request #37 from Permissionless-Software-Foundation/ct-unstable
fix(hydrateUtxos): Using local calls to the REST API
2020-10-01 20:22:57 -07:00
Chris Troutner 41a3cd91fc fix(hydrateUtxos): Using local calls to the REST API 2020-10-01 20:20:28 -07:00
Chris Troutner 0b4038eeb4 Merge pull request #36 from Permissionless-Software-Foundation/ct-unstable
Ct unstable
2020-10-01 17:38:38 -07:00
Chris Troutner 86bf504b78 Fixing unit tests 2020-10-01 17:34:36 -07:00
Chris Troutner d56e6d6b3a linting 2020-10-01 17:26:31 -07:00
Chris Troutner 7339b8554f fix(basic auth): Disabling Basic Authentication 2020-10-01 17:25:52 -07:00
Rosco Kalis e97a0be456 Remove .only 2020-10-01 06:53:46 -04:00
Rosco Kalis 085618470f Update comments 2020-09-30 20:55:43 -04:00
Rosco Kalis 22d7a2b7a2 Add POST /tx/broadcast endpoint + tests 2020-09-30 20:52:13 -04:00
Chris Troutner e6dcaa2f24 Merge pull request #34 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Fixing hydrateUtxos rate limits
2020-09-28 20:24:43 -07:00
Chris Troutner 698ac38251 fix(rate limits): Fixing hydrateUtxos rate limits 2020-09-28 20:17:07 -07:00
Chris Troutner 7c66ce7f73 Merge pull request #33 from Permissionless-Software-Foundation/ct-unstable
Increasing rate limits for hydrateUtxos()
2020-09-28 19:57:55 -07:00
Chris Troutner 9e3dfd9848 Updating package lock 2020-09-28 19:55:28 -07:00
Chris Troutner 10eb4da112 fix(rate limits): Increasing rate limits for internal calls 2020-09-28 19:49:49 -07:00
Chris Troutner f4f5f02a2f fix(bch-js): bumping to version 3.6.3 2020-09-28 19:45:47 -07:00
Chris Troutner bb69a6dee9 Merge pull request #32 from Permissionless-Software-Foundation/ct-unstable
fix(rate limits): Increasing internal rate limits
2020-09-28 18:35:29 -07:00
Chris Troutner d67b3aa052 fix(rate limits): Increasing internal rate limits 2020-09-28 18:32:43 -07:00
9 changed files with 362 additions and 177 deletions
+3 -3
View File
@@ -366,9 +366,9 @@
} }
}, },
"@psf/bch-js": { "@psf/bch-js": {
"version": "3.6.2", "version": "3.6.3",
"resolved": "https://registry.npmjs.org/@psf/bch-js/-/bch-js-3.6.2.tgz", "resolved": "https://registry.npmjs.org/@psf/bch-js/-/bch-js-3.6.3.tgz",
"integrity": "sha512-6r8NBB48WgWHAFeuwrlkaE3B87TT3o/8hdjU1DOWXUx7lMFIF1Aq25CffUxF3sHP0pSx3/+4ulQZFROHGTwnDQ==", "integrity": "sha512-0nqmLprZU+1lh1WTnAqVHQD+bIPJIcEQ36rBNoyh4ejzWZoQ7pTMj2r2I7JGhWmxWdSQ+g4stT1OrC4qmH6jdw==",
"requires": { "requires": {
"@uppy/core": "^1.10.4", "@uppy/core": "^1.10.4",
"@uppy/tus": "^1.5.12", "@uppy/tus": "^1.5.12",
+1 -1
View File
@@ -28,7 +28,7 @@
"node": ">=10.15.1" "node": ">=10.15.1"
}, },
"dependencies": { "dependencies": {
"@psf/bch-js": "^3.6.2", "@psf/bch-js": "^3.6.3",
"apidoc": "^0.23.0", "apidoc": "^0.23.0",
"axios": "^0.19.0", "axios": "^0.19.0",
"bitcore-lib-cash": "^8.20.3", "bitcore-lib-cash": "^8.20.3",
+49 -49
View File
@@ -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,9 @@ 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 : 'BITBOX'
// 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}`)
@@ -48,55 +48,55 @@ class AuthMW {
passport.use(new AnonymousStrategy()) passport.use(new AnonymousStrategy())
// 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 === 'BITBOX') {
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 // 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(['basic', 'anonymous'], { return passport.authenticate(['anonymous'], {
session: false session: false
}) })
} }
+21 -13
View File
@@ -20,7 +20,7 @@ const redisClient = new Redis(redisOptions)
const { RateLimiterRedis } = require('rate-limiter-flexible') const { RateLimiterRedis } = require('rate-limiter-flexible')
const rateLimitOptions = { const rateLimitOptions = {
storeClient: redisClient, storeClient: redisClient,
points: 100, // Number of points points: 1000, // Number of points
duration: 60 // Per minute (per 60 seconds) duration: 60 // Per minute (per 60 seconds)
} }
@@ -98,8 +98,8 @@ class RateLimits {
wlogger.debug('No JWT token found!') wlogger.debug('No JWT token found!')
} }
// Used for displaying error message. Default value is 3. // Used for displaying error message. Default value is 30.
let rateLimit = 3 let rateLimit = 30
// Code here for the rate limiter is adapted from this example: // 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 // https://github.com/animir/node-rate-limiter-flexible/wiki/Overall-example#authorized-and-not-authorized-users
@@ -129,8 +129,16 @@ class RateLimits {
origin && origin &&
(origin.toString().indexOf('wallet.fullstack.cash') > -1 || (origin.toString().indexOf('wallet.fullstack.cash') > -1 ||
origin.toString().indexOf('sandbox.fullstack.cash') > -1 || origin.toString().indexOf('sandbox.fullstack.cash') > -1 ||
origin.toString().indexOf('172.17.') > -1 ||
origin === 'slp-api') origin === 'slp-api')
) {
pointsToConsume = 10
res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
}
// Apply paid-access rate limits based on key/IP
if (
key.toString().indexOf('172.17.') > -1 ||
key.toString().indexOf('::ffff:127.0.0.1') > -1
) { ) {
pointsToConsume = 1 pointsToConsume = 1
res.locals.pointsToConsume = pointsToConsume // Feedback for tests. res.locals.pointsToConsume = pointsToConsume // Feedback for tests.
@@ -140,7 +148,7 @@ class RateLimits {
`User ${key} consuming ${pointsToConsume} point for resource ${resource}.` `User ${key} consuming ${pointsToConsume} point for resource ${resource}.`
) )
rateLimit = Math.floor(100 / pointsToConsume) rateLimit = Math.floor(1000 / pointsToConsume)
// Update the key so that rate limits track both the user and the resource. // Update the key so that rate limits track both the user and the resource.
key = `${key}-${resource}` key = `${key}-${resource}`
@@ -170,7 +178,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 = 30 // By default, use anonymous tier. let retVal = 300 // By default, use anonymous tier.
try { try {
// console.log(`jwtInfo: ${JSON.stringify(jwtInfo, null, 2)}`) // console.log(`jwtInfo: ${JSON.stringify(jwtInfo, null, 2)}`)
@@ -187,22 +195,22 @@ class RateLimits {
if (jwtInfo.id) { if (jwtInfo.id) {
// SLP indexer routes // SLP indexer routes
if (level40Routes.includes(resource)) { if (level40Routes.includes(resource)) {
if (apiLevel >= 40) retVal = 1 if (apiLevel >= 40) retVal = 10
// else if (apiLevel >= 10) retVal = 10 // else if (apiLevel >= 10) retVal = 10
else retVal = 10 else retVal = 100
// Normal indexer routes // Normal indexer routes
} else if (level30Routes.includes(resource)) { } else if (level30Routes.includes(resource)) {
if (apiLevel >= 30) retVal = 1 if (apiLevel >= 30) retVal = 10
else retVal = 10 else retVal = 100
// Full node tier // Full node tier
} else if (apiLevel >= 20) { } else if (apiLevel >= 20) {
retVal = 1 retVal = 10
// Free tier, full node only. // Free tier, full node only.
} else { } else {
retVal = 10 retVal = 100
} }
} }
@@ -210,7 +218,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 = 30 retVal = 300
} }
return retVal return retVal
+87
View File
@@ -52,6 +52,7 @@ class Electrum {
_this.router.post('/utxos', _this.utxosBulk) _this.router.post('/utxos', _this.utxosBulk)
_this.router.get('/tx/data/:txid', _this.getTransactionDetails) _this.router.get('/tx/data/:txid', _this.getTransactionDetails)
_this.router.post('/tx/data', _this.transactionDetailsBulk) _this.router.post('/tx/data', _this.transactionDetailsBulk)
_this.router.post('/tx/broadcast', _this.broadcastTransaction)
_this.router.get('/block/headers/:height', _this.getBlockHeaders) _this.router.get('/block/headers/:height', _this.getBlockHeaders)
_this.router.post('/block/headers', _this.blockHeadersBulk) _this.router.post('/block/headers', _this.blockHeadersBulk)
_this.router.get('/balance/:address', _this.getBalance) _this.router.get('/balance/:address', _this.getBalance)
@@ -491,6 +492,92 @@ class Electrum {
} }
} }
// Returns a promise that resolves to transaction ID of the broadcasted transaction or an error.
// Expects input to be a txHex string, and input validation to have already
// been done by parent, calling function.
async _broadcastTransactionWithElectrum (txHex) {
try {
if (!_this.isReady) {
throw new Error(
'ElectrumX server connection is not ready. Call await connectToServer() first.'
)
}
// Broadcast the transaction hex to the ElectrumX server.
const electrumResponse = await _this.electrumx.request(
'blockchain.transaction.broadcast',
txHex
)
// console.log(
// `electrumResponse: ${JSON.stringify(electrumResponse, null, 2)}`
// )
return electrumResponse
} catch (err) {
// console.log('err: ', err)
// Write out error to error log.
wlogger.error(
'Error in elecrumx.js/_transactionDetailsFromElectrum(): ',
err
)
throw err
}
}
/**
* @api {post} /electrumx/tx/broadcast Broadcast a raw transaction
* @apiName Broadcast a raw transaction
* @apiGroup ElectrumX / Fulcrum
* @apiDescription Broadcast a raw transaction and return the transaction ID on success or error on failure.
*
* @apiExample Example usage:
* curl -X POST "https://api.fullstack.cash/v3/electrumx/tx/broadcast" -H "accept: application/json" -H "Content-Type: application/json" -d '{"txHex":"020000000265d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667010000006441dd1dd72770cadede1a7fd0363574846c48468a398ddfa41a9677c74cac8d2652b682743725a3b08c6c2021a629011e11a264d9036e9d5311e35b5f4937ca7b4e4121020797d8fd4d2fa6fd7cdeabe2526bfea2b90525d6e8ad506ec4ee3c53885aa309ffffffff65d13ef402840c8a51f39779afb7ae4d49e4b0a3c24a3d0e7742038f2c679667000000006441347d7f218c11c04487c1ad8baac28928fb10e5054cd4494b94d078cfa04ccf68e064fb188127ff656c0b98e9ce87f036d183925d0d0860605877d61e90375f774121028a53f95eb631b460854fc836b2e5d31cad16364b4dc3d970babfbdcc3f2e4954ffffffff035ac355000000000017a914189ce02e332548f4804bac65cba68202c9dbf822878dfd0800000000001976a914285bb350881b21ac89724c6fb6dc914d096cd53b88acf9ef3100000000001976a91445f1f1c4a9b9419a5088a3e9c24a293d7a150e6488ac00000000"}'
*
*/
// POST handler for broadcasting a single transaction
async broadcastTransaction (req, res, next) {
try {
const txHex = req.body.txHex
if (typeof txHex !== 'string') {
res.status(400)
return res.json({
success: false,
error: 'request body must be a string.'
})
}
wlogger.debug(
'Executing electrumx/broadcastTransaction with this tx hex: ',
txHex
)
// Get data from ElectrumX server.
const electrumResponse = await _this._broadcastTransactionWithElectrum(txHex)
// console.log(`_utxosFromElectrumx(): ${JSON.stringify(electrumResponse, null, 2)}`)
// Pass the error message if ElectrumX reports an error.
if (electrumResponse instanceof Error) {
res.status(400)
return res.json({
success: false,
error: electrumResponse.message
})
}
res.status(200)
return res.json({
success: true,
txid: electrumResponse
})
} catch (err) {
wlogger.error('Error in electrumx.js/broadcastTransaction().', err)
return _this.errorHandler(err, res)
}
}
// Returns a promise that resolves to block header data for a block height. // Returns a promise that resolves to block header data for a block height.
// Expects input to be a height number, and input validation to have already // Expects input to be a height number, and input validation to have already
// been done by parent, calling function. // been done by parent, calling function.
+4 -1
View File
@@ -13,8 +13,11 @@ const Slpdb = require('./services/slpdb')
// const strftime = require('strftime') // const strftime = require('strftime')
const wlogger = require('../../util/winston-logging') const wlogger = require('../../util/winston-logging')
const LOCAL_RESTURL = process.env.LOCAL_RESTURL
? process.env.LOCAL_RESTURL
: 'https://api.fullstack.cash/v3/'
const BCHJS = require('@psf/bch-js') const BCHJS = require('@psf/bch-js')
const bchjs = new BCHJS() const bchjs = new BCHJS({ restURL: LOCAL_RESTURL })
// Used to convert error messages to strings, to safely pass to users. // Used to convert error messages to strings, to safely pass to users.
const util = require('util') const util = require('util')
+86
View File
@@ -906,6 +906,92 @@ describe('#ElectrumX Router', () => {
}) })
}) })
describe('#_broadcastTransactionWithElectrum', () => {
it('should return error object for invalid formatted transaction', async () => {
const invalidHex = mockData.txDetails.hex.substring(10)
stubMethodForUnitTests(
electrumxRoute.electrumx,
'request',
new Error('Error: the transaction was rejected by network rules.\n\nTX decode failed\n')
)
const result = await electrumxRoute._broadcastTransactionWithElectrum(invalidHex)
assert.instanceOf(result, Error)
assert.include(result.message, 'TX decode failed')
})
it('should return txid for valid transaction', async function () {
// We cannot send an actual broadcast transaction to mainnet
if (process.env.TEST !== 'unit') return this.skip()
const validHex = mockData.txDetails.hex
stubMethodForUnitTests(
electrumxRoute.electrumx,
'request',
mockData.txDetails.hash
)
const result = await electrumxRoute._broadcastTransactionWithElectrum(validHex)
assert.typeOf(result, 'string')
assert.equal(result, mockData.txDetails.hash)
})
})
describe('#broadcastTransaction', () => {
it('should throw an error for a non-string', async () => {
req.body = 456
stubMethodForUnitTests(
electrumxRoute,
'_broadcastTransactionWithElectrum',
new Error('request body must be a string.')
)
const result = await electrumxRoute.broadcastTransaction(req, res)
expectRouteError(res, result, 'request body must be a string.')
})
it('should throw an error object for invalid formatted transaction', async () => {
req.body.txHex = mockData.txDetails.hex.substring(10)
stubMethodForUnitTests(
electrumxRoute,
'_broadcastTransactionWithElectrum',
new Error('Error: the transaction was rejected by network rules.\n\nTX decode failed\n')
)
const result = await electrumxRoute.broadcastTransaction(req, res)
expectRouteError(res, result, 'TX decode failed')
})
it('should return txid for valid transaction', async function () {
// We cannot send an actual broadcast transaction to mainnet
if (process.env.TEST !== 'unit') return this.skip()
req.body.txHex = mockData.txDetails.hex
stubMethodForUnitTests(
electrumxRoute,
'_broadcastTransactionWithElectrum',
mockData.txDetails.hash
)
const result = await electrumxRoute.broadcastTransaction(req, res)
assert.property(result, 'success')
assert.equal(result.success, true)
assert.property(result, 'txid')
assert.equal(result.txid, mockData.txDetails.hash)
})
})
describe('#_balanceFromElectrumx', () => { describe('#_balanceFromElectrumx', () => {
it('should throw error for invalid address', async () => { it('should throw error for invalid address', async () => {
try { try {
+76 -75
View File
@@ -16,9 +16,10 @@ 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 TEST_JWT = const TEST_JWT =
'eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlM2EwNDE1ZWIyOWE5NjJkYTI3MDhiNCIsImFwaUxldmVsIjowLCJyYXRlTGltaXQiOjEwLCJpYXQiOjE1ODA4NjA0NjcsImV4cCI6MTU4MzQ1MjQ2N30.fuY5S-YrF0J11h5uyMjPe7wiVkYRnIyXi4dL9-V-C6pLJm33p0dSq_pSheVVWw78n5kAvL_9kFHngbnmQiOJYQ' 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlODhhY2JmMDIyMWMxMDAxMmFkOTNmZiIsImVtYWlsIjoiY2hyaXMudHJvdXRuZXJAZ21haWwuY29tIiwiYXBpTGV2ZWwiOjQwLCJyYXRlTGltaXQiOjMsImlhdCI6MTYwMDYyODk1MSwiZXhwIjoxNjAzMjIwOTUxfQ.JPXDJQsxJFtCGZjHOd-hRfJuY41Ef_FQ4ET06CtYdNk'
describe('#rate limits', () => { describe('#rate limits', () => {
it('should get control/getNetworkInfo() with no auth', async () => { it('should get control/getNetworkInfo() with no auth', async () => {
@@ -35,7 +36,7 @@ describe('#rate limits', () => {
assert.hasAnyKeys(result.data, ['version']) assert.hasAnyKeys(result.data, ['version'])
}) })
it('should trigger rate-limit handler if rate limits exceeds 30 request per minute', async () => { it('should trigger rate-limit handler if rate limits exceeds 5 request per minute', 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 = {
@@ -44,7 +45,7 @@ describe('#rate limits', () => {
} }
const promises = [] const promises = []
for (let i = 0; i < 30; i++) { for (let i = 0; i < 5; i++) {
const promise = axios(options) const promise = axios(options)
promises.push(promise) promises.push(promise)
} }
@@ -60,79 +61,79 @@ describe('#rate limits', () => {
} }
}) })
it('should not trigger rate-limit handler if correct pro-tier password is used', async () => { // it('should not trigger rate-limit handler if correct pro-tier password is used', async () => {
try { // try {
const username = 'BITBOX' // const username = 'BITBOX'
//
// // Pro-tier is accessed by using the right password.
// const password = 'BITBOX'
// // const password = "something"
//
// const combined = `${username}:${password}`
// const base64Credential = Buffer.from(combined).toString('base64')
// const readyCredential = `Basic ${base64Credential}`
//
// const options = {
// method: 'GET',
// url: `${SERVER}control/getNetworkInfo`,
// headers: { Authorization: readyCredential }
// }
//
// const promises = []
// for (let i = 0; i < 30; i++) {
// const promise = axios(options)
// promises.push(promise)
// }
//
// await Promise.all(promises)
//
// 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,
// 'This error handler should not have been triggered. Is the password correct?'
// )
// }
// })
// Pro-tier is accessed by using the right password. // it('should trigger rate-limit handler if rate limits exceeds pro-tier limit', async () => {
const password = 'BITBOX' // try {
// const password = "something" // const username = 'BITBOX'
//
const combined = `${username}:${password}` // // Pro-tier is accessed by using the right password.
const base64Credential = Buffer.from(combined).toString('base64') // const password = 'BITBOX'
const readyCredential = `Basic ${base64Credential}` // // const password = "something"
//
const options = { // const combined = `${username}:${password}`
method: 'GET', // const base64Credential = Buffer.from(combined).toString('base64')
url: `${SERVER}control/getNetworkInfo`, // const readyCredential = `Basic ${base64Credential}`
headers: { Authorization: readyCredential } //
} // // Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
// const options = {
const promises = [] // method: 'GET',
for (let i = 0; i < 30; i++) { // url: `${SERVER}control/getNetworkInfo`,
const promise = axios(options) // headers: { Authorization: readyCredential }
promises.push(promise) // }
} //
// const promises = []
await Promise.all(promises) // for (let i = 0; i < 80; i++) {
// const promise = axios(options)
assert.equal(true, true, 'Not throwing an error is a pass!') // promises.push(promise)
} catch (err) { // }
// console.log(`err.response: ${util.inspect(err.response)}`) //
// await Promise.all(promises)
assert.equal( //
true, // assert.equal(true, false, 'Unexpected result!')
false, // } catch (err) {
'This error handler should not have been triggered. Is the password correct?' // // console.log(`err.response: ${util.inspect(err.response)}`)
) //
} // assert.equal(err.response.status, 429)
}) // assert.include(err.response.data.error, 'Too many requests')
// }
it('should trigger rate-limit handler if rate limits exceeds pro-tier limit', async () => { // })
try {
const username = 'BITBOX'
// Pro-tier is accessed by using the right password.
const password = 'BITBOX'
// const password = "something"
const combined = `${username}:${password}`
const base64Credential = Buffer.from(combined).toString('base64')
const readyCredential = `Basic ${base64Credential}`
// Actual rate limit is 60 per minute X 4 nodes = 240 rpm.
const options = {
method: 'GET',
url: `${SERVER}control/getNetworkInfo`,
headers: { Authorization: readyCredential }
}
const promises = []
for (let i = 0; i < 80; i++) {
const promise = axios(options)
promises.push(promise)
}
await Promise.all(promises)
assert.equal(true, false, 'Unexpected result!')
} catch (err) {
// console.log(`err.response: ${util.inspect(err.response)}`)
assert.equal(err.response.status, 429)
assert.include(err.response.data.error, 'Too many requests')
}
})
it('should unlock pro-tier for a valid JWT token', async () => { it('should unlock pro-tier for a valid JWT token', async () => {
try { try {
+35 -35
View File
@@ -105,14 +105,14 @@ describe('#route-ratelimits & jwt-auth', () => {
}) })
describe('#calcPoints', () => { describe('#calcPoints', () => {
it('should return 30 points for anonymous user', () => { it('should return 300 points for anonymous user', () => {
const result = rateLimits.calcPoints() const result = rateLimits.calcPoints()
// console.log(`result: ${result}`) // console.log(`result: ${result}`)
assert.equal(result, 30) assert.equal(result, 300)
}) })
it('should return 10 points for free tier requesting full node access', () => { it('should return 100 points for free tier requesting full node access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 10, apiLevel: 10,
resource: 'blockchain', resource: 'blockchain',
@@ -120,10 +120,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 100)
}) })
it('should return 10 points for free tier requesting indexer access', () => { it('should return 100 points for free tier requesting indexer access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 10, apiLevel: 10,
resource: 'blockbook', resource: 'blockbook',
@@ -131,10 +131,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 100)
}) })
it('should return 10 points for free tier requesting SLPDB access', () => { it('should return 100 points for free tier requesting SLPDB access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 10, apiLevel: 10,
resource: 'slp', resource: 'slp',
@@ -142,10 +142,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 100)
}) })
it('should return 1 point for full node tier requesting full node access', () => { it('should return 10 points for full node tier requesting full node access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 20, apiLevel: 20,
resource: 'blockchain', resource: 'blockchain',
@@ -153,10 +153,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1) assert.equal(result, 10)
}) })
it('should return 10 points for full-node tier requesting indexer access', () => { it('should return 100 points for full-node tier requesting indexer access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 20, apiLevel: 20,
resource: 'blockbook', resource: 'blockbook',
@@ -164,10 +164,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 100)
}) })
it('should return 10 points for full node tier requesting SLPDB access', () => { it('should return 100 points for full node tier requesting SLPDB access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 20, apiLevel: 20,
resource: 'slp', resource: 'slp',
@@ -175,10 +175,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 100)
}) })
it('should return 1 point for indexer tier requesting full node access', () => { it('should return 10 point for indexer tier requesting full node access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 30, apiLevel: 30,
resource: 'blockchain', resource: 'blockchain',
@@ -186,32 +186,32 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1) assert.equal(result, 10)
}) })
it('should return 1 points for indexer tier requesting indexer access', () => { it('should return 10 points for indexer tier requesting indexer access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 30, apiLevel: 30,
resource: 'blockbook', resource: 'blockbook',
id: '5e3a0415eb29a962da2708b4' id: '5e3a0415eb29a962da2708b4'
} }
const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1)
})
it('should return 10 points for indexer tier requesting SLPDB access', () => {
const jwtInfo = {
apiLevel: 30,
resource: 'slp',
id: '5e3a0415eb29a962da2708b4'
}
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 10) assert.equal(result, 10)
}) })
it('should return 1 point for SLP tier requesting full node access', () => { it('should return 100 points for indexer tier requesting SLPDB access', () => {
const jwtInfo = {
apiLevel: 30,
resource: 'slp',
id: '5e3a0415eb29a962da2708b4'
}
const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 100)
})
it('should return 10 point for SLP tier requesting full node access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 40, apiLevel: 40,
resource: 'blockchain', resource: 'blockchain',
@@ -219,10 +219,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1) assert.equal(result, 10)
}) })
it('should return 1 points for SLP tier requesting indexer access', () => { it('should return 10 points for SLP tier requesting indexer access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 40, apiLevel: 40,
resource: 'blockbook', resource: 'blockbook',
@@ -230,10 +230,10 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1) assert.equal(result, 10)
}) })
it('should return 1 points for SLP tier requesting SLPDB access', () => { it('should return 10 points for SLP tier requesting SLPDB access', () => {
const jwtInfo = { const jwtInfo = {
apiLevel: 40, apiLevel: 40,
resource: 'slp', resource: 'slp',
@@ -241,7 +241,7 @@ describe('#route-ratelimits & jwt-auth', () => {
} }
const result = rateLimits.calcPoints(jwtInfo) const result = rateLimits.calcPoints(jwtInfo)
assert.equal(result, 1) assert.equal(result, 10)
}) })
}) })
@@ -442,7 +442,7 @@ describe('#route-ratelimits & jwt-auth', () => {
// Issues with token secret should treat incoming requests as anonymous // Issues with token secret should treat incoming requests as anonymous
// calls with 30 points or 3 RPM. // calls with 30 points or 3 RPM.
assert.equal(res.locals.pointsToConsume, 30) assert.equal(res.locals.pointsToConsume, 300)
}) })
}) })
}) })