From 128d20b5c2c497add8369d186b73f76f073fbd5c Mon Sep 17 00:00:00 2001 From: minuszka <101508242+minuszka@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:52:37 +0100 Subject: [PATCH] Fix hash lookups typed in capitals, staking totals in the address API, and details that went stale on open pages Five small fixes found in a code audit. - A transaction or block hash typed in capital letters now opens the same page as in lower case, on the transaction, block and search pages and in the AI lookup used by the MCP tool. Before, it answered "not found" unless the lower-case version happened to be cached. - The address rewards API never counted any stakes. It now counts the transactions in which the address staked and reports the net stake reward: what came back minus what was staked. For a very active address the first request reads all of its spending transactions; the answer is cached for 15 seconds. - An open transaction, block or address page now updates when a new block arrives: the confirmation count goes up, the newest block gains its "next block" link, and new transactions appear, without a reload. - The block page now tells "block not found" apart from "block could not be loaded". - The header's "Polling" status (the chain is current, the live connection is reconnecting) is shown in the healthy green instead of the warning colour. - Checked with new server, database and browser tests; each fix was undone once to confirm that its test fails without it. --- client/e2e/block-states.spec.ts | 40 ++++ client/e2e/fonts.spec.ts | 14 +- client/e2e/live-details.spec.ts | 218 ++++++++++++++++++ client/e2e/navigation.spec.ts | 46 ++++ client/src/components/flow/AddressFlow.tsx | 14 +- client/src/components/layout/Header.css | 7 +- .../components/layout/HeaderStatusChips.tsx | 4 +- client/src/context/AutoRefreshContext.tsx | 40 +--- client/src/pages/BlockDetailPage.tsx | 28 ++- client/src/pages/TransactionPage.tsx | 22 +- server/src/docs/openapi.ts | 5 + server/src/routes/ai.routes.ts | 6 +- server/src/routes/blocks.routes.ts | 79 ++++--- server/src/routes/search.routes.ts | 5 +- server/src/routes/transactions.routes.ts | 57 +++-- server/src/routes/v1/address.v1.routes.ts | 78 ++++++- server/src/utils/blockRoles.ts | 2 +- server/src/utils/validation.ts | 9 +- .../test/addressRewards.integration.test.ts | 116 ++++++++++ server/test/ai.routes.test.ts | 55 +++++ server/test/blocks.routes.test.ts | 169 ++++++++++++++ server/test/search.routes.test.ts | 30 +++ server/test/staleFallback.routes.test.ts | 7 +- server/test/transactions.routes.test.ts | 101 ++++++++ 24 files changed, 1026 insertions(+), 126 deletions(-) create mode 100644 client/e2e/block-states.spec.ts create mode 100644 client/e2e/live-details.spec.ts create mode 100644 server/test/addressRewards.integration.test.ts create mode 100644 server/test/ai.routes.test.ts diff --git a/client/e2e/block-states.spec.ts b/client/e2e/block-states.spec.ts new file mode 100644 index 0000000..faffa22 --- /dev/null +++ b/client/e2e/block-states.spec.ts @@ -0,0 +1,40 @@ +import { expect, test } from '@playwright/test'; +import { stubApi } from './apiStub'; + +// The block page tells a block that does not exist apart from one it could not load. + +test('a block the explorer does not have is reported as not found @smoke', async ({ page }) => { + await stubApi(page); + let requests = 0; + await page.route('**/api/block/123', (route) => { + requests += 1; + return route.fulfill({ status: 404, json: { success: false, error: { code: 'NOT_FOUND', message: 'Block not found' } } }); + }); + + await page.goto('/block/123'); + + await expect(page.getByText('Block not found', { exact: true })).toBeVisible(); + await expect(page.getByText('Block "123" was not found. It may not be synced yet.')).toBeVisible(); + await expect(page.getByRole('link', { name: 'Browse Blocks' })).toHaveAttribute('href', '/blocks'); + await expect(page.getByText('Block could not be loaded')).toHaveCount(0); + // A "not found" answer does not change on a retry. + expect(requests).toBe(1); +}); + +test('a block that fails to load is reported as an error, not as missing @smoke', async ({ page }) => { + await stubApi(page); + let requests = 0; + await page.route('**/api/block/123', (route) => { + requests += 1; + return route.fulfill({ status: 500, json: { success: false, error: { code: 'INTERNAL', message: 'Failed to fetch block' } } }); + }); + + await page.goto('/block/123'); + + const panel = page.locator('.state-panel[data-tone="danger"]'); + await expect(panel.getByText('Block could not be loaded')).toBeVisible(); + await expect(panel).toContainText('Failed to fetch block'); + await expect(page.getByText('Block not found', { exact: true })).toHaveCount(0); + // A server error is tried once more before the page gives up. + expect(requests).toBe(2); +}); diff --git a/client/e2e/fonts.spec.ts b/client/e2e/fonts.spec.ts index 49f26bc..f8a8e54 100644 --- a/client/e2e/fonts.spec.ts +++ b/client/e2e/fonts.spec.ts @@ -49,11 +49,11 @@ test('the site fonts load from this origin under the production content security expect(fontPolicyViolations).toEqual([]); }); -const delayedStats = () => ({ +const statsWithLastBlockAgo = (seconds: number) => ({ success: true, data: { blockHeight: 130_000, - lastBlockTime: Math.floor(Date.now() / 1000) - 11 * 60, + lastBlockTime: Math.floor(Date.now() / 1000) - seconds, difficulty: 1, hashrate: 1, connections: 8, @@ -69,17 +69,21 @@ const delayedStats = () => ({ }, }); +const delayedStats = () => statsWithLastBlockAgo(11 * 60); + // The longest status labels leave the least room next to them. Every case must fit on one row // without sideways scrolling, with 40px search and menu buttons. Up to 520px the header shows the // logo without the title (which stays the link's name); below 360px the block height moves to the -// menu while the status is not "Live". +// menu while the status is not "Live". "Polling" is healthy but as long as "Delayed". const NARROW_HEADER_CASES = [ { width: 600, label: 'Disconnected', titleShown: true, heightInTopBar: true }, { width: 521, label: 'Disconnected', titleShown: true, heightInTopBar: true }, { width: 360, label: 'Delayed', titleShown: false, heightInTopBar: true }, { width: 360, label: 'Disconnected', titleShown: false, heightInTopBar: true }, + { width: 360, label: 'Polling', titleShown: false, heightInTopBar: true }, { width: 320, label: 'Delayed', titleShown: false, heightInTopBar: false }, { width: 320, label: 'Disconnected', titleShown: false, heightInTopBar: false }, + { width: 320, label: 'Polling', titleShown: false, heightInTopBar: false }, ]; const disconnectedSync = { @@ -90,9 +94,11 @@ const disconnectedSync = { for (const { width, label, titleShown, heightInTopBar } of NARROW_HEADER_CASES) { test(`a ${width}px screen fits the header on one row beside "${label}" @smoke`, async ({ page }) => { await page.unroute('**/api/**'); + // A closed realtime connection with a current chain is "Polling". + if (label === 'Polling') await page.routeWebSocket('**/ws', (socket) => socket.close()); await stubApi(page, label === 'Disconnected' ? { '/api/stats': delayedStats(), '/api/sync': disconnectedSync } - : { '/api/stats': delayedStats() }); + : { '/api/stats': label === 'Polling' ? statsWithLastBlockAgo(60) : delayedStats() }); await page.setViewportSize({ width, height: 780 }); await page.goto('/'); diff --git a/client/e2e/live-details.spec.ts b/client/e2e/live-details.spec.ts new file mode 100644 index 0000000..fd78dc8 --- /dev/null +++ b/client/e2e/live-details.spec.ts @@ -0,0 +1,218 @@ +import { expect, test, type Page, type WebSocketRoute } from '@playwright/test'; +import { stubApi } from './apiStub'; + +// An open transaction, block or address page follows the chain: when the realtime connection +// announces a new block, the page asks again and shows the new state without a reload. + +const BLOCK_TIME = 1_788_609_600; // 2026-09-05 12:00:00 UTC +const TIP = 123_456; +const HASH = 'a'.repeat(64); +const NEXT_HASH = 'c'.repeat(64); +const TXID = `d${'e'.repeat(62)}f`; +const NEW_TXID = `7${'6'.repeat(62)}5`; +const ADDRESS = 'DGK3yNxxedc2pvaPPwTbVBey2NmFC8FUGZ'; +const OTHER = `D${'R'.repeat(33)}`; + +/** + * A realtime connection that stays open and the chain tip it reports. `newBlock()` moves the tip + * one block on and announces it the way the server does, with the next sequence number. + */ +async function followChain(page: Page) { + let socket: WebSocketRoute | null = null; + let seq = 1; + const chain = { + tip: TIP, + async newBlock() { + await expect.poll(() => socket !== null).toBe(true); + chain.tip += 1; + seq += 1; + socket!.send(JSON.stringify({ + type: 'block:new', ts: new Date().toISOString(), seq, + data: { hash: chain.tip === TIP + 1 ? NEXT_HASH : 'f'.repeat(64), height: chain.tip, time: BLOCK_TIME + 150, txCount: 2 }, + })); + }, + }; + await page.routeWebSocket('**/ws', (ws) => { + socket = ws; + ws.send(JSON.stringify({ type: 'hello', ts: new Date().toISOString(), seq: 1, data: {} })); + }); + return chain; +} + +function transaction(txid: string, height: number, tip: number) { + const output = (n: number, value: number, address: string) => ({ + n, value, valueSat: String(Math.round(value * 1e8)), scriptPubKey: { asm: '', hex: '', type: 'pubkeyhash', addresses: [address] }, + }); + return { + txid, blockhash: HASH, blockheight: height, blocktime: BLOCK_TIME, version: 3, size: 225, locktime: 0, + vin: [{ txid: 'f'.repeat(64), vout: 0, sequence: 0, address: ADDRESS, value: 15, valueSat: '1500000000' }], + vout: [output(0, 10, OTHER), output(1, 4.9999, ADDRESS)], + totalValueIn: 15, totalValueOut: 14.9999, fee: 0.0001, + totalValueInSat: '1500000000', totalValueOutSat: '1499990000', feeSat: '10000', + isCoinbase: false, confirmations: tip - height + 1, + }; +} + +test('an open transaction page shows the new confirmation count after a block @smoke', async ({ page }) => { + await stubApi(page); + const chain = await followChain(page); + await page.route(`**/api/tx/${TXID}`, (route) => + route.fulfill({ json: { success: true, data: transaction(TXID, TIP - 2, chain.tip) } })); + + await page.goto(`/tx/${TXID}`); + const confirmations = page.locator('.detail-row') + .filter({ has: page.locator('.detail-label', { hasText: /^Confirmations$/ }) }) + .locator('.detail-value'); + await expect(confirmations).toHaveText('3'); + + await chain.newBlock(); + await expect(confirmations).toHaveText('4'); +}); + +test('an open block page at the chain tip gains its link to the next block @smoke', async ({ page }) => { + await stubApi(page, { + [`/api/block/${TIP}/txs`]: { success: true, data: [], pagination: { page: 1, limit: 20, total: 0, pages: 1 } }, + }); + const chain = await followChain(page); + await page.route(`**/api/block/${TIP}`, (route) => route.fulfill({ json: { success: true, data: { + hash: HASH, height: TIP, confirmations: chain.tip - TIP + 1, size: 538, version: 0x20000000, merkleroot: 'b'.repeat(64), + time: BLOCK_TIME, mediantime: BLOCK_TIME, nonce: 0, bits: '190a969d', difficulty: 400_000_000, chainwork: '0', nTx: 0, + rewardSat: 1_050_000_000_000, totalValueOutSat: 0, txids: [], reward: 10_500, totalValueOut: 0, + previousblockhash: 'e'.repeat(64), ...(chain.tip > TIP ? { nextblockhash: NEXT_HASH } : {}), + } } })); + + await page.goto(`/block/${TIP}`); + const nav = page.getByRole('navigation', { name: 'Neighbouring blocks' }); + await expect(page.getByText('1 Confirmations')).toBeVisible(); + await expect(nav.getByRole('link', { name: 'Block #123,455' })).toBeVisible(); + await expect(nav.getByRole('link', { name: 'Block #123,457' })).toHaveCount(0); + + await chain.newBlock(); + await expect(nav.getByRole('link', { name: 'Block #123,457' })).toHaveAttribute('href', `/block/${TIP + 1}`); + await expect(page.getByText('2 Confirmations')).toBeVisible(); +}); + +/** + * An address page whose answers follow the chain tip. `options.fail` makes every answer after the + * new block a server error; otherwise the list answer after the new block waits until `release()`. + */ +async function openAddress(page: Page, chain: Awaited>, options: { fail?: boolean } = {}) { + await stubApi(page); + let release = () => {}; + const held = new Promise((resolve) => { release = resolve; }); + const seen = { summaryAfterBlock: 0, listAfterBlock: 0 }; + const txs = () => chain.tip > TIP + ? [transaction(NEW_TXID, chain.tip, chain.tip), transaction(TXID, TIP - 2, chain.tip)] + : [transaction(TXID, TIP - 2, chain.tip)]; + const failure = { status: 500, json: { success: false, error: { code: 'INTERNAL', message: 'Failed to fetch address' } } }; + await page.route(`**/api/address/${ADDRESS}`, (route) => { + if (chain.tip > TIP) seen.summaryAfterBlock += 1; + if (chain.tip > TIP && options.fail) return route.fulfill(failure); + return route.fulfill({ json: { success: true, data: { + address: ADDRESS, balance: 4.9999, totalReceived: 19.9999, totalSent: 15, txCount: txs().length, + balanceSat: '499990000', totalReceivedSat: '1999990000', totalSentSat: '1500000000', + } } }); + }); + await page.route(`**/api/address/${ADDRESS}/txs?*`, async (route) => { + if (chain.tip > TIP) { + seen.listAfterBlock += 1; + if (options.fail) return route.fulfill(failure); + await held; + } + return route.fulfill({ json: { + success: true, data: txs(), pagination: { page: 1, limit: 20, total: txs().length, pages: 1 }, + } }); + }); + + await page.goto(`/address/${ADDRESS}`); + await expect(page.locator('.searchv2-address-total')).toHaveText('1 total transaction'); + await expect(page.locator(`a[href="/tx/${TXID}"]`).first()).toBeVisible(); + await expect(page.locator(`a[href="/tx/${NEW_TXID}"]`)).toHaveCount(0); + return { seen, release: () => release() }; +} + +test('an open address page lists a transaction from the new block @smoke', async ({ page }) => { + const chain = await followChain(page); + const address = await openAddress(page, chain); + + await chain.newBlock(); + // While the new list is on its way, the current one stays on screen instead of a loading line. + await expect.poll(() => address.seen.listAfterBlock).toBeGreaterThan(0); + await expect(page.locator(`a[href="/tx/${TXID}"]`).first()).toBeVisible(); + await expect(page.getByText('Loading transactions for this address...')).toHaveCount(0); + + address.release(); + await expect(page.locator(`a[href="/tx/${NEW_TXID}"]`).first()).toBeVisible(); + await expect(page.locator('.searchv2-address-total')).toHaveText('2 total transactions'); +}); + +// A refresh after a new block that fails keeps what the page already shows; the next block or +// poll tries again. Each page retries a failed request once, so two failed answers mean it gave up. + +test('an open transaction page keeps the transaction when the refresh after a block fails @smoke', async ({ page }) => { + await stubApi(page); + const chain = await followChain(page); + let afterBlock = 0; + await page.route(`**/api/tx/${TXID}`, (route) => { + if (chain.tip === TIP) return route.fulfill({ json: { success: true, data: transaction(TXID, TIP - 2, chain.tip) } }); + afterBlock += 1; + return route.fulfill({ status: 500, json: { success: false, error: { code: 'INTERNAL', message: 'Failed to fetch transaction' } } }); + }); + + await page.goto(`/tx/${TXID}`); + const confirmations = page.locator('.detail-row') + .filter({ has: page.locator('.detail-label', { hasText: /^Confirmations$/ }) }) + .locator('.detail-value'); + await expect(confirmations).toHaveText('3'); + + await chain.newBlock(); + await expect.poll(() => afterBlock, { timeout: 10_000 }).toBe(2); + await page.waitForTimeout(300); + await expect(confirmations).toHaveText('3'); + await expect(page.getByText('Transaction could not be loaded')).toHaveCount(0); +}); + +test('an open block page keeps the block when the refresh after a block fails @smoke', async ({ page }) => { + await stubApi(page, { + [`/api/block/${TIP}/txs`]: { success: true, data: [], pagination: { page: 1, limit: 20, total: 0, pages: 1 } }, + }); + const chain = await followChain(page); + let afterBlock = 0; + await page.route(`**/api/block/${TIP}`, (route) => { + if (chain.tip > TIP) { + afterBlock += 1; + return route.fulfill({ status: 500, json: { success: false, error: { code: 'INTERNAL', message: 'Failed to fetch block' } } }); + } + return route.fulfill({ json: { success: true, data: { + hash: HASH, height: TIP, confirmations: 1, size: 538, version: 0x20000000, merkleroot: 'b'.repeat(64), + time: BLOCK_TIME, mediantime: BLOCK_TIME, nonce: 0, bits: '190a969d', difficulty: 400_000_000, chainwork: '0', nTx: 0, + rewardSat: 1_050_000_000_000, totalValueOutSat: 0, txids: [], reward: 10_500, totalValueOut: 0, + previousblockhash: 'e'.repeat(64), + } } }); + }); + + await page.goto(`/block/${TIP}`); + await expect(page.getByText('1 Confirmations')).toBeVisible(); + + await chain.newBlock(); + await expect.poll(() => afterBlock, { timeout: 10_000 }).toBe(2); + await page.waitForTimeout(300); + await expect(page.getByRole('heading', { name: 'Block #123,456' })).toBeVisible(); + await expect(page.getByText('1 Confirmations')).toBeVisible(); + await expect(page.getByText('Block could not be loaded')).toHaveCount(0); +}); + +test('an open address page keeps its summary and list when the refresh after a block fails @smoke', async ({ page }) => { + const chain = await followChain(page); + const address = await openAddress(page, chain, { fail: true }); + + await chain.newBlock(); + // Both the summary and the list are retried once. + await expect.poll(() => address.seen.summaryAfterBlock, { timeout: 10_000 }).toBe(2); + await expect.poll(() => address.seen.listAfterBlock, { timeout: 10_000 }).toBe(2); + await page.waitForTimeout(300); + await expect(page.locator(`a[href="/tx/${TXID}"]`).first()).toBeVisible(); + await expect(page.locator('.searchv2-address-total')).toHaveText('1 total transaction'); + await expect(page.getByText('Address details could not be loaded')).toHaveCount(0); + await expect(page.getByText('Failed to fetch address')).toHaveCount(0); +}); diff --git a/client/e2e/navigation.spec.ts b/client/e2e/navigation.spec.ts index fa193cb..803d57c 100644 --- a/client/e2e/navigation.spec.ts +++ b/client/e2e/navigation.spec.ts @@ -224,6 +224,52 @@ test('header does not report live when the indexed chain is delayed @smoke', asy await expect(status).toHaveAttribute('title', /Latest indexed block is .*old/); }); +test('header shows a current chain without realtime connection as healthy polling, not as a warning @smoke', async ({ page }) => { + await page.routeWebSocket('**/ws', (socket) => socket.close()); + await page.unroute('**/api/**'); + await stubApi(page, { + '/api/stats': { + success: true, + data: { + blockHeight: 130_000, + lastBlockTime: Math.floor(Date.now() / 1000) - 60, + difficulty: 1, + hashrate: 1, + connections: 8, + mempool: { size: 0, bytes: 0 }, + supply: { circulating: 1, max: null }, + blockReward: 1, + stakingReward: 0, + avgBlockTime: 150, + totalTransactions: 1, + totalAddresses: 1, + masternodes: 1, + stakingWallets: 1, + }, + }, + }); + + await page.goto('/'); + const status = page.locator('.status-chip-live').first(); + await expect(status).toContainText('Polling'); + await expect(status).toHaveAttribute('title', /Indexed chain is current/); + await expect(status).not.toHaveClass(/degraded/); + // The chip keeps the healthy (green) colour of "Live". + const colours = await status.evaluate((chip) => ({ + label: getComputedStyle(chip.querySelector('.status-chip-label') as Element).color, + success: getComputedStyle(document.documentElement).getPropertyValue('--success').trim(), + })); + const probe = await page.evaluate((value) => { + const element = document.createElement('span'); + element.style.color = value; + document.body.append(element); + const rgb = getComputedStyle(element).color; + element.remove(); + return rgb; + }, colours.success); + expect(colours.label).toBe(probe); +}); + test('mobile drawer exposes the same top-level navigation @smoke', async ({ page }, testInfo) => { test.skip(testInfo.project.name !== 'mobile-chromium', 'Mobile navigation is covered in the mobile project.'); diff --git a/client/src/components/flow/AddressFlow.tsx b/client/src/components/flow/AddressFlow.tsx index d234d91..6d055f8 100644 --- a/client/src/components/flow/AddressFlow.tsx +++ b/client/src/components/flow/AddressFlow.tsx @@ -32,9 +32,11 @@ export default function AddressFlow({ address }: { address: string }) { retry: retryFailedRequestOnce, }); const summary = summaryQuery.data ?? null; - const summaryNotFound = isNotFoundError(summaryQuery.error); + // A refresh that fails after a new block keeps what is on screen: the error states are only for + // a summary or a list that never loaded. + const summaryNotFound = !summary && isNotFoundError(summaryQuery.error); const summaryError = - summaryQuery.error != null && !summaryNotFound + !summary && summaryQuery.error != null && !summaryNotFound ? getErrorMessage(summaryQuery.error, 'Address details could not be loaded.') : null; @@ -44,9 +46,13 @@ export default function AddressFlow({ address }: { address: string }) { }); const txs = (txsQuery.data?.data || []) as TxView[]; const pages = txsQuery.data?.pagination?.pages || 1; - const txsLoading = txsQuery.isPending || txsQuery.isFetching; + // Loading means no list of this page yet: the first load, or another page while the previous one + // stands in. A refresh of the list on screen keeps it visible. + const txsLoading = txsQuery.isPending || (txsQuery.isFetching && txsQuery.isPlaceholderData); const txsError = - txsQuery.error != null ? getErrorMessage(txsQuery.error, 'Address transactions could not be loaded.') : null; + txsQuery.error != null && !txsQuery.data + ? getErrorMessage(txsQuery.error, 'Address transactions could not be loaded.') + : null; const txTotal = summary?.txCount ?? txsQuery.data?.pagination?.total ?? txs.length; // Neither a summary nor a single indexed transaction: the explorer has never seen this address. diff --git a/client/src/components/layout/Header.css b/client/src/components/layout/Header.css index a94c7e6..e741983 100644 --- a/client/src/components/layout/Header.css +++ b/client/src/components/layout/Header.css @@ -484,10 +484,11 @@ } } -/* Below 360px a longer status word ("Disconnected", "Sync error") leaves no room for the block - height beside the logo, the search and the menu buttons. The block height stays in the menu. */ +/* Below 360px a status word longer than "Live" ("Polling", "Disconnected", "Sync error") leaves no + room for the block height beside the logo, the search and the menu buttons. The block height + stays in the menu. */ @media (max-width: 359px) { - .header-status-chips:not(.compact) .status-chip-live.degraded ~ .status-chip-height { + .header-status-chips:not(.compact) .status-chip-live.long-label ~ .status-chip-height { display: none; } } diff --git a/client/src/components/layout/HeaderStatusChips.tsx b/client/src/components/layout/HeaderStatusChips.tsx index 059d660..e2ac6e3 100644 --- a/client/src/components/layout/HeaderStatusChips.tsx +++ b/client/src/components/layout/HeaderStatusChips.tsx @@ -60,8 +60,10 @@ function HeaderStatusChips({ compact = false }: HeaderStatusChipsProps) { return (
+ {/* The colour follows the health of the status ("Polling" is healthy); "long-label" marks any + word longer than "Live", which leaves less room beside it on a narrow screen. */}