diff --git a/backend/src/api/bitcoin/bitcoin.routes.ts b/backend/src/api/bitcoin/bitcoin.routes.ts index 73741efbf..2388a5618 100644 --- a/backend/src/api/bitcoin/bitcoin.routes.ts +++ b/backend/src/api/bitcoin/bitcoin.routes.ts @@ -1176,16 +1176,18 @@ class BitcoinRoutes { const op = (req.params.op) as 'and' | 'or' | 'nor' | undefined; const mask = BigInt(req.params.mask ?? 0n); - const { tip } = await FlagValueRepository.$getTipAndTailIndexedByBucketSize(bucketSize) || { tip: undefined }; + const { tip, tail } = await FlagValueRepository.$getTipAndTailIndexedByBucketSize(bucketSize) || { tip: undefined, tail: undefined }; - if (!tip) { + if (tip === undefined || tail === undefined) { handleError(req, res, 400, `Failed to get latest indexed flag values for ${interval}`); return; } + const totalCount = await FlagValueRepository.$getTotalBlocksIndexedByBucketSize(bucketSize === 1 ? 1008 : bucketSize) ?? tip - tail; + const startHeight = presets[interval].retentionSpan !== -1 ? (tip - presets[interval].retentionSpan) : -1; const txsCount = await FlagValueRepository.$queryTxCountBasedOnMask(mask, bucketSize, op, startHeight); - res.header('X-total-count', tip.toString()); + res.header('X-total-count', totalCount.toString()); res.header('Expires', new Date(Date.now() + 1000 * 3600 * 24 * (presets[interval].bucketSizes[0] / 144)).toUTCString()); res.send(txsCount); } catch (e: any) { diff --git a/backend/src/repositories/FlagValueRepository.ts b/backend/src/repositories/FlagValueRepository.ts index 66f8495c1..9bedf7913 100644 --- a/backend/src/repositories/FlagValueRepository.ts +++ b/backend/src/repositories/FlagValueRepository.ts @@ -128,6 +128,18 @@ class FlagValuesRepository { logger.err(`Cannot delete flag values above ${height}. Reason: ` + (e instanceof Error ? e.message : e)); } } + + public async $getTotalBlocksIndexedByBucketSize(bucketSize: number): Promise { + try { + const [rows]: any[] = await DB.query(`SELECT (count(distinct start_height) * ?) as total FROM flag_values WHERE bucket_size = ?`, [bucketSize, bucketSize.toString()]); + if (rows !== null && rows.length > 0) { + return rows[0].total; + } + } catch (e) { + logger.err(`Cannot get total blocks indexed in flag_values. Reason: ` + (e instanceof Error ? e.message : e)); + } + return null; + } } export default new FlagValuesRepository();