From 358662fb84a20b78e0e1f57f030a079b7188a988 Mon Sep 17 00:00:00 2001 From: tenthirtyone Date: Tue, 15 Aug 2017 11:38:40 -0400 Subject: [PATCH] add tx paging and protections --- server/lib/api/address.js | 7 ++++--- server/lib/api/transaction.js | 18 ++++++++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/server/lib/api/address.js b/server/lib/api/address.js index c12376a..edcbdcd 100644 --- a/server/lib/api/address.js +++ b/server/lib/api/address.js @@ -47,25 +47,26 @@ module.exports = function AddressAPI(router) { logger.log('error', `${err}`); } + const totalReceived = body.reduce((sum, tx) => sum + tx.outputs.reduce((sum, output) => { if (output.address === req.params.addr) { return sum + output.value; } return sum; - }, 0), 0); + }, 0), 0) || 0; const totalSpent = body.reduce((sum, tx) => sum + tx.inputs.reduce((sum, input) => { if (input.coin && input.coin.address === req.params.addr) { return sum + input.coin.value; } return sum; - }, 0), 0); + }, 0), 0) || 0; res.json({ addrStr: req.params.addr, - balance: totalReceived - totalSpent, + balance: (totalReceived - totalSpent) / 1e8, balanceSat: totalReceived - totalSpent, totalReceived: totalReceived / 1e8, totalReceivedSat: totalReceived, diff --git a/server/lib/api/transaction.js b/server/lib/api/transaction.js index 397537f..5b7d7fd 100644 --- a/server/lib/api/transaction.js +++ b/server/lib/api/transaction.js @@ -4,7 +4,7 @@ const logger = require('../logger'); const request = require('request'); const config = require('../../config'); -const MAX_TXS = 20; +const MAX_TXS = 10; const MAX_BLOCKS = 1; // Shoe horned in. Not dry, also in blocks. Make db api later @@ -100,6 +100,10 @@ module.exports = function transactionAPI(router) { // That callback hell router.get('/txs', (req, res) => { + const pageNum = parseInt(req.query.pageNum) || 0; + const rangeStart = pageNum * MAX_TXS; + const rangeEnd = rangeStart + MAX_TXS; + if (req.query.block) { getBlock( {}, @@ -111,6 +115,7 @@ module.exports = function transactionAPI(router) { logger.log('err', err); } if (block[0]) { + const height = block[0].height; request(`http://${config.bcoin_http}:${config.bcoin['http-port']}/block/${req.query.block}`, (err, localRes, body) => { if (err) { @@ -122,9 +127,18 @@ module.exports = function transactionAPI(router) { } catch (e) { logger.log('error', `${err}`); + res.status(501).send(); } + if (!body.txs.length) { + logger.log('error', + `${'No tx results'}`); + res.status(501).send(); + } + const totalPages = Math.ceil(body.txs.length / MAX_TXS); + body.txs = body.txs.slice(rangeStart, rangeEnd); + res.send({ - pagesTotal: 1, + pagesTotal: totalPages, txs: body.txs.map(tx => ({ txid: tx.hash, fees: tx.fee / 1e8,