diff --git a/client/e2e/home-lists.spec.ts b/client/e2e/home-lists.spec.ts new file mode 100644 index 0000000..478e8f3 --- /dev/null +++ b/client/e2e/home-lists.spec.ts @@ -0,0 +1,157 @@ +import { expect, test, type Page } from '@playwright/test'; +import { stubApi } from './apiStub'; + +// The home page lists: each block names the address that made it (not the masternode it paid), +// each transaction carries the label the transaction page uses, rewards can be hidden, and the two +// lists show the same number of rows. + +const NOW = 1_788_609_600; // 2026-09-05 12:00:00 UTC +const STAKER = 'DKgo69ycaxuut3QxaTSfyqbkFvyRvvq8Hf'; +const PAYEE = 'DGK3yNxxedc2pvaPPwTbVBey2NmFC8FUGZ'; +const MINER = 'D9NofFTND226dT475V33QaHU9LKHK7UwVe'; +const SENDER = 'D8e1nUDayNHvXSYZPv1QECNcSgCxgsXw9d'; +const TIP = 170_000; + +const block = (n: number, producer: unknown) => ({ + hash: `${n}`.padStart(64, 'b'), height: TIP - n, time: NOW - n * 150, nTx: 3, confirmations: n + 1, + reward: 10_500, minedBy: PAYEE, producer, size: 900, +}); +const BLOCKS = Array.from({ length: 10 }, (_, n) => + block(n, n === 8 ? null : n === 9 ? { address: MINER, kind: 'miner' } : { address: STAKER, kind: 'staker' })); + +const marker = { value: 0, scriptPubKey: { type: 'nonstandard', addresses: [] } }; +const pay = (value: number, address: string) => ({ value, scriptPubKey: { type: 'pubkeyhash', addresses: [address] } }); +const txid = (label: string, n: number) => `${label}${n}`.padStart(64, '0'); +const reward = (n: number) => ({ + txid: txid('cb', n), blockheight: TIP - n, blocktime: NOW - n * 150, confirmations: n + 1, totalValueOut: 10_000, + isCoinbase: true, vin: [], vout: [marker, pay(10_000, PAYEE)], +}); +const stake = (n: number) => ({ + txid: txid('cs', n), blockheight: TIP - n, blocktime: NOW - n * 150, confirmations: n + 1, totalValueOut: 25_500, + isCoinbase: false, vin: [{ address: STAKER }], vout: [marker, pay(25_500, STAKER)], +}); +const transfer = (n: number) => ({ + txid: txid('tr', n), blockheight: TIP - n, blocktime: NOW - n * 150, confirmations: n + 1, totalValueOut: 99.9, + isCoinbase: false, vin: [{ address: SENDER }], vout: [pay(40, MINER), pay(59.9, SENDER)], +}); +// Fourteen latest transactions, as an older server sent them: more rows than blocks. +const TXS = [reward(0), stake(0), transfer(0), reward(1), stake(1), reward(2), stake(2), transfer(2), reward(3), stake(3), reward(4), stake(4), reward(5), stake(5)]; +const TRANSFERS = [transfer(0), transfer(2), transfer(6)]; + +async function openHome(page: Page, overview: Record = {}) { + await page.clock.setFixedTime(new Date(NOW * 1000)); + await stubApi(page, { + '/api/dashboard/overview': { success: true, data: { stats: {}, blocks: BLOCKS, txs: TXS, transfers: TRANSFERS, ...overview } }, + }); + await page.goto('/'); + await expect(page.locator('.latest-card').first().locator('.latest-item-shell')).toHaveCount(10); +} + +const blockList = (page: Page) => page.locator('.latest-card').filter({ has: page.getByRole('heading', { name: 'Latest Blocks' }) }); +const txList = (page: Page) => page.locator('.latest-card').filter({ has: page.getByRole('heading', { name: 'Latest Transactions' }) }); + +test('each latest block names the address that staked or mined it, never the masternode it paid @smoke', async ({ page }) => { + await openHome(page); + const rows = blockList(page).locator('.latest-item-shell'); + + await expect(rows.nth(0).locator('.latest-producer')).toHaveText(/^Staked by DKgo69/); + await expect(rows.nth(0).locator('.latest-producer')).toHaveAttribute('title', STAKER); + await expect(rows.nth(8).locator('.latest-producer')).toHaveText('Producer unknown'); + await expect(rows.nth(9).locator('.latest-producer')).toHaveText(/^Mined by D9NofF/); + await expect(blockList(page)).not.toContainText('DGK3yN'); +}); + +test('a latest block row shows height, transactions, age and producer; its reward waits in the opened details @smoke', async ({ page }) => { + await openHome(page); + const first = blockList(page).locator('.latest-item-shell').first(); + + await expect(first.locator('.latest-item-trigger')).not.toContainText('bbbbbb'); + await expect(first.locator('.latest-item-trigger .reward-chip')).toHaveCount(0); + await expect(first.locator('.latest-item-trigger')).not.toContainText('DFCN'); + + await first.locator('.latest-item-trigger').click(); + await expect(first.locator('.latest-block-reward')).toContainText('Block reward 10,500'); +}); + +test('each latest transaction carries the same label as the transaction page @smoke', async ({ page }) => { + await openHome(page); + const rows = txList(page).locator('.latest-item'); + + await expect(rows.nth(0).locator('.latest-kind')).toHaveText('Reward'); + await expect(rows.nth(1).locator('.latest-kind')).toHaveText('Stake'); + await expect(rows.nth(2).locator('.latest-kind')).toHaveText('Transfer'); + await expect(txList(page)).not.toContainText('Block Reward'); +}); + +test('the two lists show the same number of rows @smoke', async ({ page }) => { + await openHome(page); + + await expect(txList(page).locator('.latest-item')).toHaveCount(10); +}); + +test('"Hide rewards" lists only other transactions and is remembered after a reload @smoke', async ({ page }) => { + await openHome(page); + const toggle = txList(page).getByRole('checkbox', { name: 'Hide rewards' }); + await expect(toggle).not.toBeChecked(); + + await toggle.check(); + const rows = txList(page).locator('.latest-item'); + await expect(rows).toHaveCount(3); + await expect(rows.locator('.latest-kind')).toHaveText(['Transfer', 'Transfer', 'Transfer']); + + await page.reload(); + await expect(txList(page).getByRole('checkbox', { name: 'Hide rewards' })).toBeChecked(); + await expect(txList(page).locator('.latest-item')).toHaveCount(3); +}); + +test('without a transfers list from the server, "Hide rewards" filters the latest transactions @smoke', async ({ page }) => { + await openHome(page, { transfers: undefined }); + + await txList(page).getByRole('checkbox', { name: 'Hide rewards' }).check(); + + await expect(txList(page).locator('.latest-item .latest-kind')).toHaveText(['Transfer', 'Transfer']); +}); + +test('on a phone the amount of each latest transaction stays visible, and both cards fit the screen @smoke', async ({ page }) => { + const width = 390; + await page.setViewportSize({ width, height: 844 }); + await openHome(page); + await blockList(page).locator('.latest-item-trigger').first().click(); + const amount = txList(page).locator('.latest-item').first().locator('.latest-amount'); + await expect(amount).toBeVisible(); + await expect(amount).toHaveText('10,000 DFCN'); + + // Element geometry, not page scroll width: the list section clips what overflows it. + const right = async (locator: ReturnType) => { + const box = await locator.boundingBox(); + return box ? box.x + box.width : Number.POSITIVE_INFINITY; + }; + for (const card of [blockList(page), txList(page)]) { + expect(await right(card)).toBeLessThanOrEqual(width); + } + const txCardRight = await right(txList(page)); + for (const element of [ + amount, + txList(page).getByRole('link', { name: 'View all' }), + txList(page).getByRole('checkbox', { name: 'Hide rewards' }), + ]) { + expect(await right(element)).toBeLessThanOrEqual(txCardRight); + } + expect(await right(blockList(page).getByRole('link', { name: 'Open block' }))).toBeLessThanOrEqual(await right(blockList(page))); +}); + +test('the blocks page names each block\'s producer, not the masternode it paid @smoke', async ({ page }) => { + await page.clock.setFixedTime(new Date(NOW * 1000)); + await stubApi(page, { + '/api/blocks': { success: true, data: BLOCKS.map((row) => ({ ...row, difficulty: 1, totalValueOut: 0 })), cursor: { mode: 'cursor', hasMore: false, next: null } }, + }); + await page.goto('/blocks'); + + const table = page.locator('table'); + await expect(table.getByRole('columnheader', { name: 'Producer' })).toBeVisible(); + await expect(table.getByRole('columnheader', { name: 'Extracted by' })).toHaveCount(0); + const firstRow = table.locator('tbody tr').first(); + await expect(firstRow.getByRole('link', { name: /DKgo69/ })).toHaveAttribute('href', `/address/${STAKER}`); + await expect(table.locator('tbody tr').nth(8)).toContainText('Unknown'); + await expect(table).not.toContainText('DGK3yN'); +}); diff --git a/client/src/pages/BlocksPage.tsx b/client/src/pages/BlocksPage.tsx index 505c06d..23a35aa 100644 --- a/client/src/pages/BlocksPage.tsx +++ b/client/src/pages/BlocksPage.tsx @@ -56,7 +56,7 @@ export default function BlocksPage() { Txs Difficulty Value Out - Extracted by + Producer @@ -76,13 +76,14 @@ export default function BlocksPage() { {block.nTx} {formatNumber(block.difficulty, 2)} {formatNumber(block.totalValueOut || 0, 2)} DFCN + {/* The staker (or premine miner) read from the chain; minedBy is the masternode the block paid. */} - {block.minedBy ? ( - - {truncateHash(block.minedBy, 12)} + {block.producer ? ( + + {truncateHash(block.producer.address, 12)} ) : ( - - + Unknown )} diff --git a/client/src/pages/DashboardPage.css b/client/src/pages/DashboardPage.css index e4b32e8..0c838f0 100644 --- a/client/src/pages/DashboardPage.css +++ b/client/src/pages/DashboardPage.css @@ -260,6 +260,13 @@ .latest-card .card-header { align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +/* A long hash or the header controls must not widen a card past a phone screen. */ +.dashboard-latest > .latest-card { + min-width: 0; } .latest-list { @@ -407,6 +414,7 @@ .latest-item-expand-header { display: flex; + flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; @@ -506,6 +514,44 @@ color: var(--text-muted); } +/* The opened block: its reward split, above its transactions. */ +.latest-block-reward { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-bottom: 8px; +} + +.latest-block-reward .latest-size { + margin-top: 0; +} + +.latest-header-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.latest-toggle { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 40px; + color: var(--text-muted); + font-size: 0.8rem; + cursor: pointer; +} + +.latest-toggle input { + accent-color: var(--accent); +} + +.latest-kind { + flex-shrink: 0; +} + .latest-placeholder { padding: 24px 12px; text-align: center; @@ -565,8 +611,10 @@ grid-template-columns: 1fr; } + /* The amount stays visible on a phone, in a narrower column. */ .latest-item-value { - display: none; + min-width: 0; + flex-shrink: 0; } .latest-item-expand { diff --git a/client/src/pages/DashboardPage.tsx b/client/src/pages/DashboardPage.tsx index 85e4c11..d9d733d 100644 --- a/client/src/pages/DashboardPage.tsx +++ b/client/src/pages/DashboardPage.tsx @@ -20,7 +20,8 @@ import { } from '../utils/formatters'; import { useMarketSnapshot } from '../hooks/useMarketSnapshot'; import { usePageVisibility } from '../hooks/usePageVisibility'; -import type { DashboardBlockView, DashboardTxView, TxListItemView } from '../types/api'; +import type { DashboardBlockView, DashboardTxView, TxListItemView, TxView } from '../types/api'; +import { classifyTransaction } from '../components/flow/flowModel'; import './DashboardPage.css'; import { txPath } from '../utils/routes'; import { computeMasternodeEconomics } from '../utils/masternodeEconomics'; @@ -29,6 +30,44 @@ const REWARD_TOLERANCE = 0.0000001; const PROTOCOL_TX_TOLERANCE = 0.0000001; const EMPTY_BLOCKS: DashboardBlockView[] = []; const EMPTY_TXS: DashboardTxView[] = []; +// The visitor's "Hide rewards" choice, kept in this browser only. +const HIDE_REWARDS_KEY = 'deftrack.hideRewards'; + +function readHideRewards(): boolean { + try { + return window.localStorage.getItem(HIDE_REWARDS_KEY) === '1'; + } catch { + return false; + } +} + +function writeHideRewards(hide: boolean): void { + try { + if (hide) window.localStorage.setItem(HIDE_REWARDS_KEY, '1'); + else window.localStorage.removeItem(HIDE_REWARDS_KEY); + } catch { + // Storage unavailable (private window, blocked site data): the choice lasts for this page only. + } +} + +/** The one label the transaction and address pages use (Reward, Stake, Protocol or Transfer). */ +function classifyListedTx(tx: DashboardTxView) { + // The overview carries every field the classifier reads; the rest of a full transaction is not needed. + return classifyTransaction(tx as unknown as TxView); +} + +function isRewardTx(tx: DashboardTxView): boolean { + const { kind } = classifyListedTx(tx); + return kind === 'reward' || kind === 'stake'; +} + +/** "Staked by D…", "Mined by D…" or "Producer unknown", from the producer the server read from the chain. */ +function producerText(block: DashboardBlockView): { text: string; title?: string } { + const producer = block.producer; + if (!producer) return { text: 'Producer unknown' }; + const verb = producer.kind === 'miner' ? 'Mined by' : 'Staked by'; + return { text: `${verb} ${truncateHash(producer.address, 8)}`, title: producer.address }; +} type RewardRole = 'mn' | 'stake' | 'transfer'; @@ -138,7 +177,7 @@ function LatestBlockRow({ block, stakeRewardPerBlock, isExpanded, onToggle, pric const splitStake = stakeRewardPerBlock != null && totalReward >= stakeRewardPerBlock ? stakeRewardPerBlock : 0; const splitMasternode = Math.max(totalReward - splitStake, 0); - const producerLabel = block.minedBy ? truncateHash(block.minedBy, 8) : 'Unknown'; + const producer = producerText(block); return (
@@ -153,38 +192,16 @@ function LatestBlockRow({ block, stakeRewardPerBlock, isExpanded, onToggle, pric
+ {/* The same reward goes to every block, so it waits in the opened details. */}
#{formatNumber(block.height)} {block.nTx} txs - {block.confirmations > 0 && {block.confirmations} conf}
- {truncateHash(block.hash, 10)} {formatAge(block.time)} - Producer {producerLabel} + {producer.text}
-
- {splitStake > 0 ? ( - <> - MN {formatCoin(splitMasternode)} DFCN - Stake {formatCoin(splitStake)} DFCN - - Total {formatCoin(totalReward)} DFCN - {priceUsd != null && totalReward > 0 && ` ~ $${formatSmallPrice(totalReward * priceUsd, 4)}`} - - - ) : ( - <> - {formatCoin(totalReward)} DFCN - - {priceUsd != null && totalReward > 0 - ? `~ $${formatSmallPrice(totalReward * priceUsd, 4)}` - : formatBytes(block.size)} - - - )} -
@@ -202,6 +219,19 @@ function LatestBlockRow({ block, stakeRewardPerBlock, isExpanded, onToggle, pric +
+ {splitStake > 0 && ( + <> + MN {formatCoin(splitMasternode)} DFCN + Stake {formatCoin(splitStake)} DFCN + + )} + + Block reward {formatCoin(totalReward)} DFCN + {priceUsd != null && totalReward > 0 ? ` ~ $${formatSmallPrice(totalReward * priceUsd, 4)}` : ` · ${formatBytes(block.size)}`} + +
+ {txPreviewLoading ? (
Loading {block.nTx} transaction(s)...
) : txPreview.length === 0 ? ( @@ -271,6 +301,7 @@ function LatestBlockRow({ block, stakeRewardPerBlock, isExpanded, onToggle, pric export default function DashboardPage() { const [expandedBlockHeight, setExpandedBlockHeight] = useState(null); + const [hideRewards, setHideRewards] = useState(readHideRewards); const { data: overview, isLoading: overviewLoading } = useQuery({ queryKey: ['dashboard-overview'], queryFn: fetchDashboardOverview, @@ -295,6 +326,16 @@ export default function DashboardPage() { const stats = overview?.stats; const blocks = overview?.blocks ?? EMPTY_BLOCKS; const txs = overview?.txs ?? EMPTY_TXS; + // With rewards hidden, the server's own list of other transactions; an older server sends none, so + // its latest transactions are filtered here. Never more rows than the block list shows. + const listedTxs = useMemo(() => { + const source = hideRewards ? (overview?.transfers ?? txs.filter((tx) => !isRewardTx(tx))) : txs; + return blocks.length > 0 ? source.slice(0, blocks.length) : source; + }, [hideRewards, overview?.transfers, txs, blocks.length]); + const toggleHideRewards = (hide: boolean) => { + setHideRewards(hide); + writeHideRewards(hide); + }; const totalValueTransferred24h = typeof stats?.totalValueTransferred24h === 'number' ? stats.totalValueTransferred24h : null; @@ -421,23 +462,38 @@ export default function DashboardPage() {

Latest Transactions

- - View all - +
+ + + View all + +
{overviewLoading ? (
Loading transactions...
- ) : txs.length === 0 ? ( -
No transactions available yet.
+ ) : listedTxs.length === 0 ? ( +
+ {hideRewards && txs.length > 0 ? 'No recent transactions other than rewards.' : 'No transactions available yet.'} +
) : ( - txs.map((tx) => ( + listedTxs.map((tx) => { + const kind = classifyListedTx(tx); + return (
+ {kind.label} {truncateHash(tx.txid, 10)} {tx.isDonation && Donate}
@@ -463,7 +519,7 @@ export default function DashboardPage() { <> {formatCoin(tx.totalValueOut)} DFCN - {tx.isCoinbase ? 'Block Reward' : priceUsd != null && (tx.totalValueOut || 0) > 0 + {priceUsd != null && (tx.totalValueOut || 0) > 0 ? `~ $${formatSmallPrice((tx.totalValueOut || 0) * priceUsd, 4)}` : null} @@ -471,7 +527,8 @@ export default function DashboardPage() { )}
- )) + ); + }) )}
diff --git a/client/src/types/api.ts b/client/src/types/api.ts index 90476b7..e99dbe9 100644 --- a/client/src/types/api.ts +++ b/client/src/types/api.ts @@ -151,6 +151,8 @@ export interface BlockListItemView { totalValueOut: number; reward: number; minedBy: string | null; + /** Who made the block, read from its coinstake (or a premine coinbase); null when unknown, absent from older servers. */ + producer?: { address: string; kind: 'staker' | 'miner' } | null; size: number; } @@ -170,13 +172,17 @@ export interface TxListItemView { export type DashboardBlockView = Pick< BlockListItemView, - 'hash' | 'height' | 'time' | 'nTx' | 'confirmations' | 'reward' | 'minedBy' | 'size' + 'hash' | 'height' | 'time' | 'nTx' | 'confirmations' | 'reward' | 'minedBy' | 'producer' | 'size' >; export type DashboardTxView = Pick< TxListItemView, 'txid' | 'blockheight' | 'blocktime' | 'confirmations' | 'totalValueOut' | 'isCoinbase' | 'isDonation' | 'donationAmount' ->; +> & { + /** What tells a stake from a transfer: the inputs' addresses, the outputs' values, types and first address. */ + vin?: Array<{ address?: string }>; + vout?: Array<{ value?: number; scriptPubKey?: { type?: string; addresses?: string[] } }>; +}; export type StatsView = StatsDataContract; @@ -208,6 +214,8 @@ export interface DashboardOverviewView { sync: Pick; blocks: DashboardBlockView[]; txs: DashboardTxView[]; + /** The latest transactions that are neither a block reward nor a stake; absent from older servers. */ + transfers?: DashboardTxView[]; } export interface RichListEntry { diff --git a/server/src/routes/blocks.routes.ts b/server/src/routes/blocks.routes.ts index 7d1de30..c6140ba 100644 --- a/server/src/routes/blocks.routes.ts +++ b/server/src/routes/blocks.routes.ts @@ -3,7 +3,7 @@ import { Block } from '../models/Block'; import { Transaction } from '../models/Transaction'; import { config } from '../config'; import { getChainTip } from '../services/chainTip.service'; -import { loadBlockRoles } from '../services/blockRoles.service'; +import { loadBlockRoles, withBlockProducers } from '../services/blockRoles.service'; import { withCachePolicy } from '../middleware/cachePolicy'; import { normalizeBlockAmounts, normalizeTransactionAmounts } from '../utils/amounts'; import { @@ -99,6 +99,8 @@ const BLOCK_LIST_PROJECTION = { minedBy: 1, rewardSat: 1, size: 1, + // The first two transactions name the block's producer (withBlockProducers). + txids: { $slice: 2 }, }; const BLOCK_TX_LIST_PROJECTION = { @@ -191,12 +193,12 @@ router.get('/', withCachePolicy('short'), async (req: Request, res: Response) => .sort({ height: -1 }) .limit(limit + 1) .select(BLOCK_LIST_PROJECTION) - .lean(), + .lean & { height: number; txids?: unknown }>>(), getChainTip(), ]); const hasMore = rows.length > limit; - const pageRows = hasMore ? rows.slice(0, limit) : rows; + const pageRows = await withBlockProducers(hasMore ? rows.slice(0, limit) : rows); const bestHeight = tip.height; const data = pageRows.map((block) => withBlockConfirmations(normalizeBlockAmounts(block), bestHeight) @@ -217,7 +219,13 @@ router.get('/', withCachePolicy('short'), async (req: Request, res: Response) => } const [blocks, total, tip] = await Promise.all([ - Block.find(filter).sort({ height: -1 }).skip(skip).limit(limit).select(BLOCK_LIST_PROJECTION).lean(), + Block.find(filter) + .sort({ height: -1 }) + .skip(skip) + .limit(limit) + .select(BLOCK_LIST_PROJECTION) + .lean & { height: number; txids?: unknown }>>() + .then(withBlockProducers), hasTimeFilter ? Block.countDocuments(filter) : getTotalBlockCount(), getChainTip(), ]); @@ -265,7 +273,12 @@ router.get('/latest', withCachePolicy('short'), async (req: Request, res: Respon const fetchPromise = (async () => { const [blocks, tip] = await Promise.all([ - Block.find().sort({ height: -1 }).limit(count).select(BLOCK_LIST_PROJECTION).lean(), + Block.find() + .sort({ height: -1 }) + .limit(count) + .select(BLOCK_LIST_PROJECTION) + .lean & { height: number; txids?: unknown }>>() + .then(withBlockProducers), getChainTip(), ]); const bestHeight = tip.height; diff --git a/server/src/routes/dashboard.routes.ts b/server/src/routes/dashboard.routes.ts index 7a2aa9a..deb4437 100644 --- a/server/src/routes/dashboard.routes.ts +++ b/server/src/routes/dashboard.routes.ts @@ -7,14 +7,20 @@ import { withCachePolicy } from '../middleware/cachePolicy'; import { getChainTip } from '../services/chainTip.service'; import { rpcService } from '../services/rpc.service'; import { getStatsData } from '../services/stats.service'; +import { withBlockProducers } from '../services/blockRoles.service'; +import { stakerOf, type RoleTx } from '../utils/blockRoles'; import { normalizeBlockAmounts, normalizeTransactionAmounts } from '../utils/amounts'; import { sendInternalError } from '../utils/validation'; import { mapPublicSyncError } from '../utils/publicSyncError'; const router = Router(); +// The two lists on the home page show the same number of rows. const BLOCKS_LIMIT = 10; -const TXS_LIMIT = 14; +const TXS_LIMIT = 10; +// "Hide rewards" lists the latest transactions that are neither a block reward nor a stake, found +// among this many latest non-coinbase transactions. +const TRANSFER_SCAN = 200; const TTL_MS = Math.max(15_000, Math.min(30_000, config.cache.ttlSeconds * 2000)); const STALE_MAX_MS = Math.max(TTL_MS * 4, 120_000); @@ -28,6 +34,8 @@ const BLOCK_LIST_PROJECTION = { minedBy: 1, rewardSat: 1, size: 1, + // The first two transactions name the block's producer (withBlockProducers). + txids: { $slice: 2 }, }; const TX_LIST_PROJECTION = { @@ -39,10 +47,20 @@ const TX_LIST_PROJECTION = { feeSat: 1, isCoinbase: 1, size: 1, + // What the client needs to tell a stake from a transfer (classifyTransaction). + 'vin.address': 1, 'vout.valueSat': 1, + 'vout.scriptPubKey.type': 1, 'vout.scriptPubKey.addresses': { $slice: 1 }, }; +// What stakerOf needs, so that stakes can be left out of the transfers list. +const TRANSFER_SCAN_PROJECTION = { + ...TX_LIST_PROJECTION, + 'vout.scriptPubKey.hex': 1, + 'vout.scriptPubKey.addresses': 1, +}; + function withBlockConfirmations( block: T, bestHeight: number @@ -73,6 +91,8 @@ type DashboardPayload = { }; blocks: Array>; txs: Array>; + /** The latest transactions that are neither a block reward nor a stake (for "Hide rewards"). */ + transfers: Array>; }; }; @@ -80,11 +100,21 @@ let cached: { atMs: number; payload: DashboardPayload } | null = null; let inFlight: Promise | null = null; async function buildDashboardPayload(): Promise { - const [stats, tip, blocks, txs, syncState, daemonHeightResult] = await Promise.all([ + const [stats, tip, blocks, txs, transferCandidates, syncState, daemonHeightResult] = await Promise.all([ getStatsData(), getChainTip(), - Block.find().sort({ height: -1 }).limit(BLOCKS_LIMIT).select(BLOCK_LIST_PROJECTION).lean(), + Block.find() + .sort({ height: -1 }) + .limit(BLOCKS_LIMIT) + .select(BLOCK_LIST_PROJECTION) + .lean & { height: number; txids?: unknown }>>() + .then(withBlockProducers), Transaction.find().sort({ blockheight: -1, _id: -1 }).limit(TXS_LIMIT).select(TX_LIST_PROJECTION).lean(), + Transaction.find({ isCoinbase: false }) + .sort({ blockheight: -1, _id: -1 }) + .limit(TRANSFER_SCAN) + .select(TRANSFER_SCAN_PROJECTION) + .lean & RoleTx & { blockheight: number }>>(), SyncState.findOne({ key: 'main' }).lean(), rpcService.getBlockCount().catch(() => null), ]); @@ -93,9 +123,13 @@ async function buildDashboardPayload(): Promise { const normalizedBlocks = blocks.map((block) => withBlockConfirmations(normalizeBlockAmounts(block), bestHeight) ); - const normalizedTxs = txs.map((tx) => - withTxConfirmations(normalizeTransactionAmounts(tx, { maxVoutAddresses: 1 }), bestHeight) - ); + const normalizeTx = (tx: Record & { blockheight: number }) => + withTxConfirmations(normalizeTransactionAmounts(tx, { maxVoutAddresses: 1 }), bestHeight); + const normalizedTxs = txs.map(normalizeTx); + const transfers = transferCandidates + .filter((tx) => stakerOf(tx) == null) + .slice(0, TXS_LIMIT) + .map(normalizeTx); const daemonHeight = typeof daemonHeightResult === 'number' ? daemonHeightResult : -1; const lastSyncedHeight = syncState?.lastSyncedHeight ?? -1; @@ -116,6 +150,7 @@ async function buildDashboardPayload(): Promise { }, blocks: normalizedBlocks, txs: normalizedTxs, + transfers, }, }; } diff --git a/server/src/services/blockRoles.service.ts b/server/src/services/blockRoles.service.ts index a7256ed..fc9b6ba 100644 --- a/server/src/services/blockRoles.service.ts +++ b/server/src/services/blockRoles.service.ts @@ -1,6 +1,6 @@ import { Block } from '../models/Block'; import { Transaction } from '../models/Transaction'; -import { blockRoles, stakerOf, type BlockRoles, type RoleTx } from '../utils/blockRoles'; +import { blockRoles, stakerOf, type BlockProducer, type BlockRoles, type RoleTx } from '../utils/blockRoles'; const ROLE_TX_PROJECTION = { _id: 0, @@ -22,6 +22,23 @@ export async function loadBlockRoles(txids: unknown): Promise { return blockRoles(txids, txs); } +/** + * The producer of each listed block, from the blocks' first two transactions in one query. Each + * block needs its first two `txids` (a `{ txids: { $slice: 2 } }` projection is enough); the list + * comes back in the same order, without `txids`, with `producer` (null when unknown). + */ +export async function withBlockProducers( + blocks: T[] +): Promise> { + const firstTwo = blocks.flatMap((block) => + Array.isArray(block.txids) ? block.txids.slice(0, 2).filter((txid): txid is string => typeof txid === 'string') : [] + ); + const txs = firstTwo.length > 0 + ? await Transaction.find({ txid: { $in: firstTwo } }).select(ROLE_TX_PROJECTION).lean() + : []; + return blocks.map(({ txids, ...block }) => ({ ...block, producer: blockRoles(txids, txs).producer }) as T & { producer: BlockProducer | null }); +} + /** * How many different addresses staked a block since `sinceTime` (unix seconds), read from each * block's coinstake. Undefined when no block in the window has an identifiable staker. diff --git a/server/test/homeLists.integration.test.ts b/server/test/homeLists.integration.test.ts new file mode 100644 index 0000000..28eb33f --- /dev/null +++ b/server/test/homeLists.integration.test.ts @@ -0,0 +1,139 @@ +import express from 'express'; +import mongoose from 'mongoose'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import dashboardRoutes, { invalidateDashboardCache } from '../src/routes/dashboard.routes'; +import blocksRoutes from '../src/routes/blocks.routes'; +import * as statsService from '../src/services/stats.service'; +import * as chainTipService from '../src/services/chainTip.service'; +import { rpcService } from '../src/services/rpc.service'; +import { Block } from '../src/models/Block'; +import { Transaction } from '../src/models/Transaction'; + +// This suite requires an explicitly supplied disposable localhost database. +// The normal unit suite must never connect to an operator's configured MongoDB. +const baseUri = process.env.TEST_POSE_MONGO_URI; + +const STAKER = 'DNSSwp3CWfyus5h8TSBvJHFoTUASQCF8Rj'; +const PAYEE = 'DGK3yNxxedc2pvaPPwTbVBey2NmFC8FUGZ'; +const SENDER = 'D8e1nUDayNHvXSYZPv1QECNcSgCxgsXw9d'; +const RECEIVER = 'DKgo69ycaxuut3QxaTSfyqbkFvyRvvq8Hf'; +const TIP = 1_000; +const BLOCK_COUNT = 14; +const dec = (sat: bigint) => mongoose.Types.Decimal128.fromString(sat.toString()); +const COIN = 100_000_000n; + +// Shaped like the chain stores them. A proof-of-stake coinbase and a coinstake open with an empty +// marker output: worth nothing, paying no address, with an empty script. +const marker = () => ({ valueSat: dec(0n), scriptPubKey: { type: 'nonstandard', hex: '' } }); +const pay = (coins: bigint, address: string) => ({ + valueSat: dec(coins * COIN), scriptPubKey: { type: 'pubkeyhash', hex: '76a914' + '00'.repeat(20) + '88ac', addresses: [address] }, +}); +const id = (label: string, height: number) => `${label}${height}`.padStart(64, '0'); + +// Every block: a coinbase paying the masternode and a coinstake of STAKER. Every second block also +// carries a transfer from SENDER to RECEIVER. +function chain() { + const blocks: Array> = []; + const txs: Array> = []; + for (let n = 0; n < BLOCK_COUNT; n++) { + const height = TIP - n; + const time = 1_800_000_000 + height * 150; + const common = { blockhash: height.toString(16).padStart(64, 'a'), blockheight: height, blocktime: time }; + const coinbase = { ...common, txid: id('cb', height), isCoinbase: true, vin: [{ coinbase: '03aa0d02' }], vout: [marker(), pay(10_000n, PAYEE)] }; + const stake = { + ...common, txid: id('cs', height), isCoinbase: false, + vin: [{ txid: id('p', height), vout: 1, address: STAKER, valueSat: dec(25_000n * COIN) }], + vout: [marker(), pay(25_500n, STAKER)], + }; + const blockTxs = [coinbase, stake]; + if (n % 2 === 0) { + blockTxs.push({ + ...common, txid: id('tr', height), isCoinbase: false, + vin: [{ txid: id('q', height), vout: 0, address: SENDER, valueSat: dec(100n * COIN) }], + vout: [pay(40n, RECEIVER), pay(59n, SENDER)], + }); + } + txs.push(...blockTxs); + blocks.push({ + hash: common.blockhash, height, time, nTx: blockTxs.length, size: 500, difficulty: 1, + version: 1, merkleroot: 'm'.repeat(64), nonce: 0, bits: '1d00ffff', + // What the indexer stores as minedBy: the first address the coinbase pays, here the masternode. + minedBy: PAYEE, rewardSat: dec(10_500n * COIN), totalValueOutSat: dec(35_599n * COIN), + txids: blockTxs.map((tx) => tx.txid), + }); + } + return { blocks, txs }; +} + +describe.skipIf(!baseUri)('home page lists and block lists with disposable MongoDB', () => { + const app = express(); + app.use('/api/dashboard', dashboardRoutes); + app.use('/api/blocks', blocksRoutes); + + beforeAll(async () => { + if (!baseUri || !/^mongodb:\/\/127\.0\.0\.1:\d+\/deftrack_pose_test_[a-f0-9]+$/.test(baseUri)) { + throw new Error('TEST_POSE_MONGO_URI must name an isolated localhost test database'); + } + // Own database, so it cannot collide with other integration suites that may run at the same time. + await mongoose.connect(`${baseUri}dl`, { serverSelectionTimeoutMS: 5000 }); + await Promise.all([Block.init(), Transaction.init()]); + const { blocks, txs } = chain(); + await Promise.all([Block.deleteMany({}), Transaction.deleteMany({})]); + await Promise.all([Block.insertMany(blocks), Transaction.insertMany(txs)]); + }); + beforeEach(() => { + invalidateDashboardCache(); + vi.spyOn(statsService, 'getStatsData').mockResolvedValue({} as never); + vi.spyOn(chainTipService, 'getChainTip').mockResolvedValue({ height: TIP, time: 1_800_000_000 + TIP * 150, hash: 'tip' }); + vi.spyOn(rpcService, 'getBlockCount').mockResolvedValue(TIP); + }); + afterAll(async () => { + if (mongoose.connection.readyState === 1) await mongoose.connection.dropDatabase(); + await mongoose.disconnect(); + }); + + it('the home page overview names each block\'s staker, not the masternode it paid', async () => { + const res = await request(app).get('/api/dashboard/overview'); + + expect(res.status).toBe(200); + const blocks = res.body.data.blocks as Array<{ height: number; producer: unknown; minedBy: string; txids?: unknown }>; + expect(blocks).toHaveLength(10); + for (const block of blocks) { + expect(block.producer).toEqual({ address: STAKER, kind: 'staker' }); + expect(block.minedBy).toBe(PAYEE); + expect(block.txids).toBeUndefined(); + } + }); + + it('the latest transactions and the blocks are equally many, and carry what tells a stake from a transfer', async () => { + const res = await request(app).get('/api/dashboard/overview'); + + const txs = res.body.data.txs as Array<{ vin: Array<{ address?: string }>; vout: Array<{ scriptPubKey?: { type?: string } }> }>; + expect(txs).toHaveLength(res.body.data.blocks.length); + const stake = txs.find((tx) => tx.vin.some((input) => input.address === STAKER)); + expect(stake?.vout.map((output) => output.scriptPubKey?.type)).toEqual(['nonstandard', 'pubkeyhash']); + }); + + it('the transfers list leaves out block rewards and stakes', async () => { + const res = await request(app).get('/api/dashboard/overview'); + + const transfers = res.body.data.transfers as Array<{ txid: string; isCoinbase: boolean; blockheight: number }>; + // Seven of the fourteen blocks carry a transfer. + expect(transfers.map((tx) => tx.txid)).toEqual( + Array.from({ length: 7 }, (_, n) => id('tr', TIP - 2 * n)) + ); + expect(transfers.every((tx) => !tx.isCoinbase)).toBe(true); + }); + + it('the block list names each block\'s staker, on every way of paging', async () => { + for (const path of ['/api/blocks?cursor=1&limit=5', '/api/blocks?page=2&limit=5', '/api/blocks/latest?count=5']) { + const res = await request(app).get(path); + expect({ path, status: res.status }).toEqual({ path, status: 200 }); + expect(res.body.data).toHaveLength(5); + for (const block of res.body.data as Array<{ producer: unknown; txids?: unknown }>) { + expect({ path, producer: block.producer, txids: block.txids }).toEqual({ path, producer: { address: STAKER, kind: 'staker' }, txids: undefined }); + } + } + }); +}); diff --git a/shared/src/types/block.ts b/shared/src/types/block.ts index 86ab035..8267bac 100644 --- a/shared/src/types/block.ts +++ b/shared/src/types/block.ts @@ -22,7 +22,7 @@ export interface IBlock { nextblockhash?: string; /** The first address the coinbase pays: the masternode in a proof-of-stake block, not its producer. */ minedBy?: string; - /** Block detail only: the producer read from the coinstake (or a premine coinbase); null when unknown. */ + /** Block detail and block lists: the producer read from the coinstake (or a premine coinbase); null when unknown. */ producer?: BlockProducer | null; /** Block detail only: the one address the coinbase of a proof-of-stake block pays; null when unknown. */ masternodePayee?: string | null;