diff --git a/packages/message-registry/src/aztec.ts b/packages/message-registry/src/aztec.ts index fbce100b3..6efaac011 100644 --- a/packages/message-registry/src/aztec.ts +++ b/packages/message-registry/src/aztec.ts @@ -26,6 +26,13 @@ export type NewBlockEvent = BlockEvent & { ordered?: { proposedTip: number }; }; +/** + * The deepest prune the listener follows and the longest chain walk the API + * takes: a prune within it leaves no more canonical blocks above the next + * ordered block's proposed tip than the API demotes. + */ +export const CHAIN_WALK_BOUND = 10_000; + export type PendingTxsEvent = { txs: ChicmozL2PendingTx[]; }; diff --git a/services/aztec-listener/src/environment.ts b/services/aztec-listener/src/environment.ts index 1d12262e3..46c87b13c 100644 --- a/services/aztec-listener/src/environment.ts +++ b/services/aztec-listener/src/environment.ts @@ -1,8 +1,10 @@ +import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry"; import { l2NetworkIdSchema, rpcNodePoolSchema, type L2NetworkId, } from "@chicmoz-pkg/types"; +import { MAX_RPC_BLOCKS_LEN } from "@aztec-labs/stdlib/interfaces/api-limit"; import { z } from "zod"; /** @@ -21,10 +23,6 @@ export const BLOCK_POLL_INTERVAL_MS = z.coerce .number() .default(3000) .parse(process.env.BLOCK_POLL_INTERVAL_MS); -export const CATCHUP_POLL_WAIT_TIME_MS = z.coerce - .number() - .default(100) - .parse(process.env.CATCHUP_POLL_WAIT_TIME_MS); export const TX_POLL_INTERVAL_MS = z.coerce .number() .default(4000) // NOTE: https://github.com/aztec-scan/chicmoz/issues/430#issuecomment-2841287541 @@ -33,10 +31,6 @@ export const CHAIN_INFO_POLL_INTERVAL_MS = z.coerce .number() .default(30000) .parse(process.env.CHAIN_INFO_POLL_INTERVAL_MS); -export const L2_TIPS_POLL_INTERVAL_MS = z.coerce - .number() - .default(5000) - .parse(process.env.L2_TIPS_POLL_INTERVAL_MS); export const L2_TIPS_HEARTBEAT_INTERVAL_MS = z.coerce .number() .default(60000) @@ -79,7 +73,8 @@ export const AZTEC_MAX_PRUNE_DEPTH = z.coerce .number() .int() .positive() - .default(10_000) + .max(CHAIN_WALK_BOUND) + .default(CHAIN_WALK_BOUND) .parse(process.env.AZTEC_MAX_PRUNE_DEPTH); export const AZTEC_STREAM_STALL_ALERT_MS = z.coerce .number() @@ -93,6 +88,20 @@ export const AZTEC_NODE_PROBE_TIMEOUT_MS = z.coerce .positive() .default(2_000) .parse(process.env.AZTEC_NODE_PROBE_TIMEOUT_MS); +export const AZTEC_BLOCK_STREAM_BATCH_SIZE = z.coerce + .number() + .int() + .positive() + .max(MAX_RPC_BLOCKS_LEN) + .default(10) + .parse(process.env.AZTEC_BLOCK_STREAM_BATCH_SIZE); +/** The most proven blocks one pass runs the fee-juice balance work on. */ +export const AZTEC_PROVEN_BLOCKS_PER_PASS = z.coerce + .number() + .int() + .positive() + .default(200) + .parse(process.env.AZTEC_PROVEN_BLOCKS_PER_PASS); export const L2_BLOCK_RANGE_REQUEST_MAX_RANGES = z.coerce .number() .int() @@ -152,11 +161,21 @@ export const L2_NETWORK_ID: L2NetworkId = l2NetworkIdSchema.parse( export const AZTEC_RPC_URLS = rpcNodePoolSchema.parse( process.env.AZTEC_RPC_URLS, ); +// A pool URL can carry a key in its userinfo, path or query. +const printedUrl = (url: string) => { + try { + const { protocol, host, pathname, search } = new URL(url); + const more = pathname.length > 1 || search !== "" ? "/…" : ""; + return `${protocol}//${host}${more}`; + } catch { + return "(not a URL)"; + } +}; const printPool = () => { let finalString = "\n"; AZTEC_RPC_URLS.forEach( (node) => - (finalString = `${finalString} Name: ${node.name}\n URL: ${node.url}\n\n`), + (finalString = `${finalString} Name: ${node.name}\n URL: ${printedUrl(node.url)}\n\n`), ); return finalString.trim(); }; @@ -187,8 +206,6 @@ CHAIN_INFO_POLL_INTERVAL_MS: ${CHAIN_INFO_POLL_INT }s AZTEC_LISTEN_FOR_L2_TIPS: ${AZTEC_LISTEN_FOR_L2_TIPS ? "✅" : "❌" } -L2_TIPS_POLL_INTERVAL_MS: ${L2_TIPS_POLL_INTERVAL_MS / 1000 - }s L2_TIPS_HEARTBEAT_INTERVAL_MS: ${L2_TIPS_HEARTBEAT_INTERVAL_MS / 1000 }s AZTEC_ENABLE_FULL_SWEEP_CATCHUP: ${AZTEC_ENABLE_FULL_SWEEP_CATCHUP ? "✅" : "❌" @@ -196,6 +213,8 @@ AZTEC_ENABLE_FULL_SWEEP_CATCHUP: ${AZTEC_ENABLE_FULL_S AZTEC_MAX_PRUNE_DEPTH: ${AZTEC_MAX_PRUNE_DEPTH} AZTEC_STREAM_STALL_ALERT_MS: ${AZTEC_STREAM_STALL_ALERT_MS / 1000}s AZTEC_NODE_PROBE_TIMEOUT_MS: ${AZTEC_NODE_PROBE_TIMEOUT_MS / 1000}s +AZTEC_BLOCK_STREAM_BATCH_SIZE: ${AZTEC_BLOCK_STREAM_BATCH_SIZE} +AZTEC_PROVEN_BLOCKS_PER_PASS: ${AZTEC_PROVEN_BLOCKS_PER_PASS} MAX_BATCH_SIZE_FETCH_MISSED_BLOCKS: ${MAX_BATCH_SIZE_FETCH_MISSED_BLOCKS} L2_BLOCK_RANGE_REQUEST_MAX_RANGES: ${L2_BLOCK_RANGE_REQUEST_MAX_RANGES} L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS: ${L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS} diff --git a/services/aztec-listener/src/events/emitted/index.ts b/services/aztec-listener/src/events/emitted/index.ts index 909efc3e7..193bbcddb 100644 --- a/services/aztec-listener/src/events/emitted/index.ts +++ b/services/aztec-listener/src/events/emitted/index.ts @@ -11,9 +11,11 @@ import type { L2BlockStatusHint, L2TipsEvent, } from "@chicmoz-pkg/message-registry"; +import { L2_NETWORK_ID } from "../../environment.js"; import { logger } from "../../logger.js"; import { txsController } from "../../svcs/database/index.js"; import { + publishKeyedMessage, publishMessage, publishMessageSync, } from "../../svcs/message-bus/index.js"; @@ -30,27 +32,26 @@ const toSafeBlockNumber = (value: bigint): number => { return blockNumber; }; -export const onBlock = async ( - block: L2Block, - statusHint: L2BlockStatusHint, -) => { +/** + * Sends a block of the ordered stream, keyed by the network so the topic + * keeps the send order. `proposedTip` is the proposed tip of the pass that + * sends it. + */ +export const onOrderedBlock = async (block: L2Block, proposedTip: number) => { const height = BigInt(block.header.globalVariables.blockNumber.toString()); const heightNumber = toSafeBlockNumber(height); - const statusHintStr = - statusHint === "proposed" - ? "🦊 publishing proposed block" - : "🐴 publishing proven block"; logger.info( - `${statusHintStr} ${height} (hash: ${( + `🦊 publishing block ${height} (hash: ${( await block.hash() - ).toString()})...`, + ).toString()}, proposed tip ${proposedTip})...`, ); const blockBuffer = block.toBuffer() as Uint8Array; const blockStr = Buffer.from(blockBuffer).toString("hex"); - await publishMessage("NEW_BLOCK_EVENT", { + await publishKeyedMessage("NEW_BLOCK_EVENT", L2_NETWORK_ID, { block: blockStr, - statusHint, + statusHint: "proposed", blockNumber: heightNumber, + ordered: { proposedTip }, }); const potentiallyIncludedTxs = await txsController.getTxs([ "pending", @@ -61,12 +62,10 @@ export const onBlock = async ( ); for (const potentialTx of potentiallyIncludedTxs) { - const txFoundInBlock = blockTxHashes.includes(potentialTx.txHash); - if (txFoundInBlock) { - const newState = statusHint; - await txsController.storeOrUpdate(potentialTx, newState); + if (blockTxHashes.includes(potentialTx.txHash)) { + await txsController.storeOrUpdate(potentialTx, "proposed"); logger.info( - `✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to ${newState}`, + `✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to proposed`, ); } } @@ -75,7 +74,10 @@ export const onBlock = async ( export const onCatchupBlock = async ( block: L2Block, statusHint: L2BlockStatusHint, - metadata: Pick = {}, + metadata: Pick< + CatchupBlockEvent, + "requestId" | "catchupReason" | "finalized" + > = {}, ) => { const blockNumber = BigInt( block.header.globalVariables.blockNumber.toString(), diff --git a/services/aztec-listener/src/events/received/on-l2-block-range-request.ts b/services/aztec-listener/src/events/received/on-l2-block-range-request.ts index 692d926cc..20e0917f0 100644 --- a/services/aztec-listener/src/events/received/on-l2-block-range-request.ts +++ b/services/aztec-listener/src/events/received/on-l2-block-range-request.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "@chicmoz-pkg/message-bus"; +import { EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { generateL2TopicName, getConsumerGroupId, @@ -17,11 +17,9 @@ import { } from "../../environment.js"; import { onCatchupBlock } from "../emitted/index.js"; import { logger } from "../../logger.js"; -import { - getBlock, - getLatestProposedHeight, - getLatestProvenHeight, -} from "../../svcs/poller/network-client/index.js"; +import { openAttestedReader } from "../../svcs/poller/network-client/attested-reads.js"; +import { getRpcNode } from "../../svcs/poller/network-client/pool.js"; +import { streamRollupVersion } from "../../svcs/poller/pollers/block_poller/index.js"; const inFlightRequests = new Set(); @@ -85,7 +83,10 @@ export const clampRangeRequest = ({ }; }; -const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { +const processL2BlockRangeRequest = async ( + event: L2BlockRangeRequestEvent, + heartbeat: Heartbeat, +) => { const requestAgeMs = Date.now() - event.requestedAt; if (requestAgeMs > L2_BLOCK_RANGE_REQUEST_MAX_AGE_MS) { logger.warn( @@ -93,8 +94,14 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { ); return; } - const proposedHeight = toSafeHeight(await getLatestProposedHeight()); - const provenHeight = toSafeHeight(await getLatestProvenHeight()); + // One node answers the whole request, so its tips attest the blocks it serves. + const reader = await openAttestedReader( + getRpcNode(), + streamRollupVersion(), + heartbeat, + ); + const proposedHeight = toSafeHeight(reader.tips.proposed.number); + const provenHeight = toSafeHeight(reader.tips.proven.block.number); const maxBlocks = Math.min( event.maxBlocks ?? L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS, L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS, @@ -118,18 +125,23 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { } for (let height = range.from; height <= range.to && publishedBlocks < maxBlocks; height++) { - const block = await getBlock(height); - if (!block) { + // Before every read and publish: two slow calls in a row can outlast the + // Kafka session. + await heartbeat(); + const read = await reader.getBlock(height); + if (!read) { failedHeights++; logger.warn(`Requested catchup block ${height} not found for ${event.requestId}`); continue; } + await heartbeat(); await onCatchupBlock( - block, + read.block, range.statusHint, { requestId: event.requestId, catchupReason: event.reason === "tip_boundary_mismatch" ? "reorg_repair" : event.reason, + ...(read.finalized ? { finalized: true as const } : {}), }, ); publishedBlocks++; @@ -141,7 +153,10 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { ); }; -const onL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { +const onL2BlockRangeRequest = async ( + event: L2BlockRangeRequestEvent, + heartbeat: Heartbeat, +) => { const dedupKey = getL2BlockRangeRequestDedupKey(event); if (inFlightRequests.has(dedupKey)) { logger.info(`Deduped in-flight L2 block range request ${event.requestId}; key=${dedupKey}`); @@ -150,7 +165,9 @@ const onL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { inFlightRequests.add(dedupKey); try { - await requestLimiter.schedule(() => processL2BlockRangeRequest(event)); + await requestLimiter.schedule(() => + processL2BlockRangeRequest(event, heartbeat), + ); } catch (error) { if (error instanceof Bottleneck.BottleneckError) { logger.warn(`Skipped queued L2 block range request ${event.requestId}: ${error.message}`); @@ -169,5 +186,8 @@ export const l2BlockRangeRequestHandler: EventHandler = { handlerName: "blockRangeRequestHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "L2_BLOCK_RANGE_REQUEST_EVENT"), - cb: onL2BlockRangeRequest as (arg0: unknown) => Promise, + cb: onL2BlockRangeRequest as ( + arg0: unknown, + heartbeat: Heartbeat, + ) => Promise, }; diff --git a/services/aztec-listener/src/svcs/database/heights.controller.ts b/services/aztec-listener/src/svcs/database/heights.controller.ts index 7cfd52a9e..20254b789 100644 --- a/services/aztec-listener/src/svcs/database/heights.controller.ts +++ b/services/aztec-listener/src/svcs/database/heights.controller.ts @@ -1,7 +1,7 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { eq, getTableColumns } from "drizzle-orm"; +import { eq, getTableColumns, sql } from "drizzle-orm"; import { L2_NETWORK_ID } from "../../environment.js"; import { heightsTable } from "./schema.js"; +import { db } from "./transaction.js"; export async function storeProcessedProposedBlockHeight(height: number) { await db() @@ -17,38 +17,12 @@ export async function storeProcessedProvenBlockHeight(height: number) { .where(eq(heightsTable.networkId, L2_NETWORK_ID)); } -export async function storeChainProposedBlockHeight(height: number) { - await db() - .update(heightsTable) - .set({ chainProposedBlockHeight: height }) - .where(eq(heightsTable.networkId, L2_NETWORK_ID)); -} - -export async function storeChainProvenBlockHeight(height: number) { - await db() - .update(heightsTable) - .set({ chainProvenBlockHeight: height }) - .where(eq(heightsTable.networkId, L2_NETWORK_ID)); -} - -export async function storeBlockHeights({ - processedProposedBlockHeight, - chainProposedBlockHeight, - processedProvenBlockHeight, - chainProvenBlockHeight, -}: { - processedProposedBlockHeight: number; - chainProposedBlockHeight: number; - processedProvenBlockHeight: number; - chainProvenBlockHeight: number; -}) { +/** Moves the proven side work's cursor back to `height`; never forward. */ +export async function lowerProcessedProvenBlockHeight(height: number) { await db() .update(heightsTable) .set({ - processedProposedBlockHeight, - chainProposedBlockHeight, - processedProvenBlockHeight, - chainProvenBlockHeight, + processedProvenBlockHeight: sql`LEAST(${heightsTable.processedProvenBlockHeight}, ${height})`, }) .where(eq(heightsTable.networkId, L2_NETWORK_ID)); } @@ -72,6 +46,8 @@ export async function getBlockHeights() { .from(heightsTable) .where(eq(heightsTable.networkId, L2_NETWORK_ID)) .limit(1); - if (result.length === 0) {throw new Error("FATAL: block heights not initialized");} + if (result.length === 0) { + throw new Error("FATAL: block heights not initialized"); + } return result[0]; } diff --git a/services/aztec-listener/src/svcs/database/schema.ts b/services/aztec-listener/src/svcs/database/schema.ts index 18e110908..6bd1d6e84 100644 --- a/services/aztec-listener/src/svcs/database/schema.ts +++ b/services/aztec-listener/src/svcs/database/schema.ts @@ -18,6 +18,8 @@ export const heightsTable = pgTable("heights", { processedProposedBlockHeight: integer( "processedProposedBlockHeight", ).notNull(), + // The old listener's last chain heights. Nothing updates them: the block + // stream's first start takes chainProvenBlockHeight as its floor. chainProposedBlockHeight: integer("chainProposedBlockHeight").notNull(), processedProvenBlockHeight: integer("processedProvenBlockHeight").notNull(), chainProvenBlockHeight: integer("chainProvenBlockHeight").notNull(), diff --git a/services/aztec-listener/src/svcs/database/txs.controller.ts b/services/aztec-listener/src/svcs/database/txs.controller.ts index de1cc8edd..5368c76b0 100644 --- a/services/aztec-listener/src/svcs/database/txs.controller.ts +++ b/services/aztec-listener/src/svcs/database/txs.controller.ts @@ -42,6 +42,12 @@ const buildTxRow = ( }; }; +const toStoredTx = (row: typeof txsTable.$inferSelect) => ({ + ...row, + initiator: row.initiator ?? undefined, + additionalMsgSenders: row.additionalMsgSenders ?? undefined, +}); + export const storeOrUpdate = async ( pendingTx: ChicmozL2PendingTx & StoredTxMetadata, txState: TxState, @@ -70,11 +76,20 @@ export const getTxs = async ( .from(txsTable) .where(inArray(txsTable.txState, statesWhitelist)); - return rows.map((row) => ({ - ...row, - initiator: row.initiator ?? undefined, - additionalMsgSenders: row.additionalMsgSenders ?? undefined, - })); + return rows.map(toStoredTx); +}; + +/** The stored txs among `txHashes`, whatever their state. */ +export const getTxsByHashes = async (txHashes: HexString[]) => { + if (txHashes.length === 0) { + return []; + } + const rows = await db() + .select() + .from(txsTable) + .where(inArray(txsTable.txHash, txHashes)); + + return rows.map(toStoredTx); }; export const storeOrUpdateState = async ( diff --git a/services/aztec-listener/src/svcs/message-bus/index.ts b/services/aztec-listener/src/svcs/message-bus/index.ts index 33124e09d..3568948ac 100644 --- a/services/aztec-listener/src/svcs/message-bus/index.ts +++ b/services/aztec-listener/src/svcs/message-bus/index.ts @@ -1,6 +1,7 @@ import { EventHandler, generateSvc, + publishKeyedMessage as pubKeyed, publishMessage as pub, startSubscribe as sub, } from "@chicmoz-pkg/message-bus"; @@ -24,6 +25,20 @@ export const publishMessage = async ( await pub(topic, message); }; +/** + * Publishes under `key`. One key maps to one partition, so messages keep + * their order only while each send is awaited before the next. + */ +export const publishKeyedMessage = async ( + eventType: K, + key: string, + message: L2_MESSAGES[K], +) => { + const topic = generateL2TopicName(L2_NETWORK_ID, eventType); + logger.info(`Publishing message to topic ${topic} with key ${key}`); + await pubKeyed(topic, key, message); +}; + export const publishMessageSync = ( ...args: Parameters ) => { diff --git a/services/aztec-listener/src/svcs/poller/index.ts b/services/aztec-listener/src/svcs/poller/index.ts index 8ece09b29..595ad3580 100644 --- a/services/aztec-listener/src/svcs/poller/index.ts +++ b/services/aztec-listener/src/svcs/poller/index.ts @@ -2,7 +2,6 @@ import { MicroserviceBaseSvc } from "@chicmoz-pkg/microservice-base"; import { NODE_ENV, NodeEnv } from "@chicmoz-pkg/types"; import { AZTEC_LISTEN_FOR_CHAIN_INFO, - AZTEC_LISTEN_FOR_L2_TIPS, AZTEC_LISTEN_FOR_PENDING_TXS, getConfigStr, } from "../../environment.js"; @@ -13,7 +12,6 @@ import * as blockPoller from "./pollers/block_poller/index.js"; import * as chainInfoPoller from "./pollers/chain-info-poller.js"; import * as pendingTxsPoller from "./pollers/txs_poller.js"; import * as droppedTxVerifier from "./pollers/dropped-tx-verifier.js"; -import * as l2TipsPoller from "./pollers/l2-tips-poller.js"; import * as processReport from "./process-report.js"; import { NodeInfo } from "@aztec-labs/aztec.js/contracts"; @@ -37,6 +35,7 @@ export const init = async () => { } await ensureInitializedBlockHeights(); const initResult = await initNetworkClient(); + await blockPoller.init(); // Initialize with chainInfo and use type assertions to satisfy TypeScript nodeInfo = { nodeVersion: "unknown", @@ -64,9 +63,6 @@ export const startPoller = () => { if (AZTEC_LISTEN_FOR_CHAIN_INFO) { chainInfoPoller.startPolling(); } - if (AZTEC_LISTEN_FOR_L2_TIPS) { - l2TipsPoller.startPolling(); - } }; export const getNodeInfo = () => nodeInfo; @@ -83,7 +79,6 @@ export const pollerService: MicroserviceBaseSvc = { pendingTxsPoller.stopPolling(); blockPoller.stopPolling(); chainInfoPoller.stopPolling(); - l2TipsPoller.stopPolling(); droppedTxVerifier.stop(); processReport.stop(); }, diff --git a/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts b/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts new file mode 100644 index 000000000..3d03a5fdc --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts @@ -0,0 +1,87 @@ +import { L2Block } from "@aztec-labs/aztec.js/block"; +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { type L2Tips } from "@aztec-labs/stdlib/block"; +import { NodeCheckError, bodyFault } from "./block-stream-source.js"; +import { callNodeFunction } from "./index.js"; +import { type RpcNode } from "./pool.js"; + +/** `finalized`: at or below the serving node's own finalized tip, on the stream's rollup version. */ +export type AttestedBlock = { block: L2Block; finalized: boolean }; + +export type AttestedReader = { + node: RpcNode; + /** The node's tips, read before any of its blocks. */ + tips: L2Tips; + /** The node's block at `height`, or undefined when it has none. */ + getBlock(height: number): Promise; +}; + +/** + * Pins `node` for one request. Its tips and rollup version are read before + * its blocks, and a finalized block cannot change, so `finalized` holds for + * every block read after them. Only the stream's own `rollupVersion` gets + * `finalized`. A caller whose session two slow reads can outlast passes its + * `heartbeat`, which runs between them. + */ +export const openAttestedReader = async ( + node: RpcNode, + rollupVersion: number | undefined, + heartbeat?: () => Promise, +): Promise => { + const tips = await callNodeFunction("getChainTips", [], node); + await heartbeat?.(); + const info = await callNodeFunction("getNodeInfo", [], node); + // The RPC client resolves a null answer to undefined, whatever the type. + if (tips === undefined || info === undefined) { + throw new Error( + `Node ${node.name} answered its tips or node info with nothing`, + ); + } + const version = + rollupVersion !== undefined && info.rollupVersion === rollupVersion + ? BigInt(rollupVersion) + : undefined; + return { + node, + tips, + getBlock: async (height) => { + const response = await callNodeFunction( + "getBlock", + [BlockNumber(height), { includeTransactions: true }], + node, + ); + if (response === undefined) { + return undefined; + } + const number = response.header.globalVariables.blockNumber; + if (number !== height) { + throw new NodeCheckError( + `Node ${node.name} sent block ${number} where ${height} was asked`, + ); + } + if (response.body === undefined) { + throw new NodeCheckError( + `Node ${node.name} sent block ${height} without its body`, + ); + } + const block = new L2Block( + response.archive, + response.header, + response.body, + response.checkpointNumber, + response.indexWithinCheckpoint, + ); + const fault = await bodyFault(block); + if (fault !== undefined) { + throw new NodeCheckError(`Node ${node.name} ${fault}`); + } + return { + block, + finalized: + version !== undefined && + block.header.globalVariables.version.toBigInt() === version && + height <= tips.finalized.block.number, + }; + }, + }; +}; diff --git a/services/aztec-listener/src/svcs/poller/network-client/block-stream-source.ts b/services/aztec-listener/src/svcs/poller/network-client/block-stream-source.ts index f2d77d1fa..bef897fcc 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/block-stream-source.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/block-stream-source.ts @@ -23,6 +23,7 @@ import { AZTEC_STREAM_STALL_ALERT_MS, } from "../../../environment.js"; import { logger } from "../../../logger.js"; +import { withDeadline } from "./deadline.js"; import { type OpenElectionReader, boundedElectionReaders, @@ -43,6 +44,13 @@ export class NodeCheckError extends Error { override readonly name = "NodeCheckError"; } +/** + * An intentional end of a block stream pass. It keeps the name `AbortError`, + * on which the SDK's stream ends a pass without logging; an AbortError from a + * dependency is a failure. + */ +export class PassExit extends AbortError {} + export type ElectionStore = Pick< L2TipsStoreBase, "getL2Tips" | "getL2BlockHash" @@ -68,13 +76,13 @@ export type StickySourceConfig = { /** What every snapshot of one pass is checked against. */ type PassBounds = { finalized: L2BlockId; floor: number | undefined }; -/** `proposed` is the tip the election's probe showed. */ -type Pin = { node: RpcNode; bounds: PassBounds; proposed: L2BlockId }; -type Bench = { until: number } | { tip: L2BlockId }; +/** `tips` are what the election's probe showed. */ +type Pin = { node: RpcNode; bounds: PassBounds; tips: L2Tips }; +type Bench = { until: number } | { tip: L2BlockId; sitsOutNext: boolean }; type Probe = { node: RpcNode; tips?: L2Tips; eligible: boolean }; type Candidate = Probe & { tips: L2Tips }; type Fault = { - kind: "behind" | "fork" | "missing" | "floor" | "unreachable"; + kind: "order" | "behind" | "fork" | "missing" | "floor" | "unreachable"; reason: string; }; @@ -94,12 +102,24 @@ const forkAt = (height: number): Fault => ({ reason: `has another block at the block stream's finalized height ${height}`, }); -// The checks a snapshot needs no read for. The stream reports a lower -// finalized tip too, which would point the store below hashes it deleted. +const tiersOrdered = ({ proposed, checkpointed, proven, finalized }: L2Tips) => + finalized.block.number <= proven.block.number && + proven.block.number <= checkpointed.block.number && + checkpointed.block.number <= proposed.number; + +// The checks a snapshot needs no read for. The store takes the tiers as the +// stream reports them: out of order, or with a lower finalized tip, which +// would point the store below hashes it deleted. const tipsFault = ( tips: L2Tips, { finalized, floor }: PassBounds, ): Fault | undefined => { + if (!tiersOrdered(tips)) { + return { + kind: "order", + reason: `has tips out of order: proposed ${tips.proposed.number}, checkpointed ${tips.checkpointed.block.number}, proven ${tips.proven.block.number}, finalized ${tips.finalized.block.number}`, + }; + } const theirs = tips.finalized.block; if (theirs.number < finalized.number) { return { @@ -119,24 +139,6 @@ const tipsFault = ( return undefined; }; -const withDeadline = async ( - work: Promise, - ms: number, - error: () => Error, -): Promise => { - let timer: ReturnType | undefined; - try { - return await Promise.race([ - work, - new Promise((_, reject) => { - timer = setTimeout(() => reject(error()), ms); - }), - ]); - } finally { - clearTimeout(timer); - } -}; - /** * The genesis hash the store starts from: the SDK's constant fits only an * empty genesis. Throws when the node does not serve block 0. @@ -201,8 +203,9 @@ const blockDataFault = async (query: BlockQuery, header: BlockHeader) => { * every read of that pass goes to it. A failed response check or a walk-back * past the bound sets the node aside for five minutes. A failed read, a tips * or range read answered with nothing, or a rejected snapshot benches it for - * five minutes; the prefix rule, an empty range or no block at a height its - * snapshot covers bench it until its tip changes. Benched nodes are all back + * five minutes; the prefix rule, an empty range, or no block at a height its + * snapshot covers bench it until its tip changes, and a tip its blocks do not + * match benches it for the next election as well. Benched nodes are all back * once no eligible node is outside the bench. */ export class StickySource implements L2BlockStreamSource { @@ -288,12 +291,16 @@ export class StickySource implements L2BlockStreamSource { ); for (const { node, tips } of eligible) { const bench = this.benched.get(node.url); - if ( - bench !== undefined && - ("until" in bench - ? bench.until <= now - : !sameBlock(bench.tip, tips.proposed)) - ) { + if (bench === undefined) { + continue; + } + if ("until" in bench) { + if (bench.until <= now) { + this.benched.delete(node.url); + } + } else if (bench.sitsOutNext) { + bench.sitsOutNext = false; + } else if (!sameBlock(bench.tip, tips.proposed)) { this.benched.delete(node.url); } } @@ -343,17 +350,28 @@ export class StickySource implements L2BlockStreamSource { } (${describeTips(before?.tips)})`, ); } - this.pin = { node: next.node, bounds, proposed: next.tips.proposed }; + this.pin = { node: next.node, bounds, tips: next.tips }; return next.node; } - /** The pass ended on the prefix rule: unpins the node and benches it. */ - endPassOnPrefix(): void { + /** Unpins the pinned node and benches it until its tip changes. */ + benchPinnedUntilNewTip(): void { if (this.pin !== undefined) { this.bench(this.pin, "new tip"); } } + /** + * Unpins the pinned node and benches it for the next election, then until + * its tip changes: a node whose blocks disagree with its tips can lead the + * election with a new tip every pass. + */ + benchPinnedPastNextElection(): void { + if (this.pin !== undefined) { + this.bench(this.pin, "next election"); + } + } + /** Keeps the pinned node out of the elections for five minutes. */ setAsidePinned(reason: string): void { if (this.pin !== undefined) { @@ -376,7 +394,7 @@ export class StickySource implements L2BlockStreamSource { const message = `Node ${pin.node.name} ${fault.reason}; the block stream skips this pass`; logger.warn(message); this.bench(pin, "cooldown"); - throw new AbortError(message); + throw new PassExit(message); } this.latestTips = tips; return tips; @@ -384,30 +402,38 @@ export class StickySource implements L2BlockStreamSource { } getBlockData(query: BlockQuery): Promise { - return this.recorded(async () => { + return this.recorded(() => { this.walkStep(++this.blockReads, "block reads"); - const { pin, result: response } = await this.pinnedCall("getBlock", [ - query, - ]); - if (response === undefined) { - const tip = this.latestTips?.proposed.number; - if ("number" in query && tip !== undefined && query.number <= tip) { - // A height its snapshot covers: the stream aborts the pass, as on an empty range. - this.bench(pin, "new tip"); - } - return undefined; - } - await this.check(pin.node, blockDataFault(query, response.header)); - return { - header: response.header, - archive: response.archive, - blockHash: response.hash, - checkpointNumber: response.checkpointNumber, - indexWithinCheckpoint: response.indexWithinCheckpoint, - }; + return this.readBlockData(query); }); } + /** The pinned node's block at `height`, read outside the walk bound. */ + pinnedBlockData(height: number): Promise { + return this.recorded(() => + this.readBlockData({ number: BlockNumber(height) }), + ); + } + + /** As `pinnedBlockData`, for a caller that benches the node itself when the block is missing. */ + pinnedBlockDataUnbenched(height: number): Promise { + return this.recorded(() => + this.readBlockData({ number: BlockNumber(height) }, false), + ); + } + + /** Calls the pinned node under the pinned reads' deadline; a failure benches no node. */ + async pinnedRead( + fnName: K, + args: Parameters, + ): Promise>> { + const pin = this.pin; + if (pin === undefined) { + throw new PassExit(); + } + return this.boundedCall(pin, fnName, args); + } + getBlocks(query: BlocksQuery): Promise { // Epoch lookups are not exposed on the public AztecNode RPC; only `from + limit` is. if (!("from" in query)) { @@ -464,39 +490,91 @@ export class StickySource implements L2BlockStreamSource { } } + private async readBlockData( + query: BlockQuery, + benchIfMissing = true, + ): Promise { + const { pin, result: response } = await this.pinnedCall("getBlock", [ + query, + ]); + if (response === undefined) { + const tip = this.latestTips?.proposed.number; + if ( + benchIfMissing && + "number" in query && + tip !== undefined && + query.number <= tip + ) { + // A height its snapshot covers: the stream aborts the pass, as on an empty range. + this.bench(pin, "new tip"); + } + return undefined; + } + await this.check(pin.node, blockDataFault(query, response.header)); + if ("number" in query && query.number === BlockNumber.ZERO) { + const fault = await this.genesisFault(response.header); + if (fault !== undefined) { + logger.error(`Node ${pin.node.name} ${fault}`); + this.fail(pin.node, fault); + } + } + return { + header: response.header, + archive: response.archive, + blockHash: response.hash, + checkpointNumber: response.checkpointNumber, + indexWithinCheckpoint: response.indexWithinCheckpoint, + }; + } + + private async genesisFault(header: BlockHeader) { + const genesis = await this.deps.store.getL2BlockHash(BlockNumber.ZERO); + return (await header.hash()).toString() === genesis + ? undefined + : "has another genesis block than the block stream's"; + } + private async pinnedCall( fnName: K, args: Parameters, ) { const pin = this.pin; if (pin === undefined) { - throw new AbortError(); + throw new PassExit(); } try { - const result = await withDeadline( - callNodeFunction(fnName, args, pin.node), - PINNED_READ_TIMEOUT_MS, - () => - new TimeoutError( - `Node ${pin.node.name} did not answer ${String(fnName)} within ${ - PINNED_READ_TIMEOUT_MS / 1000 - } s`, - ), - ); - // The RPC client resolves a null answer to undefined, whatever the - // method's type; only a block lookup may answer nothing. - if (result === undefined && fnName !== "getBlock") { - throw new Error( - `Node ${pin.node.name} answered ${String(fnName)} with nothing`, - ); - } - return { pin, result }; + return { pin, result: await this.boundedCall(pin, fnName, args) }; } catch (e) { this.bench(pin, "cooldown"); throw e; } } + private async boundedCall( + pin: Pin, + fnName: K, + args: Parameters, + ): Promise>> { + const result = await withDeadline( + callNodeFunction(fnName, args, pin.node), + PINNED_READ_TIMEOUT_MS, + () => + new TimeoutError( + `Node ${pin.node.name} did not answer ${String(fnName)} within ${ + PINNED_READ_TIMEOUT_MS / 1000 + } s`, + ), + ); + // The RPC client resolves a null answer to undefined, whatever the + // method's type; only a block lookup may answer nothing. + if (result === undefined && fnName !== "getBlock") { + throw new Error( + `Node ${pin.node.name} answered ${String(fnName)} with nothing`, + ); + } + return result; + } + private async pinnedBlockHash(height: number): Promise { const { result: block } = await this.pinnedCall("getBlock", [ BlockNumber(height), @@ -516,7 +594,7 @@ export class StickySource implements L2BlockStreamSource { } const node = this.pin?.node; if (node === undefined) { - throw new AbortError(); + throw new PassExit(); } this.fail(node, `took the block stream past ${bound} ${what} in one pass`); } @@ -546,12 +624,12 @@ export class StickySource implements L2BlockStreamSource { ); } - private bench(pin: Pin, until: "cooldown" | "new tip") { + private bench(pin: Pin, until: "cooldown" | "new tip" | "next election") { this.benched.set( pin.node.url, until === "cooldown" ? { until: this.now() + SET_ASIDE_MS } - : { tip: pin.proposed }, + : { tip: pin.tips.proposed, sitsOutNext: until === "next election" }, ); if (this.pin === pin) { this.pin = undefined; diff --git a/services/aztec-listener/src/svcs/poller/network-client/deadline.ts b/services/aztec-listener/src/svcs/poller/network-client/deadline.ts new file mode 100644 index 000000000..44bdad2db --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/deadline.ts @@ -0,0 +1,18 @@ +/** Rejects with `error()` once `ms` pass; `work` itself keeps running. */ +export const withDeadline = async ( + work: Promise, + ms: number, + error: () => Error, +): Promise => { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + work, + new Promise((_, reject) => { + timer = setTimeout(() => reject(error()), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +}; diff --git a/services/aztec-listener/src/svcs/poller/network-client/election-probe.ts b/services/aztec-listener/src/svcs/poller/network-client/election-probe.ts index 0b75abb82..35789ead2 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/election-probe.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/election-probe.ts @@ -6,7 +6,11 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { jsonStringify } from "@aztec-labs/foundation/json-rpc"; import { type JsonRpcFetch } from "@aztec-labs/foundation/json-rpc/client"; import { type L2Tips } from "@aztec-labs/stdlib/block"; -import { type RpcNode, withV5NodeNamespaceFallback } from "./pool.js"; +import { + type RpcNode, + withRedactedErrors, + withV5NodeNamespaceFallback, +} from "./pool.js"; /** Election answers are small; the cap keeps a faulty node from streaming an unbounded body into memory. */ export const ELECTION_PROBE_MAX_BYTES = 64 * 1024; @@ -66,8 +70,10 @@ class BoundedClient { constructor(url: string, maxBytes: number) { this.node = createAztecNodeClient(url, { - fetch: withV5NodeNamespaceFallback( - boundedFetch(maxBytes, () => this.deadline), + fetch: withRedactedErrors( + withV5NodeNamespaceFallback( + boundedFetch(maxBytes, () => this.deadline), + ), ), }); } diff --git a/services/aztec-listener/src/svcs/poller/network-client/index.ts b/services/aztec-listener/src/svcs/poller/network-client/index.ts index 1eb1ee637..058d3ce31 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/index.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/index.ts @@ -1,5 +1,4 @@ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ -import { deriveStorageSlotInMap } from "@aztec-labs/stdlib/hash"; import { ChicmozChainInfo, ChicmozL2RpcNode, @@ -30,10 +29,7 @@ import { getRpcNodeFromNodeInfo, } from "./utils.js"; import { AztecNode, NodeInfo } from "@aztec-labs/aztec.js/node"; -import { AztecAddress } from "@aztec-labs/stdlib/aztec-address"; -import { Fr } from "@aztec-labs/aztec.js/fields"; import { L2Block } from "@aztec-labs/aztec.js/block"; -import { ProtocolContractAddress } from "@aztec-labs/aztec.js/protocol"; import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { getAllPendingTxs } from "./pending-txs.js"; @@ -106,18 +102,6 @@ const sleep = async (ms: number) => { return new Promise((resolve) => setTimeout(resolve, ms)); }; -const toSafeAztecBlockNumber = (value: bigint): number => { - const blockNumber = Number(value); - - if (!Number.isSafeInteger(blockNumber) || blockNumber < 0) { - throw new Error( - `Block number ${value.toString()} cannot be represented safely as a number`, - ); - } - - return blockNumber; -}; - export const init = async () => { initPool(); await sleep(1000); @@ -233,37 +217,13 @@ export const getBlocks = async (fromHeight: number, toHeight: number) => { return blocks; }; -export const getLatestProposedHeight = async () => { - return callNodeFunction("getBlockNumber"); -}; - export const getLatestProvenHeight = async () => { return await callNodeFunction("getBlockNumber", ["proven"]); }; -export const getL2Tips = async () => { - return await callNodeFunction("getChainTips"); -}; - export const getPendingTxs = async () => { const node = getRpcNode(); return getAllPendingTxs((limit, after) => callNodeFunction("getPendingTxs", [limit, after], node), ); }; - -export const getBalanceOf = async ( - blockNumber: bigint | "latest", - address: AztecAddress, -) => { - const slot = await deriveStorageSlotInMap(new Fr(1), address); - const blockParam = - blockNumber === "latest" - ? "latest" - : BlockNumber(toSafeAztecBlockNumber(blockNumber)); - return callNodeFunction("getPublicStorageAt", [ - blockParam, - ProtocolContractAddress.FeeJuice, - slot, - ]); -}; diff --git a/services/aztec-listener/src/svcs/poller/network-client/pool.ts b/services/aztec-listener/src/svcs/poller/network-client/pool.ts index 72cefeea0..8480cc601 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/pool.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/pool.ts @@ -6,6 +6,7 @@ import { import { AZTEC_RPC_URLS } from "../../../environment.js"; import { onL2RpcNodeError } from "../../../events/emitted/index.js"; import { logger } from "../../../logger.js"; +import { redactError } from "./redact-urls.js"; export interface RpcNode { name: string; @@ -99,6 +100,28 @@ export const withV5NodeNamespaceFallback = return await send(host, rewrittenBody, extraHeaders, noRetry); }; +/** + * `send`, with the URLs in each error it throws redacted. The SDK's fetch names + * the node's URL in its errors, Node's fetch names a URL with userinfo, and the + * SDK client logs a failed fetch's error before any caller sees it. The offline + * markers callNodeFunction looks for name no URL. + */ +export const withRedactedErrors = + (send: JsonRpcFetch): JsonRpcFetch => + async (host, body, extraHeaders, noRetry) => { + try { + return await send(host, body, extraHeaders, noRetry); + } catch (e) { + throw redactError(e); + } + }; + +/** The JSON-RPC client the pool keeps for the node at `url`. */ +export const nodeClient = (url: string): AztecNode => + createAztecNodeClient(url, { + fetch: withRedactedErrors(withV5NodeNamespaceFallback(defaultFetch)), + }); + const resetPools = () => { logger.info( `⚠️ ⚠️ ⚠️ Resetting node pools (online: ${onlinePool.length}, offline: ${offlinePool.length})`, @@ -117,9 +140,7 @@ export const initPool = () => { return { name: node.name, url: node.url, - instance: createAztecNodeClient(node.url, { - fetch: withV5NodeNamespaceFallback(defaultFetch), - }), + instance: nodeClient(node.url), }; }); resetPools(); diff --git a/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts b/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts new file mode 100644 index 000000000..9ce2e9609 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts @@ -0,0 +1,97 @@ +import { AZTEC_RPC_URLS } from "../../../environment.js"; + +// A node's URL can carry a key in its userinfo, path or query. The last +// character class keeps a trailing colon or period out of the match. Node +// prints an ES module's stack frames as file URLs, which name no node. +const URL_PATTERN = + /\b(?!file:)[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*[^\s"'<>.,:;)]/gi; + +// Below this, a path segment or query value is redacted only as part of its +// URL, so a segment like `v1` does not blank every line. +const MIN_PART = 8; + +const decoded = (part: string) => { + try { + return decodeURIComponent(part); + } catch { + return part; + } +}; + +// The pattern stops at an apostrophe, which a path can hold, and an error can +// name any one part of a URL alone. +const partsOf = (configured: string) => { + let url: URL; + try { + url = new URL(configured); + } catch { + return [configured]; + } + const { href, host, hostname, pathname, search, username, password } = url; + const pieces = [ + ...pathname.split("/"), + ...search + .slice(1) + .split("&") + .map((p) => p.slice(p.indexOf("=") + 1)), + ...url.searchParams.values(), + ] + .flatMap((p) => [p, decoded(p)]) + .filter((p) => p.length >= MIN_PART); + return [ + configured, + href, + host, + hostname, + pathname.length > 1 ? pathname : "", + search, + username, + decoded(username), + password, + decoded(password), + ...pieces, + ]; +}; + +/** + * Replaces with `` each part of the `configured` URLs, longest first, + * then any other URL but a file URL. + */ +export const urlRedactor = (configured: string[]) => { + const parts = [...new Set(configured.flatMap(partsOf))] + .filter((p) => p.length > 0) + .sort((a, b) => b.length - a.length); + // Case-sensitive, so a host such as `gateway` leaves the offline marker + // `Bad Gateway` whole. An error names a part as configured or as `URL` + // normalized it, and `parts` holds both. + const exact = + parts.length === 0 + ? undefined + : new RegExp( + parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), + "g", + ); + return (text: string) => + (exact === undefined ? text : text.replace(exact, "")).replace( + URL_PATTERN, + "", + ); +}; + +/** `text` with the node pool's URLs and any other URL but a file URL redacted. */ +export const redactUrls = urlRedactor(AZTEC_RPC_URLS.map(({ url }) => url)); + +/** + * `e` with the URLs in its message and stack redacted, in place, so that its + * class stays; anything else thrown becomes an Error. + */ +export const redactError = (e: unknown): Error => { + if (!(e instanceof Error)) { + return new Error(redactUrls(String(e))); + } + e.message = redactUrls(e.message); + if (e.stack !== undefined) { + e.stack = redactUrls(e.stack); + } + return e; +}; diff --git a/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts b/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts new file mode 100644 index 000000000..5fc2a9a6f --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts @@ -0,0 +1,49 @@ +import { TimeoutError } from "@aztec-labs/foundation/error"; +import { logger } from "../../../logger.js"; +import { withDeadline } from "./deadline.js"; +import { callNodeFunction } from "./index.js"; +import { type RpcNode } from "./pool.js"; +import { redactUrls } from "./redact-urls.js"; + +export type ReportedVersion = { node: RpcNode; version: number }; + +/** + * The highest rollup version the nodes' node info reports, with a node that + * reports it, or undefined when none answers within `timeoutMs`. + */ +export const readLatestRollupVersion = async ( + nodes: RpcNode[], + timeoutMs: number, +): Promise => { + const reports = await Promise.all( + nodes.map(async (node): Promise => { + try { + const info = await withDeadline( + callNodeFunction("getNodeInfo", [], node), + timeoutMs, + () => + new TimeoutError( + `Node ${node.name} did not answer getNodeInfo within ${ + timeoutMs / 1000 + } s`, + ), + ); + return Number.isSafeInteger(info?.rollupVersion) + ? { node, version: info.rollupVersion } + : undefined; + } catch (e) { + logger.info( + `Node ${node.name} reported no rollup version: ${redactUrls((e as Error).message)}`, + ); + return undefined; + } + }), + ); + let latest: ReportedVersion | undefined; + for (const report of reports) { + if (report !== undefined && report.version > (latest?.version ?? -1)) { + latest = report; + } + } + return latest; +}; diff --git a/services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts new file mode 100644 index 000000000..00d634a50 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts @@ -0,0 +1,348 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { + type L2Block, + type L2BlockId, + type L2BlockStreamEvent, + type L2BlockStreamEventHandler, + type L2Tips, + type L2TipsStoreBase, +} from "@aztec-labs/stdlib/block"; +import { + AZTEC_MAX_PRUNE_DEPTH, + AZTEC_STREAM_STALL_ALERT_MS, +} from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { + PassExit, + type StickySource, +} from "../../network-client/block-stream-source.js"; + +type PruneEvent = Extract; +type ProposedEvent = Extract; +type TierEvent = Extract< + L2BlockStreamEvent, + { type: "chain-checkpointed" | "chain-proven" | "chain-finalized" } +>; +type Rejection = { reason: string; alert?: true }; + +export type ChainPublisherDeps = { + rollupVersion: number; + store: Pick< + L2TipsStoreBase, + "getL2Tips" | "getL2BlockHash" | "handleBlockStreamEvent" + >; + source: Pick< + StickySource, + | "pinned" + | "lastTips" + | "pinnedBlockData" + | "pinnedBlockDataUnbenched" + | "benchPinnedUntilNewTip" + | "benchPinnedPastNextElection" + | "setAsidePinned" + >; + /** Sends one block of the ordered stream; resolves once it is sent. */ + publishBlock: (block: L2Block, tip: number) => Promise; + /** Moves the proven side work's cursor back to a height; never forward. */ + lowerProvenCursor: (height: number) => Promise; + /** Runs `fn` in one listener transaction, which the store's writes join. */ + transaction: (fn: () => Promise) => Promise; + now?: () => number; +}; + +export type ChainPublisherConfig = { + maxPruneDepth: number; + /** How long passes may end on the prefix rule before it alerts, and between alerts. */ + prefixAlertMs: number; +}; + +/** The block stream's handler: it stores a batch only once every block in it is sent. */ +export class ChainPublisher implements L2BlockStreamEventHandler { + private prefixWait: { since: number; alertedAt?: number } | undefined; + private endedOnPrefix = false; + private failure: Error | undefined; + private readonly now: () => number; + + constructor( + private readonly deps: ChainPublisherDeps, + private readonly config: ChainPublisherConfig = { + maxPruneDepth: AZTEC_MAX_PRUNE_DEPTH, + prefixAlertMs: AZTEC_STREAM_STALL_ALERT_MS, + }, + ) { + this.now = deps.now ?? (() => Date.now()); + } + + /** Call before each pass's `sync()`. */ + startPass(): void { + this.endedOnPrefix = false; + this.failure = undefined; + } + + /** + * Call after each pass's `sync()`, which resolves even when a handler + * failed: this rethrows that failure. A pass that did not end on the prefix + * rule ends the wait. + */ + finishPass(): void { + if (!this.endedOnPrefix) { + this.prefixWait = undefined; + } + const failure = this.failure; + this.failure = undefined; + if (failure !== undefined) { + throw failure; + } + } + + async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise { + try { + await this.handle(event); + } catch (e) { + if (e instanceof PassExit) { + throw e; + } + // The stream would log it, or drop it for its AbortError name, and end + // the pass; finishPass() rethrows it. + const error = e instanceof Error ? e : new Error(String(e)); + this.failure ??= error; + throw new PassExit(error.message, { cause: error }); + } + } + + private handle(event: L2BlockStreamEvent): Promise { + switch (event.type) { + case "blocks-added": + return this.addBlocks(event.blocks); + case "chain-pruned": + return this.prune(event); + case "chain-proposed": + return this.confirmProposed(event); + case "chain-checkpointed": + case "chain-proven": + case "chain-finalized": + return this.moveTier(event); + default: + return this.deps.store.handleBlockStreamEvent(event); + } + } + + private async addBlocks(blocks: L2Block[]) { + const tip = this.snapshot().proposed; + const rejection = await this.batchFault(blocks); + if (rejection !== undefined) { + this.reject(rejection); + } + await this.confirmTip(tip, blocks); + for (const block of blocks) { + await this.deps.publishBlock(block, tip.number); + } + // The blocks sent so far carry this pass's tip, which the node may drop + // before the next pass; storing none of them after a failed send makes + // that pass send them again with its own tip. + await this.deps.store.handleBlockStreamEvent({ + type: "blocks-added", + blocks, + }); + } + + private async batchFault(blocks: L2Block[]): Promise { + const version = BigInt(this.deps.rollupVersion); + for (const [i, block] of blocks.entries()) { + const theirs = block.header.globalVariables.version.toBigInt(); + if (theirs !== version) { + return { + reason: `sent block ${block.number} of rollup version ${theirs}, not ${version}`, + alert: true, + }; + } + const previous = blocks[i - 1]; + if ( + previous !== undefined && + !block.header.lastArchive.root.equals(previous.archive.root) + ) { + return { + reason: `sent block ${block.number}, which does not extend block ${previous.number}`, + }; + } + } + const first = blocks[0]; + const height = BlockNumber(first.number - 1); + const stored = await this.deps.store.getL2BlockHash(height); + if (stored === undefined) { + // A first pass from `startingBlock` has no stored parent. + return undefined; + } + // The store keeps hashes only; the link needs the parent's archive root. + const parent = await this.deps.source.pinnedBlockData(height); + if (parent === undefined) { + throw new PassExit(); + } + if ((await parent.header.hash()).toString() !== stored) { + return { + reason: `has another block ${height} than the one the block stream stored`, + }; + } + if (!first.header.lastArchive.root.equals(parent.archive.root)) { + return { + reason: `sent block ${first.number}, which does not extend block ${height}`, + }; + } + return undefined; + } + + // The stream checks its snapshot's tip only after emitting every batch, yet + // the API takes each block's tip as where the listener's chain ends. A node + // that moved since its tips were read is not at fault, so a mismatch benches + // it for the next election and until its tip changes, not for a cooldown. + // The next pass then follows any other eligible node, which the sticky + // election keeps while the benched node leads it by no more than the pin's lead. + private async confirmTip(tip: L2BlockId, blocks: L2Block[]) { + const last = blocks[blocks.length - 1]; + const held = + last.number === tip.number + ? last.hash() + : this.deps.source + .pinnedBlockDataUnbenched(tip.number) + .then((data) => data?.header.hash()); + if ((await held)?.toString() !== tip.hash) { + logger.warn( + `Node ${this.pinnedName()} no longer holds this pass's proposed tip ${tip.number}; the pass ends before sending blocks ${blocks[0].number}-${last.number}`, + ); + this.deps.source.benchPinnedPastNextElection(); + throw new PassExit(); + } + } + + private async prune(event: PruneEvent) { + const snapshot = this.snapshot(); + const target = event.block; + const local = await this.deps.store.getL2Tips(); + if (target.number === snapshot.proposed.number) { + // A real prune shows another block above the target; this node only + // has a shorter copy of the stored chain. + this.endedOnPrefix = true; + this.notePrefixWait(target.number, local.proposed.number); + this.deps.source.benchPinnedUntilNewTip(); + throw new PassExit(); + } + const [atTarget, above] = await Promise.all([ + this.deps.store.getL2BlockHash(target.number), + this.deps.store.getL2BlockHash(BlockNumber(target.number + 1)), + ]); + // The SDK ends a walk-back at the finalized tip on a disagreement, and + // walks through heights the store holds no hash for. + if (atTarget !== target.hash || above === undefined) { + this.reject({ + reason: `asks to prune to block ${target.number}, which the block stream cannot confirm it holds`, + alert: true, + }); + } + // The store writes each tier it lowers over the hash at that height, which + // can be the finalized witness; at or below the target, no block of this + // pass writes it back. + for (const [tier, { block }] of [ + ["checkpointed", event.checkpointed], + ["proven", event.proven], + ] as const) { + if (block.number <= target.number) { + await this.checkStored(tier, block); + } + } + const depth = local.proposed.number - target.number; + if (depth > this.config.maxPruneDepth) { + logger.error( + `Node ${this.pinnedName()} asks to prune ${depth} blocks, past AZTEC_MAX_PRUNE_DEPTH ${this.config.maxPruneDepth}; the block stream stores nothing`, + ); + throw new PassExit(); + } + const provenBack = event.proven.block.number < local.proven.block.number; + await this.deps.transaction(async () => { + await this.deps.store.handleBlockStreamEvent(event); + await this.deps.lowerProvenCursor( + provenBack + ? Math.min(target.number, event.proven.block.number) + : target.number, + ); + }); + } + + // The stream reports the snapshot's tip even when it downloaded nothing up + // to it, as from a `startingBlock` past that tip. A valid pass has stored + // that tip by now; a hash at its height alone can be a tier's, which a + // prune writes before any block is sent. + private async confirmProposed(event: ProposedEvent) { + const { proposed } = await this.deps.store.getL2Tips(); + if ( + proposed.number !== event.block.number || + proposed.hash !== event.block.hash + ) { + logger.warn( + `Node ${this.pinnedName()} has proposed tip ${event.block.number}, which this pass did not send; the pass ends`, + ); + throw new PassExit(); + } + } + + private async moveTier(event: TierEvent) { + // The store writes a tier's hash over the one at its height, and the + // finalized tier deletes the hashes below it. + await this.checkStored(event.type.slice("chain-".length), event.block); + if (event.type === "chain-proven") { + const proven = (await this.deps.store.getL2Tips()).proven.block.number; + if (event.block.number < proven) { + await this.deps.transaction(async () => { + await this.deps.store.handleBlockStreamEvent(event); + await this.deps.lowerProvenCursor(event.block.number); + }); + return; + } + } + await this.deps.store.handleBlockStreamEvent(event); + } + + private async checkStored(tier: string, block: L2BlockId) { + if ((await this.deps.store.getL2BlockHash(block.number)) !== block.hash) { + this.reject({ + reason: `has another block at its ${tier} height ${block.number} than the one the block stream stored`, + }); + } + } + + private snapshot(): L2Tips { + const tips = this.deps.source.lastTips; + if (tips === undefined) { + throw new Error( + "The block stream sent an event before the pass read the tips", + ); + } + return tips; + } + + private reject({ reason, alert }: Rejection): never { + const message = `Node ${this.pinnedName()} ${reason}`; + if (alert) { + logger.error(message); + } + this.deps.source.setAsidePinned(message); + throw new PassExit(message); + } + + private notePrefixWait(target: number, stored: number) { + const now = this.now(); + const entering = this.prefixWait === undefined; + this.prefixWait ??= { since: now }; + const message = `Node ${this.pinnedName()} is at block ${target}, below the block stream's tip ${stored} on its chain; the block stream waits for a node at or past its tip`; + const { since, alertedAt } = this.prefixWait; + if (now - (alertedAt ?? since) >= this.config.prefixAlertMs) { + logger.error(`${message} (${Math.round((now - since) / 1000)}s so far)`); + this.prefixWait.alertedAt = now; + } else if (entering) { + logger.warn(message); + } + } + + private pinnedName() { + return this.deps.source.pinned?.name ?? "(none pinned)"; + } +} diff --git a/services/aztec-listener/src/svcs/poller/pollers/block_poller/handle-proven-block-txs.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/handle-proven-block-txs.ts index fa753f94a..22f909e98 100644 --- a/services/aztec-listener/src/svcs/poller/pollers/block_poller/handle-proven-block-txs.ts +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/handle-proven-block-txs.ts @@ -1,32 +1,31 @@ import { L2Block } from "@aztec-labs/aztec.js/block"; import { AztecAddress } from "@aztec-labs/aztec.js/addresses"; +import { Fr } from "@aztec-labs/aztec.js/fields"; +import { ProtocolContractAddress } from "@aztec-labs/aztec.js/protocol"; +import { type BlockHash } from "@aztec-labs/stdlib/block"; +import { deriveStorageSlotInMap } from "@aztec-labs/stdlib/hash"; import { logger } from "../../../../logger.js"; import { txsController } from "../../../database/index.js"; import { publishMessage } from "../../../message-bus/index.js"; -import { getBalanceOf } from "../../network-client/index.js"; + +/** Reads a public storage slot as of `block`. */ +export type ReadPublicStorage = ( + block: BlockHash, + contract: AztecAddress, + slot: Fr, +) => Promise; + +export type ProvenBlockOutcome = { ok: true } | { ok: false; error: Error }; type StoredTx = Awaited>[number]; -type BalanceFetchSuccess = { - status: "fulfilled"; - addr: string; - sourceTxHash: string; - balance: Awaited>; -}; -type BalanceFetchFailure = { - status: "rejected"; - addr: string; - sourceTxHash: string; - reason: unknown; -}; const BALANCE_FETCH_CONCURRENCY = 8; -// Collect all unique addresses across all proven txs in the block. -// Maps address → first txHash that introduced it (used as sourceTxHash). -const collectUniqueAddresses = (provenTxs: StoredTx[]): Map => { +// Maps each address to the first tx that names it (the event's sourceTxHash). +const collectUniqueAddresses = (txs: StoredTx[]): Map => { const addressToTxHash = new Map(); - for (const tx of provenTxs) { + for (const tx of txs) { const candidates: (string | null | undefined)[] = [ tx.feePayer, tx.initiator, @@ -43,135 +42,106 @@ const collectUniqueAddresses = (provenTxs: StoredTx[]): Map => { return addressToTxHash; }; +// The fee juice contract keeps balances in a map at storage slot 1. +const readFeeJuiceBalance = async ( + readStorage: ReadPublicStorage, + block: BlockHash, + address: AztecAddress, +) => + readStorage( + block, + ProtocolContractAddress.FeeJuice, + await deriveStorageSlotInMap(new Fr(1), address), + ); + const fetchBalances = async ( - blockNumber: bigint, - addressToTxHash: Map, + readStorage: ReadPublicStorage, + block: BlockHash, + addresses: string[], ) => { - const entries = [...addressToTxHash.entries()]; - const results: Array = []; + const balances = new Map(); let nextIndex = 0; - + // One failed read fails the block, so the other workers stop reading. + let failed = false; await Promise.all( Array.from( - { length: Math.min(BALANCE_FETCH_CONCURRENCY, entries.length) }, + { length: Math.min(BALANCE_FETCH_CONCURRENCY, addresses.length) }, async () => { - while (nextIndex < entries.length) { - const currentIndex = nextIndex++; - const [addr, sourceTxHash] = entries[currentIndex]; - + while (!failed && nextIndex < addresses.length) { + const addr = addresses[nextIndex++]; try { - const balance = await getBalanceOf( - blockNumber, - AztecAddress.fromStringUnsafe(addr), - ); - results[currentIndex] = { - status: "fulfilled", + balances.set( addr, - sourceTxHash, - balance, - }; - } catch (reason) { - results[currentIndex] = { - status: "rejected", - addr, - sourceTxHash, - reason, - }; + await readFeeJuiceBalance( + readStorage, + block, + AztecAddress.fromStringUnsafe(addr), + ), + ); + } catch (e) { + failed = true; + throw e; } } }, ), ); - - return results; + return balances; }; -export const handleProvenTransactions = async (block: L2Block) => { +/** + * Publishes the fee juice balance, as of `block`, of every address its stored + * txs name, then marks those txs proven. It handles every stored tx of the + * block, whatever its state, so a block run again after a prune or a proof + * that moved back sends the same updates. Any failure fails the whole block. + */ +export const handleProvenTransactions = async ( + block: L2Block, + readStorage: ReadPublicStorage, +): Promise => { try { - const notProvenTxs = await txsController.getTxs([ - "pending", - "dropped", - "proposed", - ]); - if (notProvenTxs.length === 0) { - return; - } - - const provenTxHashes = block.body.txEffects.map((txEffect) => { - const hash = txEffect.txHash; - return hash.toString(); - }); - - const provenPendingTxs = provenTxHashes - .map((txHash) => { - const tx = notProvenTxs.find((tx) => tx.txHash === txHash); - if (!tx) { - return undefined; - } - logger.info(`🔍 ${txHash} found in pending or dropped txs`); - return tx; - }) - .filter((tx) => tx !== undefined); - - if (provenPendingTxs.length === 0) { - return; - } - - const blockNumber = BigInt( - block.header.globalVariables.blockNumber.toString(), + const hashes = block.body.txEffects.map((txEffect) => + txEffect.txHash.toString(), ); - logger.info( - `🎯 Found ${provenPendingTxs.length} proven pending txs in block ${blockNumber}`, + const stored = new Map( + (await txsController.getTxsByHashes(hashes)).map((tx) => [tx.txHash, tx]), ); - - // Step 1 — collect all unique addresses across the entire block - const addressToTxHash = collectUniqueAddresses(provenPendingTxs); + // In block order: an address's source tx is the block's first to name it. + const txs = hashes.flatMap((hash) => stored.get(hash) ?? []); + if (txs.length === 0) { + return { ok: true }; + } + const blockNumber = block.header.globalVariables.blockNumber.toString(); + const addressToTxHash = collectUniqueAddresses(txs); logger.info( - `📋 Fetching fee-juice balances for ${addressToTxHash.size} unique addresses in block ${blockNumber}`, + `📋 Fetching fee-juice balances for ${addressToTxHash.size} addresses named by ${txs.length} txs in block ${blockNumber}`, ); + const balances = await fetchBalances(readStorage, await block.hash(), [ + ...addressToTxHash.keys(), + ]); - // Step 2 — fetch balances with bounded concurrency - const balanceResults = await fetchBalances(blockNumber, addressToTxHash); - - // Step 3 — publish Kafka events for successful balance fetches - await Promise.all( - balanceResults.map(async (result) => { - if (result.status === "rejected") { - logger.error( - `Failed to fetch balance for ${result.addr} (sourceTxHash: ${result.sourceTxHash}, block: ${blockNumber.toString()}): ${String(result.reason)}`, - ); - return; - } - const { addr, sourceTxHash, balance } = result; - const balanceBigInt = balance.toBigInt(); - if (balanceBigInt === 0n) { - logger.debug(`⏭️ Skipping zero balance for ${addr}`); - return; - } - await publishMessage("CONTRACT_INSTANCE_BALANCE_EVENT", { - contractAddress: addr, - balance: balanceBigInt.toString(), - timestamp: new Date().getTime(), - sourceTxHash, - feeRecipient: block.header.globalVariables.feeRecipient.toString(), - blockNumber: blockNumber.toString(), - }); - logger.info(`💰 Snapshotted balance for ${addr}`); - }), - ); + for (const [addr, sourceTxHash] of addressToTxHash) { + const balance = balances.get(addr)?.toBigInt() ?? 0n; + if (balance === 0n) { + logger.debug(`⏭️ Skipping zero balance for ${addr}`); + continue; + } + await publishMessage("CONTRACT_INSTANCE_BALANCE_EVENT", { + contractAddress: addr, + balance: balance.toString(), + timestamp: new Date().getTime(), + sourceTxHash, + feeRecipient: block.header.globalVariables.feeRecipient.toString(), + blockNumber, + }); + logger.info(`💰 Snapshotted balance for ${addr}`); + } - // Step 4 — update tx states in parallel - await Promise.all( - provenPendingTxs.map(async (provenTx) => { - try { - await txsController.storeOrUpdateState(provenTx.txHash, "proven"); - logger.info(`✅ Updated tx ${provenTx.txHash} to proven state`); - } catch (error) { - logger.error(`Error updating tx ${provenTx.txHash} state:`, error); - } - }), - ); + for (const tx of txs) { + await txsController.storeOrUpdateState(tx.txHash, "proven"); + } + return { ok: true }; } catch (error) { - logger.error("Error handling proven transactions:", error); + return { ok: false, error: error as Error }; } }; diff --git a/services/aztec-listener/src/svcs/poller/pollers/block_poller/index.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/index.ts index 4764db73c..fff7c3528 100644 --- a/services/aztec-listener/src/svcs/poller/pollers/block_poller/index.ts +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/index.ts @@ -1,205 +1,271 @@ +import { inspect } from "node:util"; +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { L2BlockStream, localTipsMatch } from "@aztec-labs/stdlib/block"; import { - AZTEC_ENABLE_FULL_SWEEP_CATCHUP, + AZTEC_BLOCK_STREAM_BATCH_SIZE, AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS, AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS, + AZTEC_ENABLE_FULL_SWEEP_CATCHUP, + AZTEC_LISTEN_FOR_L2_TIPS, + AZTEC_NODE_PROBE_TIMEOUT_MS, BLOCK_POLL_INTERVAL_MS, - CATCHUP_POLL_WAIT_TIME_MS, + CHAIN_INFO_POLL_INTERVAL_MS, } from "../../../../environment.js"; -import { onBlock, onCatchupBlock } from "../../../../events/emitted/index.js"; +import { + onCatchupBlock, + onOrderedBlock, +} from "../../../../events/emitted/index.js"; import { logger } from "../../../../logger.js"; import { getBlockHeights, - storeBlockHeights, + lowerProcessedProvenBlockHeight, storeProcessedProposedBlockHeight, storeProcessedProvenBlockHeight, } from "../../../database/heights.controller.js"; +import { PostgresL2TipsStore } from "../../../database/l2-tips-store.js"; +import { inTransaction } from "../../../database/transaction.js"; +import { openAttestedReader } from "../../network-client/attested-reads.js"; import { - getBlock, - getLatestProposedHeight, - getLatestProvenHeight, -} from "../../network-client/index.js"; -import { handleProvenTransactions } from "./handle-proven-block-txs.js"; + type ElectionStore, + PassExit, + StickySource, + readGenesisBlockHash, +} from "../../network-client/block-stream-source.js"; +import { getOnlineRpcNodes, getRpcNode } from "../../network-client/pool.js"; +import { redactUrls } from "../../network-client/redact-urls.js"; +import { + type ReportedVersion, + readLatestRollupVersion, +} from "../../network-client/rollup-version.js"; +import { publishTipsIfDue } from "../l2-tips-poller.js"; +import { ChainPublisher } from "./chain-publisher.js"; +import { runProvenSideWork } from "./proven-side-work.js"; +import { streamLogger } from "./stream-logger.js"; + +/** One rollup version's block stream. */ +export type StreamChain = { + rollupVersion: number; + store: Pick< + ElectionStore, + "getL2Tips" | "getL2BlockHash" | "holdsHashAtOrAbove" + >; + source: StickySource; + publisher: ChainPublisher; +}; + +// Whether the store holds a block, which its tip does not tell: a prune to +// block 0 leaves the tip at 0 over the hashes above it. +const holdsBlocks = (store: StreamChain["store"]) => + store.holdsHashAtOrAbove(1); -let timeoutId: number | undefined; +let started = false; let cancelPolling = false; +let timeoutId: ReturnType | undefined; +let chain: StreamChain | undefined; +let latest: ReportedVersion | undefined; +let versionReadAt = Number.NEGATIVE_INFINITY; +let sweepHeight = 1; -export const startPolling = () => { - if (timeoutId) { - throw new Error("Poller already started"); - } - logger.info( - AZTEC_ENABLE_FULL_SWEEP_CATCHUP - ? "Full-sweep catchup is enabled; listener will sweep historical blocks when live head is idle." - : "Full-sweep catchup is disabled; request-driven reconciliation is the primary missing-block repair path.", +/** The rollup version the stream follows, once it follows one. */ +export const streamRollupVersion = () => chain?.rollupVersion; + +const openChain = async ({ + node, + version, +}: ReportedVersion): Promise => { + const store = new PostgresL2TipsStore( + version, + await readGenesisBlockHash(node), ); - syncRecursivePolling(true); + const source = new StickySource({ + store, + legacyProvenHeight: async () => + (await getBlockHeights()).chainProvenBlockHeight, + }); + const publisher = new ChainPublisher({ + rollupVersion: version, + store, + source, + publishBlock: onOrderedBlock, + lowerProvenCursor: lowerProcessedProvenBlockHeight, + transaction: inTransaction, + }); + return { rollupVersion: version, store, source, publisher }; }; -export const stopPolling = () => { - cancelPolling = true; - if (timeoutId) { - clearTimeout(timeoutId); - timeoutId = undefined; +/** + * The stream of the highest rollup version the nodes report, read again every + * CHAIN_INFO_POLL_INTERVAL_MS. A new version starts a new store from the + * reporting node's block 0; the old version's rows stay. + */ +export const currentChain = async (now = Date.now()): Promise => { + if (now - versionReadAt >= CHAIN_INFO_POLL_INTERVAL_MS) { + latest = + (await readLatestRollupVersion( + getOnlineRpcNodes(), + AZTEC_NODE_PROBE_TIMEOUT_MS, + )) ?? latest; + versionReadAt = now; } + if (latest === undefined) { + throw new Error("No Aztec node reported its rollup version"); + } + if (chain?.rollupVersion !== latest.version) { + const next = await openChain(latest); + if (chain !== undefined) { + logger.warn( + `Nodes report rollup version ${next.rollupVersion}; the block stream leaves version ${chain.rollupVersion} for a new store`, + ); + } + chain = next; + } + return chain; }; -const syncRecursivePolling = (isFirstRun: boolean) => { - recursivePolling(isFirstRun).catch((e) => { - logger.error(`🐻 error in recursive polling: ${(e as Error).stack}`); - }); +/** One block of the full sweep, bounded by the store's tip, not the node's. */ +const sweepOnce = async (storeTip: number, rollupVersion: number) => { + if (!AZTEC_ENABLE_FULL_SWEEP_CATCHUP || storeTip === 0) { + return; + } + const height = Math.min(sweepHeight, storeTip); + const reader = await openAttestedReader(getRpcNode(), rollupVersion); + const read = await reader.getBlock(height); + if (read === undefined) { + return; + } + await onCatchupBlock( + read.block, + "proposed", + read.finalized ? { finalized: true } : {}, + ); + sweepHeight = (height + 1) % storeTip || 1; }; -const recursivePolling = async (isFirstRun = false) => { - try { - const [chainProposedBlockHeight, chainProvenBlockHeight] = - await Promise.all([getLatestProposedHeight(), getLatestProvenHeight()]); - let heights = { - ...(await getBlockHeights()), - chainProposedBlockHeight: Number(chainProposedBlockHeight), - chainProvenBlockHeight: Number(chainProvenBlockHeight), - }; +const readProvenCursor = async () => + (await getBlockHeights()).processedProvenBlockHeight; - heights = await ensureSaneValues(heights); - const proposedProvenDiff = - heights.chainProposedBlockHeight - heights.chainProvenBlockHeight; - const proposedHeightDiff = - heights.chainProposedBlockHeight - heights.processedProposedBlockHeight; - const provenHeightDiff = - heights.chainProvenBlockHeight - heights.processedProvenBlockHeight; - logger.info(`🐱 ==== poller state ==== 🐱 ${ - proposedProvenDiff > 0 - ? `| ${proposedProvenDiff} proposed blocks ahead of proven` - : "" - } -Proposed height PROCESSED ${heights.processedProposedBlockHeight} | CHAIN ${ - heights.chainProposedBlockHeight - } | DIFF ${proposedHeightDiff} -Proven height PROCESSED ${heights.processedProvenBlockHeight} | CHAIN ${ - heights.chainProvenBlockHeight - } | DIFF ${provenHeightDiff}`); +/** + * One pass: the election and the stream, then the heights, the tips, the + * proven side work and the full sweep. The tips and the side work need the + * store to hold the pass's snapshot: an aborted pass's tips would contradict + * its blocks, and its proven tip need not be the node's. + */ +export const runPass = async ({ + rollupVersion, + store, + source, + publisher, +}: StreamChain) => { + const before = await store.getL2Tips(); + if ((await source.elect()) !== undefined) { + publisher.startPass(); + const empty = !(await holdsBlocks(store)); try { - while ( - !cancelPolling && - heights.processedProposedBlockHeight < chainProposedBlockHeight && - !AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS - ) { - heights.processedProposedBlockHeight++; - await pollProposedBlock( - heights.processedProposedBlockHeight, - isFirstRun, - ); - } - } catch (e) { - logger.error( - `🐼 error while processing proposed blocks: ${(e as Error).stack}`, - ); + await new L2BlockStream( + source, + source.localData, + publisher, + streamLogger, + { + batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, + // The stream reads this as it plans its downloads, after it read its + // snapshot: an empty store starts at that snapshot's finalized + // block, inclusive, and no history is replayed. + get startingBlock() { + return empty ? source.lastTips?.finalized.block.number : undefined; + }, + }, + ).sync(); + } finally { + publisher.finishPass(); } - try { - while ( - !cancelPolling && - heights.processedProvenBlockHeight < chainProvenBlockHeight && - !AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS - ) { - heights.processedProvenBlockHeight++; - await pollProvenBlock(heights.processedProvenBlockHeight, isFirstRun); - } - } catch (e) { - logger.error( - `🐹 error while processing proven blocks: ${(e as Error).stack}`, - ); - } - const nothingToProcess = proposedHeightDiff === 0 && provenHeightDiff === 0; - if (nothingToProcess) { - await oneEternalCatchupFetch(chainProposedBlockHeight); - } - } catch (e) { - logger.error(`🐱 error while processing blocks: ${(e as Error).stack}`); - } finally { - logger.info( - `🐱 waiting ${BLOCK_POLL_INTERVAL_MS / 1000}s for next poll...`, - ); - timeoutId = setTimeout(syncRecursivePolling, BLOCK_POLL_INTERVAL_MS); + } + const after = await store.getL2Tips(); + // Only the listener's previous version reads it, to resume from it after a + // rollback; a pass that failed after storing blocks can leave it behind. It + // waits for the store's first block: that version lifts a 0 to the chain's + // proven height, and would send again the blocks it sent above that. + if ( + (await holdsBlocks(store)) && + (await getBlockHeights()).processedProposedBlockHeight !== + after.proposed.number + ) { + await storeProcessedProposedBlockHeight(after.proposed.number); + } + const snapshot = source.lastTips; + const settled = snapshot !== undefined && localTipsMatch(after, snapshot); + if (settled && AZTEC_LISTEN_FOR_L2_TIPS) { + await publishTipsIfDue(snapshot); + } + if (settled && !AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS) { + await runProvenSideWork({ + source, + rollupVersion, + provenTip: after.proven.block.number, + finalizedTip: after.finalized.block.number, + storedHash: (height) => store.getL2BlockHash(BlockNumber(height)), + readCursor: readProvenCursor, + storeCursor: storeProcessedProvenBlockHeight, + }); + } + if (after.proposed.number === before.proposed.number) { + await sweepOnce(after.proposed.number, rollupVersion); } }; -const pollProposedBlock = async (height: number, isCatchup: boolean) => { - const block = await internalGetBlock(height); - if (isCatchup) { - await onCatchupBlock( - block, - "proposed", - { catchupReason: "eternal" }, - ); - logger.info(`🐱 catchup proposed block ${height}`); - await new Promise((r) => setTimeout(r, CATCHUP_POLL_WAIT_TIME_MS)); - } else { - await onBlock(block, "proposed"); +/** One poll: the pass of the stream `chain` gives, logging its failure. */ +export const pollOnce = async ( + chain: () => Promise = currentChain, +) => { + try { + await runPass(await chain()); + } catch (e) { + // A read with no node pinned; the next pass elects one. + if (!(e instanceof PassExit)) { + // A node read's error names the node's URL; inspect() adds the cause. + logger.error(`🐻 block stream pass failed: ${redactUrls(inspect(e))}`); + } } - await storeProcessedProposedBlockHeight(height); }; -const pollProvenBlock = async (height: number, isCatchup: boolean) => { - const block = await internalGetBlock(height); - - if (isCatchup) { - await onCatchupBlock(block, "proven"); - logger.info(`🐱 catchup proven block ${height}`); - await new Promise((r) => setTimeout(r, CATCHUP_POLL_WAIT_TIME_MS)); - } else { - await onBlock(block, "proven"); +const tick = async () => { + try { + await pollOnce(); + } finally { + if (!cancelPolling) { + timeoutId = setTimeout(() => void tick(), BLOCK_POLL_INTERVAL_MS); + } } - - await handleProvenTransactions(block); - await storeProcessedProvenBlockHeight(height); }; -const internalGetBlock = async (height: number) => { - const blockRes = await getBlock(height); - if (!blockRes) { - throw new Error(`Block ${height} not found`); +/** Opens the stream for the nodes' rollup version; a node without block 0 stops the listener. */ +export const init = async () => { + if (!AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS) { + await currentChain(); } - return blockRes; }; -const ensureSaneValues = async ( - heights: Awaited>, -) => { - if (heights.processedProvenBlockHeight > heights.chainProvenBlockHeight) { - logger.warn( - `🐷 processed proven block height is higher than chain proven height: ${heights.processedProvenBlockHeight} > ${heights.chainProvenBlockHeight}. This might be L1 reorg. Backing up DB-value to match chain proven height.`, - ); - heights.processedProvenBlockHeight = heights.chainProvenBlockHeight; - } - if (heights.processedProposedBlockHeight > heights.chainProposedBlockHeight) { - logger.warn( - `🐷 processed proposed block height is higher than chain proposed height: ${heights.processedProposedBlockHeight} > ${heights.chainProposedBlockHeight}. This might be L2 (or even L1?) reorg. Backing up DB-value to match chain proposed height.`, - ); - heights.processedProposedBlockHeight = heights.chainProposedBlockHeight; +export const startPolling = () => { + if (started) { + throw new Error("Poller already started"); } - if (heights.processedProposedBlockHeight < heights.chainProvenBlockHeight) { - logger.debug( - `🐷 processed proposed block height is lower than chain proven height: ${heights.processedProposedBlockHeight} < ${heights.chainProvenBlockHeight}. Adjusting DB-value so that block is not fetched twice.`, + started = true; + logger.info( + AZTEC_ENABLE_FULL_SWEEP_CATCHUP + ? "Full-sweep catchup is enabled; listener will sweep historical blocks when live head is idle." + : "Full-sweep catchup is disabled; request-driven reconciliation is the primary missing-block repair path.", + ); + if (AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS) { + logger.info( + "AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS is set; the block stream does not run", ); - heights.processedProposedBlockHeight = heights.chainProvenBlockHeight; + return; } - await storeBlockHeights(heights); - return heights; + void tick(); }; -let currentEternalCatchupHeight = 1; -const oneEternalCatchupFetch = async (currentProposedHeight: number) => { - if (!AZTEC_ENABLE_FULL_SWEEP_CATCHUP) { - return; - } - // NOTE: if we have started the poller without catchup, we at least want it to eventually be in sync - const block = await internalGetBlock(currentEternalCatchupHeight); - if (block) { - await onCatchupBlock(block, "proposed"); - currentEternalCatchupHeight = - (currentEternalCatchupHeight + 1) % currentProposedHeight || 1; - currentEternalCatchupHeight = Math.min( - currentEternalCatchupHeight, - currentProposedHeight, - ); - } +export const stopPolling = () => { + cancelPolling = true; + clearTimeout(timeoutId); + timeoutId = undefined; }; diff --git a/services/aztec-listener/src/svcs/poller/pollers/block_poller/proven-side-work.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/proven-side-work.ts new file mode 100644 index 000000000..254572615 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/proven-side-work.ts @@ -0,0 +1,95 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { type L2Block } from "@aztec-labs/stdlib/block"; +import { + AZTEC_BLOCK_STREAM_BATCH_SIZE, + AZTEC_PROVEN_BLOCKS_PER_PASS, +} from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { type StickySource } from "../../network-client/block-stream-source.js"; +import { redactUrls } from "../../network-client/redact-urls.js"; +import { + type ReadPublicStorage, + handleProvenTransactions, +} from "./handle-proven-block-txs.js"; + +export type ProvenSideWorkDeps = { + source: Pick; + rollupVersion: number; + /** The pinned node's proven tip, as the store holds it after a settled pass. */ + provenTip: number; + /** The store's finalized tip; the store keeps no hashes below it. */ + finalizedTip: number; + storedHash: (height: number) => Promise; + readCursor: () => Promise; + storeCursor: (height: number) => Promise; +}; + +// The node can serve another block at a height once the pass has settled. +// Below the finalized tip, where a block cannot change, the store keeps no +// hash, so the side work trusts the pinned node's block there. +const onStoredChain = async ( + block: L2Block, + { rollupVersion, finalizedTip, storedHash }: ProvenSideWorkDeps, +) => { + if ( + block.header.globalVariables.version.toBigInt() !== BigInt(rollupVersion) + ) { + return false; + } + const stored = await storedHash(block.number); + return stored === undefined + ? block.number < finalizedTip + : stored === (await block.hash()).toString(); +}; + +/** + * Runs the proven blocks above the cursor, at most `max` of them, from the + * pinned node, and moves the cursor past each block that completed. A failed + * block, or one off the stored chain, stops the run, so the next pass retries + * it. + */ +export const runProvenSideWork = async ( + deps: ProvenSideWorkDeps, + { max, batchSize } = { + max: AZTEC_PROVEN_BLOCKS_PER_PASS, + batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, + }, +) => { + const { source, provenTip, readCursor, storeCursor } = deps; + let cursor = await readCursor(); + // The cursor spans rollup versions, and a new version's heights start over. + if (cursor > provenTip) { + cursor = provenTip; + await storeCursor(cursor); + } + const end = Math.min(provenTip, cursor + max); + const readStorage: ReadPublicStorage = (block, contract, slot) => + source.pinnedRead("getPublicStorageAt", [block, contract, slot]); + while (cursor < end) { + const blocks = await source.getBlocks({ + from: BlockNumber(cursor + 1), + limit: Math.min(batchSize, end - cursor), + }); + // Below the snapshot's tip, so the source has benched the node. + if (blocks.length === 0) { + return; + } + for (const block of blocks) { + if (!(await onStoredChain(block, deps))) { + logger.warn( + `Proven side work stopped at block ${block.number}, which is not the block the block stream stored there; the next pass retries`, + ); + return; + } + const outcome = await handleProvenTransactions(block, readStorage); + if (!outcome.ok) { + logger.warn( + `Proven side work stopped at block ${block.number}, which the next pass retries: ${redactUrls(outcome.error.message)}`, + ); + return; + } + cursor = block.number; + await storeCursor(cursor); + } + } +}; diff --git a/services/aztec-listener/src/svcs/poller/pollers/block_poller/stream-logger.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/stream-logger.ts new file mode 100644 index 000000000..ec2fef427 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/stream-logger.ts @@ -0,0 +1,35 @@ +import { inspect } from "node:util"; +import { type Logger as SdkLogger } from "@aztec-labs/foundation/log"; +import { logger } from "../../../../logger.js"; +import { redactUrls } from "../../network-client/redact-urls.js"; + +// The stream's data carries bigints, which JSON rejects. +const line = (msg: string, ...data: unknown[]) => + redactUrls( + [msg, ...data.filter((d) => d !== undefined).map((d) => inspect(d))].join( + " ", + ), + ); + +/** + * The SDK block stream's logger, routed to the listener's. The stream reports + * its own failures only here, so they must not go to the SDK's own output. + */ +export const streamLogger: SdkLogger = { + silent: () => undefined, + fatal: (msg: string, err?: unknown, data?: unknown) => + logger.error(line(msg, err, data)), + error: (msg: string, err?: unknown, data?: unknown) => + logger.error(line(msg, err, data)), + warn: (msg, data) => logger.warn(line(msg, data)), + info: (msg, data) => logger.info(line(msg, data)), + verbose: (msg, data) => logger.debug(line(msg, data)), + debug: (msg, data) => logger.debug(line(msg, data)), + // Every pass traces its tips and each hash it compares. + trace: () => undefined, + level: "debug", + isLevelEnabled: (level) => level !== "trace" && level !== "silent", + module: "block-stream", + createChild: () => streamLogger, + getBindings: () => ({}), +}; diff --git a/services/aztec-listener/src/svcs/poller/pollers/l2-tips-poller.ts b/services/aztec-listener/src/svcs/poller/pollers/l2-tips-poller.ts index 0dae8fd3b..9e23af4cf 100644 --- a/services/aztec-listener/src/svcs/poller/pollers/l2-tips-poller.ts +++ b/services/aztec-listener/src/svcs/poller/pollers/l2-tips-poller.ts @@ -5,13 +5,9 @@ import { chicmozL2TipsSchema, jsonStringify, } from "@chicmoz-pkg/types"; -import { - L2_TIPS_HEARTBEAT_INTERVAL_MS, - L2_TIPS_POLL_INTERVAL_MS, -} from "../../../environment.js"; +import { type L2Tips } from "@aztec-labs/stdlib/block"; +import { L2_TIPS_HEARTBEAT_INTERVAL_MS } from "../../../environment.js"; import { onL2Tips } from "../../../events/emitted/index.js"; -import { logger } from "../../../logger.js"; -import { getL2Tips } from "../network-client/index.js"; type RawTipBlock = { number: { valueOf?: () => unknown } | number | bigint; hash: unknown }; type RawCheckpointTip = { @@ -26,7 +22,6 @@ type RawL2Tips = { finalized: RawCheckpointTip; }; -let pollInterval: NodeJS.Timeout | undefined; let lastPublishedTips: string | undefined; let lastPublishedAt = 0; @@ -68,8 +63,8 @@ const normalizeTips = (tips: RawL2Tips): ChicmozL2Tips => finalized: normalizeCheckpointTip(tips.finalized), }); -const pollOnce = async () => { - const tips = normalizeTips((await getL2Tips()) as unknown as RawL2Tips); +export const publishTipsIfDue = async (raw: L2Tips) => { + const tips = normalizeTips(raw as unknown as RawL2Tips); const serialized = jsonStringify(tips); const heartbeatDue = Date.now() - lastPublishedAt >= L2_TIPS_HEARTBEAT_INTERVAL_MS; if (serialized === lastPublishedTips && !heartbeatDue) { @@ -79,20 +74,3 @@ const pollOnce = async () => { lastPublishedTips = serialized; lastPublishedAt = Date.now(); }; - -export const startPolling = () => { - pollOnce().catch((error) => { - logger.error(`Error fetching L2 tips: ${(error as Error).stack}`); - }); - pollInterval = setInterval(() => { - pollOnce().catch((error) => { - logger.error(`Error fetching L2 tips: ${(error as Error).stack}`); - }); - }, L2_TIPS_POLL_INTERVAL_MS); -}; - -export const stopPolling = () => { - if (pollInterval) { - clearInterval(pollInterval); - } -}; diff --git a/services/aztec-listener/tests/characterization/producer-payloads.corpus.test.ts b/services/aztec-listener/tests/characterization/producer-payloads.corpus.test.ts index 02f818531..c8bec4b49 100644 --- a/services/aztec-listener/tests/characterization/producer-payloads.corpus.test.ts +++ b/services/aztec-listener/tests/characterization/producer-payloads.corpus.test.ts @@ -14,9 +14,8 @@ import type * as NetworkClient from "../../src/svcs/poller/network-client/index. import type * as Pool from "../../src/svcs/poller/network-client/pool.js"; import { mockLogger, mockTxsController } from "../mocks/index.js"; -const { publish, getL2Tips, pool } = vi.hoisted(() => ({ +const { publish, pool } = vi.hoisted(() => ({ publish: vi.fn<(topic: string, payload: unknown) => Promise>(), - getL2Tips: vi.fn<() => Promise>(), pool: { nodes: [] as Pool.RpcNode[] }, })); @@ -29,9 +28,6 @@ vi.mock("../../src/svcs/database/index.js", () => ({ txsController: mockTxsController, })); vi.mock("../../src/logger.js", () => ({ logger: mockLogger })); -vi.mock("../../src/svcs/poller/network-client/index.js", () => ({ - getL2Tips, -})); vi.mock( "../../src/svcs/poller/network-client/pool.js", async (importOriginal) => ({ @@ -145,22 +141,17 @@ describe("aztec-listener producer frames", () => { for (const source of FIXTURE_SOURCES) { for (const name of listFixtures(source, "l2-tips")) { - // The poller skips tips equal to the last ones it published. + // The publisher skips tips equal to the last ones it published. vi.resetModules(); - const poller = await import( + const { publishTipsIfDue } = await import( "../../src/svcs/poller/pollers/l2-tips-poller.js" ); - getL2Tips.mockResolvedValueOnce( - L2TipsSchema.parse(loadFixture(source, "l2-tips", name).data.result), + const tips = L2TipsSchema.parse( + loadFixture(source, "l2-tips", name).data.result, + ); + await record({ [`${source}/l2-tips`]: "L2_TIPS_EVENT" }, () => + publishTipsIfDue(tips), ); - mockLogger.error.mockClear(); - await record({ [`${source}/l2-tips`]: "L2_TIPS_EVENT" }, async () => { - poller.startPolling(); - await flush(); - poller.stopPolling(); - // The poller logs a failed poll instead of throwing. - expect(mockLogger.error).not.toHaveBeenCalled(); - }); } } diff --git a/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts new file mode 100644 index 000000000..698686c17 --- /dev/null +++ b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts @@ -0,0 +1,190 @@ +import { randomBytes } from "node:crypto"; +import { + BlockNumber, + CheckpointNumber, +} from "@aztec-labs/foundation/branded-types"; +import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { + type L2BlockId, + type L2BlockStreamEvent, + L2Block, + type L2Tips, +} from "@aztec-labs/stdlib/block"; +import { attach, createDatabase } from "@chicmoz/test-harness"; +import { type MicroserviceBaseSvc } from "@chicmoz-pkg/microservice-base"; +import { afterAll, beforeAll, describe, expect, inject, it, vi } from "vitest"; +import { TEMPLATE_DB } from "./support/constants.js"; + +type Modules = { + store: typeof import("../../src/svcs/database/l2-tips-store.js"); + heights: typeof import("../../src/svcs/database/heights.controller.js"); + transaction: typeof import("../../src/svcs/database/transaction.js"); + publisher: typeof import("../../src/svcs/poller/pollers/block_poller/chain-publisher.js"); +}; + +const VERSION = 11; +// Each test gets a store of its own version in the file's database. +let nextVersion = VERSION; +let modules: Modules; +let database: MicroserviceBaseSvc; + +beforeAll(async () => { + const stack = attach(inject("harnessStack")); + const dbName = `t_${randomBytes(4).toString("hex")}`; + await createDatabase(stack, dbName, { template: TEMPLATE_DB }); + Object.assign(process.env, stack.env, { + POSTGRES_DB_NAME: dbName, + L2_NETWORK_ID: "SANDBOX", + }); + // These modules read their environment at import. + const { MicroserviceBaseSvcState, setLogger, setSvcState } = await import( + "@chicmoz-pkg/microservice-base" + ); + const { logger } = await import("../../src/logger.js"); + setLogger(logger); + ({ databaseService: database } = await import( + "../../src/svcs/database/index.js" + )); + setSvcState(database.svcId, MicroserviceBaseSvcState.INITIALIZING); + await database.init(); + setSvcState(database.svcId, MicroserviceBaseSvcState.UP); + modules = { + store: await import("../../src/svcs/database/l2-tips-store.js"), + heights: await import("../../src/svcs/database/heights.controller.js"), + transaction: await import("../../src/svcs/database/transaction.js"), + publisher: await import( + "../../src/svcs/poller/pollers/block_poller/chain-publisher.js" + ), + }; + await modules.heights.ensureInitializedBlockHeights(); +}); + +afterAll(async () => { + await database.shutdown(); +}); + +const idOf = async (block: L2Block): Promise => ({ + number: block.number, + hash: (await block.hash()).toString(), +}); + +const tierOf = async (block: L2Block) => ({ + block: await idOf(block), + checkpoint: { + number: CheckpointNumber(block.number), + hash: `0x${block.number.toString(16).padStart(64, "0")}`, + }, +}); + +/** + * A fresh store holding blocks 1-8, proven at 6, the proven cursor at 6, and + * a publisher whose cursor write fails after it lands when `failCursor` is set. + */ +const arrange = async (failCursor: boolean) => { + const blocks = await Promise.all( + Array.from({ length: 9 }, (_, n) => + L2Block.random(BlockNumber(n), { txsPerBlock: 0 }), + ), + ); + const version = nextVersion++; + const store = new modules.store.PostgresL2TipsStore( + version, + await blocks[0].hash(), + ); + await store.handleBlockStreamEvent({ + type: "blocks-added", + blocks: blocks.slice(1), + }); + await store.handleBlockStreamEvent({ + type: "chain-proven", + ...(await tierOf(blocks[6])), + }); + await modules.heights.storeProcessedProvenBlockHeight(6); + const snapshot: L2Tips = { + proposed: { number: BlockNumber(9), hash: Fr.random().toString() }, + checkpointed: await tierOf(blocks[8]), + proven: await tierOf(blocks[4]), + finalized: await tierOf(blocks[0]), + }; + const publisher = new modules.publisher.ChainPublisher({ + rollupVersion: version, + store, + source: { + pinned: undefined, + lastTips: snapshot, + pinnedBlockData: vi.fn(), + pinnedBlockDataUnbenched: vi.fn(), + benchPinnedUntilNewTip: vi.fn(), + benchPinnedPastNextElection: vi.fn(), + setAsidePinned: vi.fn(), + }, + publishBlock: () => Promise.resolve(), + lowerProvenCursor: async (height) => { + await modules.heights.lowerProcessedProvenBlockHeight(height); + if (failCursor) { + throw new Error("injected after the cursor write"); + } + }, + transaction: modules.transaction.inTransaction, + }); + const state = async () => ({ + tips: await store.getL2Tips(), + hashes: await Promise.all( + blocks.map((_, n) => store.getL2BlockHash(BlockNumber(n))), + ), + cursor: (await modules.heights.getBlockHeights()) + .processedProvenBlockHeight, + }); + return { blocks, snapshot, publisher, state }; +}; + +const pruneTo = async ( + blocks: L2Block[], + snapshot: L2Tips, +): Promise => ({ + type: "chain-pruned", + block: await idOf(blocks[5]), + checkpointed: snapshot.checkpointed, + proven: snapshot.proven, +}); + +describe("ChainPublisher on Postgres", () => { + it.each([ + { + change: "a prune", + event: (blocks: L2Block[], snapshot: L2Tips) => pruneTo(blocks, snapshot), + }, + { + change: "a proof that moves back", + event: async (blocks: L2Block[]): Promise => ({ + type: "chain-proven", + ...(await tierOf(blocks[4])), + }), + }, + ])( + "rolls back $change and the proven cursor together when a write after the store's fails", + async ({ event }) => { + const { blocks, snapshot, publisher, state } = await arrange(true); + const before = await state(); + + await expect( + publisher.handleBlockStreamEvent(await event(blocks, snapshot)), + ).rejects.toThrow("injected after the cursor write"); + + expect(await state()).toEqual(before); + }, + ); + + it("stores a prune and moves the proven cursor back to its proven tip in one transaction", async () => { + const { blocks, snapshot, publisher, state } = await arrange(false); + + await publisher.handleBlockStreamEvent(await pruneTo(blocks, snapshot)); + + const after = await state(); + expect(after.tips.proposed).toEqual(await idOf(blocks[5])); + expect(after.tips.proven.block).toEqual(await idOf(blocks[4])); + expect(after.cursor).toBe(4); + await modules.heights.lowerProcessedProvenBlockHeight(7); + expect((await state()).cursor).toBe(4); + }); +}); diff --git a/services/aztec-listener/tests/mocks/index.ts b/services/aztec-listener/tests/mocks/index.ts index 69eb0399e..197799635 100644 --- a/services/aztec-listener/tests/mocks/index.ts +++ b/services/aztec-listener/tests/mocks/index.ts @@ -11,6 +11,7 @@ export const mockTxsController = { // Mock the message bus export const mockMessageBus = { publishMessage: vi.fn(), + publishKeyedMessage: vi.fn(), publishMessageSync: vi.fn(), }; @@ -110,6 +111,7 @@ export const mockModules = { // Mock the message bus module "../../src/svcs/message-bus/index.js": () => ({ publishMessage: mockMessageBus.publishMessage, + publishKeyedMessage: mockMessageBus.publishKeyedMessage, publishMessageSync: mockMessageBus.publishMessageSync, }), diff --git a/services/aztec-listener/tests/unit/attested-reads.test.ts b/services/aztec-listener/tests/unit/attested-reads.test.ts new file mode 100644 index 000000000..76f6278c4 --- /dev/null +++ b/services/aztec-listener/tests/unit/attested-reads.test.ts @@ -0,0 +1,111 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { L2Block } from "@aztec-labs/stdlib/block"; +import { beforeAll, describe, expect, it, vi } from "vitest"; +import { openAttestedReader } from "../../src/svcs/poller/network-client/attested-reads.js"; +import { NodeCheckError } from "../../src/svcs/poller/network-client/block-stream-source.js"; +import { + type Chain, + FakeNode, + ROLLUP_VERSION, + emptyBlock, + genesisChain, + grow, + respond, +} from "./support/chain.js"; + +vi.mock("../../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, +})); +vi.mock("../../src/events/emitted/index.js", () => ({ + onChainInfo: vi.fn(), + onL2RpcNodeAlive: vi.fn(), + onL2RpcNodeError: vi.fn(), + onL2RpcNodeInfo: vi.fn(), +})); + +let chain: Chain; + +beforeAll(async () => { + chain = await grow(await genesisChain(), 4); +}); + +const nodeAt = (finalized: number) => { + const node = new FakeNode("x", chain); + node.tiers = { checkpointed: 4, proven: 3, finalized }; + return node; +}; + +describe("openAttestedReader", () => { + it("reads the node's tips and version before its blocks, with the caller's heartbeat between the two, and marks a block finalized only at or below its finalized tip", async () => { + const node = nodeAt(2); + const reader = await openAttestedReader(node.rpc, ROLLUP_VERSION, () => { + node.calls.push("heartbeat"); + return Promise.resolve(); + }); + + const [two, three] = [await reader.getBlock(2), await reader.getBlock(3)]; + + expect(node.calls).toEqual([ + "getChainTips", + "heartbeat", + "getNodeInfo", + "getBlock", + "getBlock", + ]); + expect(await two?.block.hash()).toEqual(await chain.blocks[2].hash()); + expect([two?.finalized, three?.finalized]).toEqual([true, false]); + expect(reader.tips.proposed.number).toBe(4); + }); + + it.each([ + { + on: "a node of another rollup version", + nodeVersion: ROLLUP_VERSION + 1, + blockVersion: ROLLUP_VERSION, + streamVersion: ROLLUP_VERSION, + }, + { + on: "a block of another rollup version", + nodeVersion: ROLLUP_VERSION, + blockVersion: ROLLUP_VERSION + 1, + streamVersion: ROLLUP_VERSION, + }, + { + on: "a stream that follows no version yet", + nodeVersion: ROLLUP_VERSION, + blockVersion: ROLLUP_VERSION, + streamVersion: undefined, + }, + ])( + "marks no block finalized on $on", + async ({ nodeVersion, blockVersion, streamVersion }) => { + const node = nodeAt(4); + node.rollupVersion = nodeVersion; + const block = await emptyBlock(1, chain.blocks[0], blockVersion); + node.getBlockOverride = () => respond(block, true); + const reader = await openAttestedReader(node.rpc, streamVersion); + + expect((await reader.getBlock(1))?.finalized).toBe(false); + }, + ); + + it.each([ + { + answer: "another block than the one asked", + serve: () => respond(chain.blocks[3], true), + }, + { + answer: "a body that does not match its header", + serve: async () => ({ + ...(await respond(chain.blocks[2], true)), + body: (await L2Block.random(BlockNumber(2), { txsPerBlock: 1 })).body, + }), + }, + ])("throws when the node answers with $answer", async ({ serve }) => { + const node = nodeAt(2); + node.getBlockOverride = serve; + const reader = await openAttestedReader(node.rpc, ROLLUP_VERSION); + + await expect(reader.getBlock(2)).rejects.toThrow(NodeCheckError); + }); +}); diff --git a/services/aztec-listener/tests/unit/block-poller-cursor.test.ts b/services/aztec-listener/tests/unit/block-poller-cursor.test.ts index dbeb13de9..e1079898b 100644 --- a/services/aztec-listener/tests/unit/block-poller-cursor.test.ts +++ b/services/aztec-listener/tests/unit/block-poller-cursor.test.ts @@ -1,100 +1,273 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; - -const node = vi.hoisted(() => ({ - tip: 5, - processedProposed: 5, - failOnce: new Set(), - delivered: [] as number[], - pollsFinished: 0, -})); +import { type L2Block } from "@aztec-labs/stdlib/block"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { + type ProvenSideWorkDeps, + runProvenSideWork, +} from "../../src/svcs/poller/pollers/block_poller/proven-side-work.js"; + +type StoredTx = { txHash: string; feePayer: string; txState: string }; -vi.mock("../../src/environment.js", () => ({ - AZTEC_ENABLE_FULL_SWEEP_CATCHUP: false, - AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS: false, - AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS: false, - BLOCK_POLL_INTERVAL_MS: 60_000, - CATCHUP_POLL_WAIT_TIME_MS: 0, +const db = vi.hoisted(() => ({ + txs: new Map(), + published: [] as Record[], +})); +const logger = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), })); -vi.mock("../../src/logger.js", () => ({ - logger: { - debug: () => undefined, - info: (message: string) => { - if (message.startsWith("🐱 waiting")) { - node.pollsFinished++; + +vi.mock("../../src/logger.js", () => ({ logger })); +vi.mock("../../src/svcs/database/index.js", () => ({ + txsController: { + getTxsByHashes: (hashes: string[]) => + Promise.resolve( + hashes.flatMap((hash) => { + const tx = db.txs.get(hash); + return tx === undefined ? [] : [{ ...tx }]; + }), + ), + storeOrUpdateState: (hash: string, txState: string) => { + const tx = db.txs.get(hash); + if (tx !== undefined) { + tx.txState = txState; } + return Promise.resolve(); }, - warn: () => undefined, - error: () => undefined, - }, -})); -vi.mock("../../src/svcs/database/heights.controller.js", () => ({ - getBlockHeights: () => - Promise.resolve({ - processedProposedBlockHeight: node.processedProposed, - processedProvenBlockHeight: 5, - chainProposedBlockHeight: 0, - chainProvenBlockHeight: 0, - }), - storeBlockHeights: (heights: { processedProposedBlockHeight: number }) => { - node.processedProposed = heights.processedProposedBlockHeight; - return Promise.resolve(); - }, - storeProcessedProposedBlockHeight: (height: number) => { - node.processedProposed = height; - return Promise.resolve(); }, - storeProcessedProvenBlockHeight: () => Promise.resolve(), -})); -vi.mock("../../src/svcs/poller/network-client/index.js", () => ({ - getBlock: (height: number) => Promise.resolve({ height }), - getLatestProposedHeight: () => Promise.resolve(node.tip), - getLatestProvenHeight: () => Promise.resolve(5), })); -vi.mock("../../src/events/emitted/index.js", () => ({ - onBlock: ({ height }: { height: number }) => { - if (node.failOnce.delete(height)) { - return Promise.reject(new Error("publish rejected")); - } - node.delivered.push(height); +vi.mock("../../src/svcs/message-bus/index.js", () => ({ + publishMessage: (_: string, payload: Record) => { + db.published.push(payload); return Promise.resolve(); }, - onCatchupBlock: () => Promise.resolve(), })); -vi.mock( - "../../src/svcs/poller/pollers/block_poller/handle-proven-block-txs.js", - () => ({ handleProvenTransactions: () => Promise.resolve() }), -); -afterEach(() => { - vi.useRealTimers(); +const PAYER = `0x${"11".repeat(32)}`; +const VERSION = 7; + +// The side work reads a block's number, version, tx hashes, hash and fee recipient. +const blockAt = (n: number, txHashes: string[] = [], version = VERSION) => + ({ + number: n, + body: { + txEffects: txHashes.map((hash) => ({ txHash: { toString: () => hash } })), + }, + header: { + globalVariables: { + blockNumber: n, + version: { toBigInt: () => BigInt(version) }, + feeRecipient: { toString: () => "0xfee" }, + }, + }, + hash: () => Promise.resolve(`block-${n}`), + }) as unknown as L2Block; + +/** A pinned node serving `blocks`, whose balance reads fail at the heights in `failing` once each. */ +const sourceOf = (blocks: L2Block[], failing = new Set()) => { + const ranges: { from: number; limit: number }[] = []; + const source = { + getBlocks: ({ from, limit }: { from: number; limit: number }) => { + ranges.push({ from, limit }); + return Promise.resolve(blocks.slice(from - 1, from - 1 + limit)); + }, + // The fee juice balance at a block is its height. + pinnedRead: (_: string, [block]: unknown[]) => { + const height = Number(String(block).slice("block-".length)); + return failing.delete(height) + ? Promise.reject(new Error("storage read failed")) + : Promise.resolve({ toBigInt: () => BigInt(height) }); + }, + } as unknown as ProvenSideWorkDeps["source"]; + return { source, ranges }; +}; + +const cursorAt = (start: number) => { + const cursor = { value: start }; + return { + cursor, + readCursor: () => Promise.resolve(cursor.value), + storeCursor: (height: number) => { + cursor.value = height; + return Promise.resolve(); + }, + }; +}; + +/** A store that holds every served block's hash, unless `stored` says otherwise. */ +const depsOf = ( + source: ProvenSideWorkDeps["source"], + provenTip: number, + cursors: Pick, + { + finalizedTip = 0, + stored = (height: number) => `block-${height}` as string | undefined, + } = {}, +): ProvenSideWorkDeps => ({ + source, + rollupVersion: VERSION, + provenTip, + finalizedTip, + storedHash: (height) => Promise.resolve(stored(height)), + ...cursors, +}); + +const balances = () => + db.published.map( + ({ contractAddress, balance, sourceTxHash, blockNumber }) => ({ + contractAddress, + balance, + sourceTxHash, + blockNumber, + }), + ); + +beforeEach(() => { + vi.clearAllMocks(); + db.txs.clear(); + db.published.length = 0; }); -// A cursor stored past a block whose publish failed leaves that block to -// reconciliation; only the real poll loop shows the store follows the publish. -describe("block poller cursor", () => { - it("re-polls a proposed block whose publish failed before marking it processed", async () => { - vi.useFakeTimers(); - const poller = await import( - "../../src/svcs/poller/pollers/block_poller/index.js" +describe("proven side work", () => { + it("runs a 201-block proven advance over two passes, moving the cursor past each block", async () => { + const { source, ranges } = sourceOf( + Array.from({ length: 201 }, (_, i) => blockAt(i + 1)), + ); + const { cursor, ...cursors } = cursorAt(0); + const run = () => runProvenSideWork(depsOf(source, 201, cursors)); + + await run(); + expect(cursor.value).toBe(200); + await run(); + expect(cursor.value).toBe(201); + + expect(ranges.every(({ limit }) => limit <= 10)).toBe(true); + expect(ranges.at(-1)).toEqual({ from: 201, limit: 1 }); + }); + + it("stops at a block that fails and runs it again on the next pass", async () => { + db.txs.set("tx-2", { + txHash: "tx-2", + feePayer: PAYER, + txState: "proposed", + }); + const { source } = sourceOf( + [blockAt(1), blockAt(2, ["tx-2"]), blockAt(3)], + new Set([2]), ); - const pollFinished = (count: number) => - vi.waitFor(() => expect(node.pollsFinished).toBe(count)); - - poller.startPolling(); // the first poll is a catch-up run; nothing to do - try { - await pollFinished(1); - node.tip = 7; - node.failOnce.add(6); - await vi.advanceTimersByTimeAsync(60_000); - await pollFinished(2); - expect(node.processedProposed).toBe(5); - await vi.advanceTimersByTimeAsync(60_000); - await pollFinished(3); - } finally { - poller.stopPolling(); - } - - expect(node.delivered).toEqual([6, 7]); - expect(node.processedProposed).toBe(7); + const { cursor, ...cursors } = cursorAt(0); + const run = () => runProvenSideWork(depsOf(source, 3, cursors)); + + await run(); + expect(cursor.value).toBe(1); + expect(db.published).toEqual([]); + expect(db.txs.get("tx-2")?.txState).toBe("proposed"); + expect(logger.warn).toHaveBeenCalledTimes(1); + + await run(); + expect(cursor.value).toBe(3); + expect(balances()).toEqual([ + { + contractAddress: PAYER, + balance: "2", + sourceTxHash: "tx-2", + blockNumber: "2", + }, + ]); + expect(db.txs.get("tx-2")?.txState).toBe("proven"); + }); + + it("moves its cursor down to a lower proven tip, where a new rollup version's heights start over", async () => { + const { source } = sourceOf([blockAt(1), blockAt(2), blockAt(3)]); + const { cursor, ...cursors } = cursorAt(50); + + await runProvenSideWork(depsOf(source, 2, cursors)); + expect(cursor.value).toBe(2); + await runProvenSideWork(depsOf(source, 3, cursors)); + expect(cursor.value).toBe(3); + }); + + it.each([ + { + at2: "another hash than the stored one", + stored: "block-2'", + finalizedTip: 0, + version: VERSION, + runs: false, + }, + { + at2: "no hash, below the finalized tip", + stored: undefined, + finalizedTip: 3, + version: VERSION, + runs: true, + }, + { + at2: "no hash, at the finalized tip", + stored: undefined, + finalizedTip: 2, + version: VERSION, + runs: false, + }, + { + at2: "a block of another rollup version", + stored: "block-2", + finalizedTip: 0, + version: VERSION + 1, + runs: false, + }, + ])( + "with $at2 at block 2, runs it: $runs", + async ({ stored, finalizedTip, version, runs }) => { + db.txs.set("tx-2", { + txHash: "tx-2", + feePayer: PAYER, + txState: "proposed", + }); + const { source } = sourceOf([ + blockAt(1), + blockAt(2, ["tx-2"], version), + blockAt(3), + ]); + const { cursor, ...cursors } = cursorAt(0); + + await runProvenSideWork( + depsOf(source, 3, cursors, { + finalizedTip, + stored: (height) => (height === 2 ? stored : `block-${height}`), + }), + ); + + expect(cursor.value).toBe(runs ? 3 : 1); + expect(db.txs.get("tx-2")?.txState).toBe(runs ? "proven" : "proposed"); + expect(logger.warn).toHaveBeenCalledTimes(runs ? 0 : 1); + }, + ); + + it("sends the same updates when its cursor moves back over a block whose txs it marked proven", async () => { + db.txs.set("tx-1", { txHash: "tx-1", feePayer: PAYER, txState: "pending" }); + const { source } = sourceOf([blockAt(1, ["tx-1"]), blockAt(2)]); + const { cursor, ...cursors } = cursorAt(0); + const run = () => runProvenSideWork(depsOf(source, 2, cursors)); + + await run(); + const first = balances(); + expect(db.txs.get("tx-1")?.txState).toBe("proven"); + // As a stored prune or a proof that moved back leaves it. + cursor.value = 0; + db.published.length = 0; + await run(); + + expect(balances()).toEqual(first); + expect(first).toEqual([ + { + contractAddress: PAYER, + balance: "1", + sourceTxHash: "tx-1", + blockNumber: "1", + }, + ]); + expect(cursor.value).toBe(2); }); }); diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts new file mode 100644 index 000000000..56503ca51 --- /dev/null +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -0,0 +1,390 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { AbortError } from "@aztec-labs/foundation/error"; +import { type BlockHash } from "@aztec-labs/stdlib/block"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { CHAIN_INFO_POLL_INTERVAL_MS } from "../../src/environment.js"; +import { StickySource } from "../../src/svcs/poller/network-client/block-stream-source.js"; +import { ChainPublisher } from "../../src/svcs/poller/pollers/block_poller/chain-publisher.js"; +import { + currentChain, + pollOnce, + runPass, + streamRollupVersion, +} from "../../src/svcs/poller/pollers/block_poller/index.js"; +import { runProvenSideWork } from "../../src/svcs/poller/pollers/block_poller/proven-side-work.js"; +import { + type Chain, + FakeNode, + ROLLUP_VERSION, + genesisChain, + grow, + memoryStore, + prefix, + readerOf, + respond, + tipsOf, +} from "./support/chain.js"; + +const mocks = vi.hoisted(() => { + const heights = { processedProposedBlockHeight: 0 }; + return { + heights, + // An apostrophe in its path stops the generic URL pattern. + configuredUrl: + "https://node.example:8443/v1/it's-key123secret?apikey=key456secret", + sweep: false, + openAttestedReader: vi.fn(() => + Promise.resolve({ getBlock: () => Promise.resolve(undefined) }), + ), + publishTipsIfDue: vi.fn(), + storeProcessedProposedBlockHeight: vi.fn((height: number) => { + heights.processedProposedBlockHeight = height; + return Promise.resolve(); + }), + readLatestRollupVersion: vi.fn(), + readGenesisBlockHash: vi.fn(), + stores: [] as { version: number; genesis: unknown }[], + }; +}); +const logger = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), +})); + +vi.mock("../../src/logger.js", () => ({ logger })); +vi.mock("../../src/environment.js", async (importOriginal) => ({ + ...(await importOriginal()), + AZTEC_RPC_URLS: [{ name: "configured", url: mocks.configuredUrl }], + get AZTEC_ENABLE_FULL_SWEEP_CATCHUP() { + return mocks.sweep; + }, +})); +vi.mock("../../src/svcs/poller/network-client/attested-reads.js", () => ({ + openAttestedReader: mocks.openAttestedReader, +})); +vi.mock( + "../../src/svcs/poller/network-client/pool.js", + async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../src/svcs/poller/network-client/pool.js") + >()), + getRpcNode: () => ({ name: "pool", url: "http://pool.invalid" }), + }), +); +vi.mock("../../src/events/emitted/index.js", () => ({ + onCatchupBlock: vi.fn(), + onChainInfo: vi.fn(), + onL2RpcNodeAlive: vi.fn(), + onL2RpcNodeError: vi.fn(), + onL2RpcNodeInfo: vi.fn(), + onOrderedBlock: vi.fn(), +})); +vi.mock("../../src/svcs/poller/pollers/l2-tips-poller.js", () => ({ + publishTipsIfDue: mocks.publishTipsIfDue, +})); +vi.mock("../../src/svcs/database/heights.controller.js", () => ({ + getBlockHeights: () => + Promise.resolve({ + processedProposedBlockHeight: mocks.heights.processedProposedBlockHeight, + processedProvenBlockHeight: 0, + chainProvenBlockHeight: 0, + }), + lowerProcessedProvenBlockHeight: vi.fn(), + storeProcessedProposedBlockHeight: mocks.storeProcessedProposedBlockHeight, + storeProcessedProvenBlockHeight: vi.fn(), +})); +vi.mock("../../src/svcs/database/l2-tips-store.js", () => ({ + PostgresL2TipsStore: class { + constructor(version: number, genesis: unknown) { + mocks.stores.push({ version, genesis }); + } + }, +})); +vi.mock( + "../../src/svcs/poller/pollers/block_poller/proven-side-work.js", + () => ({ + runProvenSideWork: vi.fn(), + }), +); +vi.mock("../../src/svcs/poller/network-client/rollup-version.js", () => ({ + readLatestRollupVersion: mocks.readLatestRollupVersion, +})); +vi.mock( + "../../src/svcs/poller/network-client/block-stream-source.js", + async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../../src/svcs/poller/network-client/block-stream-source.js") + >()), + readGenesisBlockHash: mocks.readGenesisBlockHash, + }), +); + +let main: Chain; +let genesis: BlockHash; + +beforeAll(async () => { + main = await grow(await genesisChain(), 10); + genesis = await main.blocks[0].hash(); +}); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.heights.processedProposedBlockHeight = 0; + mocks.sweep = false; +}); + +const chainOver = ( + nodes: FakeNode[], + send: () => Promise = () => Promise.resolve(), +) => { + const sent: number[] = []; + const store = memoryStore(genesis, () => true, 20); + const source = new StickySource({ + store, + legacyProvenHeight: () => Promise.resolve(0), + nodes: () => nodes.map((n) => n.rpc), + openReader: readerOf(nodes), + }); + const publisher = new ChainPublisher({ + rollupVersion: ROLLUP_VERSION, + store, + source, + publishBlock: async (block) => { + await send(); + sent.push(block.number); + }, + lowerProvenCursor: () => Promise.resolve(), + transaction: (fn) => fn(), + }); + return { + chain: { rollupVersion: ROLLUP_VERSION, store, source, publisher }, + sent, + }; +}; + +/** As a prune to block 0 leaves a store when its first send fails: tip 0, the hashes of blocks 1-3 kept. */ +const pruneToZero = async ( + store: ReturnType["chain"]["store"], +) => { + await store.handleBlockStreamEvent({ + type: "blocks-added", + blocks: main.blocks.slice(1, 4), + }); + const { checkpointed, proven } = await store.getL2Tips(); + await store.handleBlockStreamEvent({ + type: "chain-pruned", + block: { number: BlockNumber(0), hash: genesis.toString() }, + checkpointed, + proven, + }); +}; + +describe("block poller pass", () => { + it("starts an empty store at the elected node's finalized block", async () => { + const x = new FakeNode("x", prefix(main, 9)); + x.tiers = { checkpointed: 9, proven: 7, finalized: 6 }; + const { chain, sent } = chainOver([x]); + + await runPass(chain); + + expect(sent).toEqual([6, 7, 8, 9]); + expect((await chain.store.getL2Tips()).finalized.block.number).toBe(6); + }); + + it("starts an empty store at the finalized block of the stream's own snapshot when it lags the election's", async () => { + const x = new FakeNode("x", prefix(main, 4)); + x.tiers = { checkpointed: 4, proven: 3, finalized: 3 }; + // The election's probe reached a backend further ahead. + x.probeTipsOverride = () => + tipsOf(prefix(main, 9), { checkpointed: 9, proven: 7, finalized: 6 }); + const { chain, sent } = chainOver([x]); + + await runPass(chain); + + expect(sent).toEqual([3, 4]); + expect((await chain.store.getL2Tips()).proposed).toEqual({ + number: 4, + hash: main.hashes[4], + }); + }); + + it.each([ + { kind: "an error", error: () => new Error("broker down") }, + { kind: "an AbortError", error: () => new AbortError("broker down") }, + ])( + "fails the pass on a send that rejects with $kind, before any post-pass work, and logs it", + async ({ error }) => { + const x = new FakeNode("x", prefix(main, 3)); + const failure = error(); + let failing = false; + const { chain } = chainOver([x], () => + failing ? Promise.reject(failure) : Promise.resolve(), + ); + await runPass(chain); + // So that a pass leaving the tip where it was would write the height + // and sweep. + mocks.heights.processedProposedBlockHeight = 1; + mocks.sweep = true; + vi.clearAllMocks(); + x.chain = prefix(main, 5); + failing = true; + + await expect(runPass(chain)).rejects.toBe(failure); + + expect(mocks.publishTipsIfDue).not.toHaveBeenCalled(); + expect(runProvenSideWork).not.toHaveBeenCalled(); + expect(mocks.storeProcessedProposedBlockHeight).not.toHaveBeenCalled(); + expect(mocks.openAttestedReader).not.toHaveBeenCalled(); + expect(logger.error).not.toHaveBeenCalled(); + await pollOnce(() => Promise.resolve(chain)); + expect(logger.error).toHaveBeenCalledTimes(1); + }, + ); + + it("redacts URLs in a failed pass's log, its error's cause too, and keeps its stack frames", async () => { + const x = new FakeNode("x", prefix(main, 3)); + const { chain } = chainOver([x]); + await runPass(chain); + x.chain = prefix(main, 5); + const failure = new Error( + `Error fetching from host ${mocks.configuredUrl}: fetch failed`, + { + cause: new Error( + "connect ECONNREFUSED node.example:8443; key key456secret refused by https://user:secret@other.example/v1/key789", + ), + }, + ); + // Node prints an ES module's frames as file URLs. + failure.stack = `Error: ${failure.message}\n at read (file:///app/build/client.js:1:2)`; + // The walk-back reads block 3 first, the batch's parent check second. + let readsAt3 = 0; + x.getBlockOverride = (param) => { + const n = (param as { number: number }).number; + return n === 3 && ++readsAt3 >= 2 + ? Promise.reject(failure) + : respond(x.chain.blocks[n], false); + }; + + await pollOnce(() => Promise.resolve(chain)); + + expect(logger.error).toHaveBeenCalledTimes(1); + const [line] = logger.error.mock.calls[0] as [string]; + expect(line).toContain( + "🐻 block stream pass failed: Error: Error fetching from host : fetch failed\n at read (file:///app/build/client.js:1:2)", + ); + expect(line).toContain( + "[cause]: Error: connect ECONNREFUSED ; key refused by ", + ); + expect(line).not.toMatch(/secret|key123|key456|key789|it's|\.example|8443/); + }); + + it("publishes the snapshot's tips after a pass that reaches them, and no tips or side work after one that ends on the prefix rule", async () => { + const x = new FakeNode("x", prefix(main, 7)); + const { chain } = chainOver([x]); + + await runPass(chain); + expect(mocks.publishTipsIfDue).toHaveBeenCalledTimes(1); + expect(mocks.publishTipsIfDue.mock.calls[0][0]).toMatchObject({ + proposed: { number: 7, hash: main.hashes[7] }, + }); + expect(mocks.storeProcessedProposedBlockHeight).toHaveBeenCalledWith(7); + expect(runProvenSideWork).toHaveBeenCalledTimes(1); + const [deps] = vi.mocked(runProvenSideWork).mock.calls[0]; + expect(deps).toMatchObject({ + rollupVersion: ROLLUP_VERSION, + provenTip: 0, + finalizedTip: 0, + }); + expect(await deps.storedHash(7)).toBe(main.hashes[7]); + + x.chain = prefix(main, 5); + await runPass(chain); + expect(mocks.publishTipsIfDue).toHaveBeenCalledTimes(1); + expect(runProvenSideWork).toHaveBeenCalledTimes(1); + expect((await chain.store.getL2Tips()).proposed.number).toBe(7); + }); + + it("writes the legacy proposed height whenever it differs from the store's tip, moved or not", async () => { + const x = new FakeNode("x", prefix(main, 7)); + const { chain } = chainOver([x]); + await runPass(chain); + await runPass(chain); + expect(mocks.storeProcessedProposedBlockHeight.mock.calls).toEqual([[7]]); + + // As a pass that failed after storing blocks leaves it. + mocks.heights.processedProposedBlockHeight = 5; + await runPass(chain); + + expect(mocks.storeProcessedProposedBlockHeight.mock.calls).toEqual([ + [7], + [7], + ]); + }); + + it.each([ + { pass: "elects no node", nodes: () => [] }, + { + pass: "follows a node at block 0", + nodes: () => [new FakeNode("x", prefix(main, 0))], + }, + ])( + "keeps the legacy proposed height after a pass that $pass, which leaves the store empty", + async ({ nodes }) => { + const { chain } = chainOver(nodes()); + mocks.heights.processedProposedBlockHeight = 5; + + await runPass(chain); + + expect((await chain.store.getL2Tips()).proposed.number).toBe(0); + expect(mocks.storeProcessedProposedBlockHeight).not.toHaveBeenCalled(); + }, + ); + + it("starts a store pruned to block 0 from block 1, not from the snapshot's finalized block", async () => { + const x = new FakeNode("x", await grow(prefix(main, 0), 9)); + x.tiers = { checkpointed: 9, proven: 6, finalized: 6 }; + const { chain, sent } = chainOver([x]); + await pruneToZero(chain.store); + + await runPass(chain); + + expect(sent).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]); + }); + + it("writes a tip of 0 over the legacy proposed height after a prune to block 0, as the store still holds blocks", async () => { + const { chain } = chainOver([]); + await pruneToZero(chain.store); + mocks.heights.processedProposedBlockHeight = 5; + + await runPass(chain); + + expect(mocks.storeProcessedProposedBlockHeight.mock.calls).toEqual([[0]]); + }); + + it("starts a new store, from the reporting node's block 0, when node info reports a new rollup version", async () => { + const [a, b] = [new FakeNode("a", main), new FakeNode("b", main)]; + mocks.readLatestRollupVersion + .mockResolvedValueOnce({ node: a.rpc, version: 1 }) + .mockResolvedValueOnce(undefined) + .mockResolvedValueOnce({ node: b.rpc, version: 2 }); + mocks.readGenesisBlockHash.mockImplementation( + ({ name }: { name: string }) => Promise.resolve(`block 0 of ${name}`), + ); + + const first = await currentChain(0); + // No read within the interval, and a read no node answers keeps the version. + expect(await currentChain(CHAIN_INFO_POLL_INTERVAL_MS - 1)).toBe(first); + expect(await currentChain(CHAIN_INFO_POLL_INTERVAL_MS)).toBe(first); + const second = await currentChain(2 * CHAIN_INFO_POLL_INTERVAL_MS); + + expect(mocks.readLatestRollupVersion).toHaveBeenCalledTimes(3); + expect(mocks.stores).toEqual([ + { version: 1, genesis: "block 0 of a" }, + { version: 2, genesis: "block 0 of b" }, + ]); + expect(second.rollupVersion).toBe(2); + expect(streamRollupVersion()).toBe(2); + }); +}); diff --git a/services/aztec-listener/tests/unit/block-processing.test.ts b/services/aztec-listener/tests/unit/block-processing.test.ts index e6139b26d..825fd9129 100644 --- a/services/aztec-listener/tests/unit/block-processing.test.ts +++ b/services/aztec-listener/tests/unit/block-processing.test.ts @@ -1,6 +1,3 @@ -// Tests for the actual onBlock function -// Tests the real implementation with mocked dependencies - import { describe, it, expect, vi, beforeEach } from "vitest"; import { mockTxsController, @@ -18,6 +15,7 @@ vi.mock("../../src/svcs/database/index.js", () => ({ vi.mock("../../src/svcs/message-bus/index.js", () => ({ publishMessage: mockMessageBus.publishMessage, + publishKeyedMessage: mockMessageBus.publishKeyedMessage, })); vi.mock("../../src/logger.js", () => ({ @@ -25,168 +23,40 @@ vi.mock("../../src/logger.js", () => ({ })); // Import the actual function after setting up mocks -import { onBlock } from "../../src/events/emitted/index.js"; +import { onOrderedBlock } from "../../src/events/emitted/index.js"; -describe("onBlock Function", () => { +describe("onOrderedBlock", () => { beforeEach(() => { resetAllMocks(); - vi.clearAllTimers(); }); - it("should promote pending transactions to proposed when found in proposed block", async () => { - // Setup: Block with transactions, pending transactions in DB - const mockBlock = createMockL2Block(100, ["tx-1", "tx-2"]); - const storedTxs = [ + it("sends the block under the network's key with its pass's tip, and promotes its pending txs to proposed", async () => { + mockTxsController.getTxs.mockResolvedValue([ createMockDbTx("tx-1", "pending"), - createMockDbTx("tx-2", "suspected_dropped"), - createMockDbTx("tx-3", "pending"), // Not in block - ]; - - mockTxsController.getTxs.mockResolvedValue(storedTxs); - mockTxsController.storeOrUpdate.mockResolvedValue(undefined); - mockMessageBus.publishMessage.mockResolvedValue(undefined); + createMockDbTx("tx-3", "suspected_dropped"), + ]); - // Execute with proposed block - await onBlock( + await onOrderedBlock( // @ts-expect-error - Mock object doesn't implement full L2Block interface - mockBlock, - "proposed", + createMockL2Block(100, ["tx-1", "tx-2"]), + 104, ); - // Verify: NEW_BLOCK_EVENT published - expect(mockMessageBus.publishMessage).toHaveBeenCalledWith( + expect(mockMessageBus.publishKeyedMessage).toHaveBeenCalledWith( "NEW_BLOCK_EVENT", - expect.objectContaining({ - blockNumber: 100, + "SANDBOX", + { + block: Buffer.from("mock-block-100").toString("hex"), statusHint: "proposed", - }), + blockNumber: 100, + ordered: { proposedTip: 104 }, + }, ); - - // Verify: Transactions found in block promoted to "proposed" + expect(mockMessageBus.publishMessage).not.toHaveBeenCalled(); + expect(mockTxsController.storeOrUpdate).toHaveBeenCalledTimes(1); expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( expect.objectContaining({ txHash: "tx-1" }), "proposed", ); - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( - expect.objectContaining({ txHash: "tx-2" }), - "proposed", - ); - - // Verify: Transaction not in block is not updated - expect(mockTxsController.storeOrUpdate).not.toHaveBeenCalledWith( - expect.objectContaining({ txHash: "tx-3" }), - expect.any(String), - ); - }); - - it("should promote transactions to proven when found in proven block", async () => { - // Setup: Block with transactions, suspected_dropped transactions in DB - const mockBlock = createMockL2Block(101, [ - "recovered-tx-1", - "recovered-tx-2", - ]); - const storedTxs = [ - createMockDbTx("recovered-tx-1", "suspected_dropped"), - createMockDbTx("recovered-tx-2", "pending"), - createMockDbTx("still-missing", "suspected_dropped"), - ]; - - mockTxsController.getTxs.mockResolvedValue(storedTxs); - mockTxsController.storeOrUpdate.mockResolvedValue(undefined); - mockMessageBus.publishMessage.mockResolvedValue(undefined); - - // Execute with proven block - await onBlock( - // @ts-expect-error - Mock object doesn't implement full L2Block interface - mockBlock, - "proven", - ); - - // Verify: Transactions found in block promoted to "proven" - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( - expect.objectContaining({ txHash: "recovered-tx-1" }), - "proven", - ); - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( - expect.objectContaining({ txHash: "recovered-tx-2" }), - "proven", - ); - - // Verify: Transaction not in block remains unchanged - expect(mockTxsController.storeOrUpdate).not.toHaveBeenCalledWith( - expect.objectContaining({ txHash: "still-missing" }), - expect.any(String), - ); - }); - - it("should handle empty blocks correctly", async () => { - // Setup: Empty block, transactions in DB - const mockBlock = createMockL2Block(102, []); // No transactions - const storedTxs = [ - createMockDbTx("tx-1", "pending"), - createMockDbTx("tx-2", "suspected_dropped"), - ]; - - mockTxsController.getTxs.mockResolvedValue(storedTxs); - mockTxsController.storeOrUpdate.mockResolvedValue(undefined); - mockMessageBus.publishMessage.mockResolvedValue(undefined); - - // Execute - await onBlock( - // @ts-expect-error - Mock object doesn't implement full L2Block interface - mockBlock, - "proposed", - ); - - // Verify: Block event published - expect(mockMessageBus.publishMessage).toHaveBeenCalledWith( - "NEW_BLOCK_EVENT", - expect.any(Object), - ); - - // Verify: No transactions updated (empty block) - expect(mockTxsController.storeOrUpdate).not.toHaveBeenCalled(); - }); - - it("should only check pending and suspected_dropped transactions", async () => { - // Setup: Block with transactions, but only return pending/suspected_dropped from DB - const mockBlock = createMockL2Block(103, ["tx-1", "tx-2", "tx-3"]); - - // The function only queries for pending and suspected_dropped, so only return those - const queriedTxs = [ - createMockDbTx("tx-1", "pending"), - createMockDbTx("tx-2", "suspected_dropped"), - // tx-3 is proven/dropped, so won't be returned by the query - ]; - - mockTxsController.getTxs.mockResolvedValue(queriedTxs); - mockTxsController.storeOrUpdate.mockResolvedValue(undefined); - mockMessageBus.publishMessage.mockResolvedValue(undefined); - - // Execute - await onBlock( - // @ts-expect-error - Mock object doesn't implement full L2Block interface - mockBlock, - "proven", - ); - - // Verify: Only pending and suspected_dropped are queried - expect(mockTxsController.getTxs).toHaveBeenCalledWith([ - "pending", - "suspected_dropped", - ]); - - // Verify: Only the queried transactions that are in the block are updated - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( - expect.objectContaining({ txHash: "tx-1" }), - "proven", - ); - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( - expect.objectContaining({ txHash: "tx-2" }), - "proven", - ); - - // Verify: Only 2 transactions were updated (the ones returned by the query) - expect(mockTxsController.storeOrUpdate).toHaveBeenCalledTimes(2); }); }); diff --git a/services/aztec-listener/tests/unit/block-stream-source.test.ts b/services/aztec-listener/tests/unit/block-stream-source.test.ts index 86661ef0b..9986e94cd 100644 --- a/services/aztec-listener/tests/unit/block-stream-source.test.ts +++ b/services/aztec-listener/tests/unit/block-stream-source.test.ts @@ -1,34 +1,37 @@ import { createServer, type ServerResponse } from "node:http"; import { type AddressInfo } from "node:net"; -import { - BlockNumber, - CheckpointNumber, -} from "@aztec-labs/foundation/branded-types"; -import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { AbortError, TimeoutError } from "@aztec-labs/foundation/error"; import { type AztecNode } from "@aztec-labs/aztec.js/node"; import { type BlockHash, - type BlockParameter, L2Block, type L2BlockStreamEventHandler, type L2BlockStreamLocalDataProvider, L2BlockStream, - type L2Tips, - L2TipsMemoryStore, } from "@aztec-labs/stdlib/block"; -import { type BlockResponse } from "@aztec-labs/stdlib/interfaces/client"; import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { NodeCheckError, StickySource, readGenesisBlockHash, } from "../../src/svcs/poller/network-client/block-stream-source.js"; -import { - type OpenElectionReader, - boundedElectionReaders, -} from "../../src/svcs/poller/network-client/election-probe.js"; +import { boundedElectionReaders } from "../../src/svcs/poller/network-client/election-probe.js"; import { type RpcNode } from "../../src/svcs/poller/network-client/pool.js"; +import { + type Chain, + FakeNode, + blocksFrom, + checkpointHash, + genesisChain, + grow, + memoryStore, + pastDeadline, + prefix, + readerOf, + respond, + tipsOf, +} from "./support/chain.js"; const logger = vi.hoisted(() => ({ info: vi.fn(), @@ -44,198 +47,13 @@ vi.mock("../../src/events/emitted/index.js", () => ({ onL2RpcNodeInfo: vi.fn(), })); -type Chain = { blocks: L2Block[]; hashes: string[] }; - -// An empty body's tx effects root is zero, so these blocks pass the body check. -const emptyBlock = (n: number) => - L2Block.random(BlockNumber(n), { - txsPerBlock: 0, - txEffectsTreeRoot: Fr.ZERO, - }); - -const grow = async (chain: Chain, to: number): Promise => { - const blocks = [...chain.blocks]; - for (let n = blocks.length; n <= to; n++) { - blocks.push(await emptyBlock(n)); - } - const hashes = await Promise.all( - blocks.map(async (b) => (await b.hash()).toString()), - ); - return { blocks, hashes }; -}; - -const prefix = (chain: Chain, to: number): Chain => ({ - blocks: chain.blocks.slice(0, to + 1), - hashes: chain.hashes.slice(0, to + 1), -}); - -const respond = async ( - block: L2Block, - withBody: boolean, -): Promise => ({ - header: block.header, - archive: block.archive, - hash: await block.hash(), - checkpointNumber: block.checkpointNumber, - indexWithinCheckpoint: block.indexWithinCheckpoint, - number: block.number, - ...(withBody ? { body: block.body } : {}), -}); - -const blocksFrom = (chain: Chain, heights: number[]) => - Promise.all(heights.map((n) => respond(chain.blocks[n], true))); - -const checkpointHash = (n: number) => `0x${n.toString(16).padStart(64, "0")}`; - -/** The parts of an Aztec node the stream source and the election read. */ -class FakeNode { - readonly rpc: RpcNode; - tiers = { checkpointed: 0, proven: 0, finalized: 0 }; - unreachable = false; - probes = 0; - headerReads = 0; - readonly calls: string[] = []; - /** Answers the pass's tips reads only; the election's probe still sees `tips()`. */ - chainTipsOverride?: () => L2Tips | undefined; - /** Answers the election's probe only. */ - probeTipsOverride?: () => L2Tips; - getBlocksOverride?: ( - from: number, - limit: number, - ) => Promise; - getBlockOverride?: ( - param: BlockParameter, - ) => Promise; - - constructor( - name: string, - public chain: Chain, - ) { - this.rpc = { - name, - url: `http://${name}.invalid`, - instance: this as unknown as AztecNode, - }; - } - - get tip() { - return this.chain.blocks.length - 1; - } - - tips(): L2Tips { - const id = (n: number) => ({ - number: BlockNumber(n), - hash: this.chain.hashes[n], - }); - const tier = (n: number) => ({ - block: id(n), - checkpoint: { number: CheckpointNumber(n), hash: checkpointHash(n) }, - }); - return { - proposed: id(this.tip), - checkpointed: tier(this.tiers.checkpointed), - proven: tier(this.tiers.proven), - finalized: tier(this.tiers.finalized), - }; - } - - getChainTips() { - this.calls.push("getChainTips"); - return Promise.resolve( - this.chainTipsOverride === undefined - ? this.tips() - : this.chainTipsOverride(), - ); - } - - getBlock(param: BlockParameter): Promise { - this.calls.push("getBlock"); - if (this.getBlockOverride !== undefined) { - return this.getBlockOverride(param); - } - const height = - typeof param === "number" - ? param - : typeof param === "object" && "number" in param - ? param.number - : typeof param === "object" && "hash" in param - ? this.chain.hashes.indexOf(param.hash.toString()) - : -1; - if (height < 0 || height > this.tip) { - return Promise.resolve(undefined); - } - return respond(this.chain.blocks[height], false); - } - - getBlocks(from: number, limit: number): Promise { - this.calls.push("getBlocks"); - if (this.getBlocksOverride !== undefined) { - return this.getBlocksOverride(from, limit); - } - return Promise.all( - this.chain.blocks - .slice(from, from + limit) - .map((block) => respond(block, true)), - ); - } -} - -const tipsOf = (chain: Chain, tiers: FakeNode["tiers"]) => { - const view = new FakeNode("view", chain); - view.tiers = tiers; - return view.tips(); -}; - -/** Runs `work` while `node`'s next block range hangs, until the pinned read's deadline ends it. */ -const pastDeadline = async (node: FakeNode, work: () => Promise) => { - let reached: () => void = () => undefined; - const hanging = new Promise((resolve) => { - reached = resolve; - }); - node.getBlocksOverride = () => { - reached(); - return new Promise(() => undefined); - }; - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - try { - const running = work(); - await hanging; - await vi.advanceTimersByTimeAsync(60_000); - return await running; - } finally { - vi.useRealTimers(); - } -}; - -const readerOf = - (fakes: FakeNode[]): OpenElectionReader => - (node) => { - const fake = fakes.find((f) => f.rpc.url === node.url); - if (fake === undefined) { - throw new Error(`no fake node ${node.name}`); - } - return { - getChainTips: () => { - fake.probes++; - return fake.unreachable - ? Promise.reject(new Error("connection refused")) - : Promise.resolve(fake.probeTipsOverride?.() ?? fake.tips()); - }, - getBlockHash: (n) => { - fake.headerReads++; - return Promise.resolve(fake.chain.hashes.at(n)); - }, - }; - }; - let genesis: BlockHash; let base: Chain; let main: Chain; beforeAll(async () => { - const block0 = await emptyBlock(0); - genesis = await block0.hash(); - base = { blocks: [block0], hashes: [genesis.toString()] }; + base = await genesisChain(); + genesis = await base.blocks[0].hash(); main = await grow(base, 20); }); @@ -253,22 +71,6 @@ type Setup = { type Pass = () => Promise; -/** The SDK's memory store with the Postgres store's two extra reads. */ -const testStore = (otherVersionStored: () => boolean) => { - const memory = new L2TipsMemoryStore(genesis); - return Object.assign(memory, { - otherVersionStored: () => Promise.resolve(otherVersionStored()), - holdsHashAtOrAbove: async (height: number) => { - for (let n = Math.max(height, 1); n < main.blocks.length; n++) { - if ((await memory.getL2BlockHash(BlockNumber(n))) !== undefined) { - return true; - } - } - return false; - }, - }); -}; - const setup = ({ nodes, online = nodes, @@ -276,7 +78,7 @@ const setup = ({ legacyProvenHeight = 0, otherVersionStored = () => true, }: Setup) => { - const store = testStore(otherVersionStored); + const store = memoryStore(genesis, otherVersionStored, 20); const clock = { now: 1_000_000 }; const world = { online }; /** A source over the same store, as after a restart. */ @@ -582,7 +384,7 @@ describe("StickySource election", () => { instance: {} as AztecNode, })); const source = new StickySource({ - store: testStore(() => true), + store: memoryStore(genesis, () => true, 20), legacyProvenHeight: () => Promise.resolve(0), nodes: () => [slow, big, good], openReader: boundedElectionReaders(300), @@ -738,6 +540,34 @@ describe("StickySource passes", () => { expect(await store.getL2Tips()).toEqual(synced); }); + it("never elects a node with tips out of order, and skips a pass whose snapshot has them before any block read", async () => { + const x = finalizedAtFour(); + const { store, source, pass } = setup({ nodes: [x] }); + await pass(); + const synced = await store.getL2Tips(); + x.chain = prefix(main, 9); + const disordered = () => + tipsOf(x.chain, { checkpointed: 9, proven: 5, finalized: 6 }); + + x.probeTipsOverride = disordered; + expect(await source.elect()).toBeUndefined(); + + x.probeTipsOverride = undefined; + x.tiers = { checkpointed: 9, proven: 6, finalized: 6 }; + x.chainTipsOverride = disordered; + x.calls.length = 0; + expect(await pass()).toBe(x.rpc); + + expect(x.calls).toEqual(["getChainTips"]); + expect(await store.getL2Tips()).toEqual(synced); + expect( + logged( + logger.warn, + "has tips out of order: proposed 9, checkpointed 9, proven 5, finalized 6", + ), + ).toBe(2); + }); + it("follows the node with the replacing block within three passes while two tied nodes have only a shorter copy, and lets a tied node back once its tip changes", async () => { const a = new FakeNode("a", prefix(main, 6)); const b = new FakeNode("b", prefix(main, 6)); @@ -751,7 +581,7 @@ describe("StickySource passes", () => { event.type === "chain-pruned" && event.block.number === source.lastTips?.proposed.number ) { - source.endPassOnPrefix(); + source.benchPinnedUntilNewTip(); throw new AbortError(); } await store.handleBlockStreamEvent(event); @@ -1018,6 +848,21 @@ describe("StickySource passes", () => { expect((await store.getL2Tips()).proposed.number).toBe(8); }); + it("sets a node aside and alerts when its pass serves another block 0 than the store's genesis block", async () => { + const x = new FakeNode("x", prefix(main, 4)); + x.servedChain = await grow(await genesisChain(), 4); + const { store, source, pass } = setup({ nodes: [x] }); + + expect(await pass()).toBe(x.rpc); + + expect(source.lastError).toBeInstanceOf(NodeCheckError); + expect(logger.error).toHaveBeenCalledWith( + "Node x has another genesis block than the block stream's", + ); + expect((await store.getL2Tips()).proposed.number).toBe(0); + expect(await source.elect()).toBeUndefined(); + }); + it("reads the genesis hash from block 0, and stops when a node does not serve it", async () => { const x = new FakeNode("x", prefix(main, 2)); expect((await readGenesisBlockHash(x.rpc)).toString()).toBe( diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts new file mode 100644 index 000000000..b643dc1f3 --- /dev/null +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -0,0 +1,582 @@ +import { + BlockNumber, + CheckpointNumber, +} from "@aztec-labs/foundation/branded-types"; +import { + type BlockHash, + type L2Block, + L2BlockStream, +} from "@aztec-labs/stdlib/block"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { StickySource } from "../../src/svcs/poller/network-client/block-stream-source.js"; +import { ChainPublisher } from "../../src/svcs/poller/pollers/block_poller/chain-publisher.js"; +import { + type Chain, + FakeNode, + ROLLUP_VERSION, + blocksFrom, + chainOf, + checkpointHash, + emptyBlock, + genesisChain, + grow, + memoryStore, + prefix, + readerOf, + respond, + tipsOf, +} from "./support/chain.js"; + +const logger = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), +})); +vi.mock("../../src/logger.js", () => ({ logger })); +vi.mock("../../src/events/emitted/index.js", () => ({ + onChainInfo: vi.fn(), + onL2RpcNodeAlive: vi.fn(), + onL2RpcNodeError: vi.fn(), + onL2RpcNodeInfo: vi.fn(), +})); + +let genesis: BlockHash; +let base: Chain; +let main: Chain; + +beforeAll(async () => { + base = await genesisChain(); + genesis = await base.blocks[0].hash(); + main = await grow(base, 20); +}); + +beforeEach(() => { + vi.clearAllMocks(); +}); + +type Sent = { block: number; hash: string; tip: number }; + +const setup = ({ + nodes, + online = nodes, + maxPruneDepth = 10, +}: { + nodes: FakeNode[]; + online?: FakeNode[]; + maxPruneDepth?: number; +}) => { + const store = memoryStore(genesis, () => true, 20); + const clock = { now: 1_000_000 }; + const world = { online }; + const source = new StickySource( + { + store, + legacyProvenHeight: () => Promise.resolve(0), + nodes: () => world.online.map((f) => f.rpc), + openReader: readerOf(nodes), + now: () => clock.now, + }, + { maxPruneDepth, waitAlertMs: 60_000 }, + ); + const sent: Sent[] = []; + const lowered: number[] = []; + const failing = new Set(); + const publisher = new ChainPublisher( + { + rollupVersion: ROLLUP_VERSION, + store, + source, + publishBlock: async (block: L2Block, tip: number) => { + if (failing.delete(block.number)) { + throw new Error("send rejected"); + } + sent.push({ + block: block.number, + hash: (await block.hash()).toString(), + tip, + }); + }, + lowerProvenCursor: (height) => { + lowered.push(height); + return Promise.resolve(); + }, + transaction: (fn) => fn(), + now: () => clock.now, + }, + { maxPruneDepth, prefixAlertMs: 60_000 }, + ); + /** One listener pass: the election, then the stream when a node is pinned. */ + const pass = async (startingBlock?: number) => { + const pinned = await source.elect(); + if (pinned !== undefined) { + publisher.startPass(); + await new L2BlockStream(source, source.localData, publisher, undefined, { + batchSize: 10, + startingBlock, + }).sync(); + publisher.finishPass(); + } + return pinned; + }; + const head = async () => (await store.getL2Tips()).proposed; + return { store, source, clock, world, sent, lowered, failing, pass, head }; +}; + +const sentOf = (chain: Chain, heights: number[], tip: number): Sent[] => + heights.map((n) => ({ block: n, hash: chain.hashes[n], tip })); + +const loggedTimes = (log: typeof logger.warn, text: string) => + log.mock.calls.filter(([message]) => String(message).includes(text)).length; + +describe("ChainPublisher after the node replaces published heights", () => { + // The node drops heights 6-7 of the stored chain and serves chain `b` from 6. + it.each([ + { + regrowth: "to 6, then to 7 on the next pass", + tips: [6, 7], + expected: [ + [[6], 6], + [[7], 7], + ] as [number[], number][], + }, + { + regrowth: "to 8, past the stored tip", + tips: [8], + expected: [[[6, 7, 8], 8]] as [number[], number][], + }, + { + regrowth: "to 7, the stored tip's height", + tips: [7], + expected: [[[6, 7], 7]] as [number[], number][], + }, + ])( + "publishes the replacing blocks, each with its pass's tip, when the chain regrows $regrowth", + async ({ tips, expected }) => { + const x = new FakeNode("x", prefix(main, 7)); + const { sent, lowered, pass, head } = setup({ nodes: [x] }); + await pass(); + sent.length = 0; + const b = await grow(prefix(main, 5), 8); + + for (const tip of tips) { + x.chain = prefix(b, tip); + await pass(); + } + + expect(sent).toEqual( + expected.flatMap(([heights, tip]) => sentOf(b, heights, tip)), + ); + expect(lowered).toEqual([5]); + const top = tips[tips.length - 1]; + expect(await head()).toEqual({ number: top, hash: b.hashes[top] }); + }, + ); + + it.each([ + { + change: "drops blocks 8-10", + next: () => Promise.resolve(prefix(main, 7)), + }, + { change: "replaces block 10", next: () => grow(prefix(main, 9), 10) }, + ])( + "sends and stores no batch of a pass whose tip the node no longer holds, after it $change", + async ({ next }) => { + const x = new FakeNode("x", prefix(main, 5)); + const { store, sent, pass } = setup({ nodes: [x] }); + await pass(); + sent.length = 0; + const before = await store.getL2Tips(); + const after = await next(); + // The node answers the pass's tips read at block 10, then changes. + x.chain = prefix(main, 10); + x.chainTipsOverride = () => { + const tips = x.tips(); + x.chain = after; + return tips; + }; + + expect(await pass()).toBe(x.rpc); + + expect(sent).toEqual([]); + expect(await store.getL2Tips()).toEqual(before); + expect( + loggedTimes(logger.warn, "no longer holds this pass's proposed tip 10"), + ).toBe(1); + expect(loggedTimes(logger.warn, "sits out the block stream")).toBe(0); + }, + ); + + it("elects another node within the pin's lead once the pinned node's tips name a block it does not serve", async () => { + const x = new FakeNode("x", prefix(main, 5)); + const y = new FakeNode("y", prefix(main, 5)); + const { pass } = setup({ nodes: [x, y] }); + await pass(); + // Its tips name block 10 of `main`; its block reads serve another block 10. + x.chain = prefix(main, 10); + x.servedChain = await grow(prefix(main, 9), 10); + y.chain = prefix(main, 11); + + expect(await pass()).toBe(x.rpc); + expect(await pass()).toBe(y.rpc); + }); + + it.each([ + { + serving: "another block at its tip", + served: (tip: number) => grow(prefix(main, 9), tip), + }, + { + serving: "no block above 7", + served: () => Promise.resolve(prefix(main, 7)), + }, + ])( + "keeps a node serving $serving out of the next election once its tip moves ahead, and the pin then stays on the node elected instead", + async ({ served }) => { + const x = new FakeNode("x", prefix(main, 5)); + const y = new FakeNode("y", prefix(main, 5)); + const { pass } = setup({ nodes: [x, y] }); + await pass(); + x.chain = prefix(main, 10); + x.servedChain = await served(10); + y.chain = prefix(main, 11); + expect(await pass()).toBe(x.rpc); + + x.chain = prefix(main, 12); + x.servedChain = await served(12); + expect(await pass()).toBe(y.rpc); + expect(await pass()).toBe(y.rpc); + }, + ); + + it("sends a pass longer than one batch whole, each block with the pass's tip", async () => { + const x = new FakeNode("x", prefix(main, 5)); + const { sent, pass, head } = setup({ nodes: [x] }); + await pass(); + sent.length = 0; + x.chain = prefix(main, 20); + + await pass(); + + const heights = Array.from({ length: 15 }, (_, i) => 6 + i); + expect(sent).toEqual(sentOf(main, heights, 20)); + expect(await head()).toEqual({ number: 20, hash: main.hashes[20] }); + }); + + it("stores no block of a batch with a failed send, and the next pass sends the whole batch again with its own tip", async () => { + const x = new FakeNode("x", prefix(main, 5)); + const { sent, failing, pass, head } = setup({ nodes: [x] }); + await pass(); + sent.length = 0; + x.chain = prefix(main, 9); + + failing.add(8); + await expect(pass()).rejects.toThrow("send rejected"); + expect(sent).toEqual(sentOf(main, [6, 7], 9)); + expect(await head()).toEqual({ number: 5, hash: main.hashes[5] }); + + // The node dropped blocks 8-9 since. + x.chain = prefix(main, 7); + await pass(); + expect(sent).toEqual([ + ...sentOf(main, [6, 7], 9), + ...sentOf(main, [6, 7], 7), + ]); + expect(await head()).toEqual({ number: 7, hash: main.hashes[7] }); + }); +}); + +describe("ChainPublisher checks", () => { + it("ends the pass on a node with only a shorter copy of the stored chain, unpins it, and alerts while every pass does", async () => { + const x = new FakeNode("x", prefix(main, 7)); + const { source, clock, sent, lowered, pass, head } = setup({ nodes: [x] }); + await pass(); + sent.length = 0; + x.chain = prefix(main, 5); + const waiting = "waits for a node at or past its tip"; + + expect(await pass()).toBe(x.rpc); + expect(source.pinned).toBeUndefined(); + clock.now += 60_000; + await pass(); + await pass(); + + expect(sent).toEqual([]); + expect(lowered).toEqual([]); + expect(await head()).toEqual({ number: 7, hash: main.hashes[7] }); + expect(loggedTimes(logger.warn, waiting)).toBe(1); + expect(loggedTimes(logger.error, waiting)).toBe(1); + + // A pass that does not end on the rule ends the wait. + x.chain = prefix(main, 7); + await pass(); + x.chain = prefix(main, 5); + await pass(); + expect(loggedTimes(logger.warn, waiting)).toBe(2); + }); + + it("stores nothing and moves no cursor on a prune deeper than the guard", async () => { + const x = new FakeNode("x", prefix(main, 8)); + const { sent, lowered, pass, head } = setup({ + nodes: [x], + maxPruneDepth: 2, + }); + await pass(); + sent.length = 0; + // Depth 3: one past the guard, and within the walk bound. + x.chain = await grow(prefix(main, 5), 9); + + await pass(); + + expect(sent).toEqual([]); + expect(lowered).toEqual([]); + expect(await head()).toEqual({ number: 8, hash: main.hashes[8] }); + expect(loggedTimes(logger.error, "past AZTEC_MAX_PRUNE_DEPTH 2")).toBe(1); + }); + + it.each([ + { + fault: "sends a batch with a broken link", + reason: "sent block 8, which does not extend block 7", + arrange: async (x: FakeNode) => { + x.chain = await chainOf([ + ...main.blocks.slice(0, 8), + await emptyBlock(8), + ]); + }, + }, + { + fault: "sends a batch unlinked to the store", + reason: "sent block 7, which does not extend block 6", + arrange: async (x: FakeNode) => { + const fork = await grow(prefix(main, 5), 9); + x.chain = prefix(main, 9); + x.getBlocksOverride = (from, limit) => + blocksFrom( + fork, + [...Array(limit).keys()].map((i) => from + i), + ); + }, + }, + { + fault: "changes the block below a batch", + reason: "has another block 6 than the one the block stream stored", + arrange: async (x: FakeNode) => { + const fork = await grow(prefix(main, 5), 6); + x.chain = prefix(main, 9); + // The walk-back reads block 6 first, the batch's parent check second. + let readsAt6 = 0; + x.getBlockOverride = (param) => { + const n = (param as { number: number }).number; + const served = n === 6 && ++readsAt6 === 2 ? fork : main; + return respond(served.blocks[n], false); + }; + }, + }, + { + fault: "sends a block of another rollup version", + reason: `sent block 7 of rollup version ${ROLLUP_VERSION + 1}`, + arrange: async (x: FakeNode) => { + x.chain = await chainOf([ + ...main.blocks.slice(0, 7), + await emptyBlock(7, main.blocks[6], ROLLUP_VERSION + 1), + ]); + }, + }, + { + fault: "forks below the stored finalized tip", + reason: "asks to prune to block 6", + arrange: async (x: FakeNode, pass: () => Promise) => { + x.chain = prefix(main, 8); + await pass(); + // Its probe shows the stored chain; its pass serves a fork from block 5. + const fork = await grow(prefix(main, 4), 9); + x.chain = prefix(main, 9); + x.servedChain = fork; + x.chainTipsOverride = () => ({ + ...tipsOf(fork, { checkpointed: 6, proven: 6, finalized: 6 }), + finalized: x.tips().finalized, + }); + }, + }, + ])( + "publishes nothing and sets the node aside when it $fault", + async ({ reason, arrange }) => { + const x = new FakeNode("x", prefix(main, 6)); + x.tiers = { checkpointed: 6, proven: 6, finalized: 6 }; + const y = new FakeNode("y", prefix(main, 6)); + y.tiers = x.tiers; + const { store, world, sent, lowered, pass } = setup({ + nodes: [x, y], + online: [x], + }); + await pass(); + await arrange(x, pass); + sent.length = 0; + const before = await store.getL2Tips(); + + expect(await pass()).toBe(x.rpc); + expect(sent).toEqual([]); + expect(lowered).toEqual([]); + expect(await store.getL2Tips()).toEqual(before); + world.online = [x, y]; + expect(await pass()).toBe(y.rpc); + expect(loggedTimes(logger.warn, "sits out the block stream")).toBe(1); + expect(loggedTimes(logger.warn, reason)).toBe(1); + }, + ); + + it.each([ + { held: "no hash", hold: () => Promise.resolve() }, + { + held: "a tier's hash", + // As a prune to block 0 leaves it when its first send fails. + hold: (store: ReturnType["store"]) => + store.handleBlockStreamEvent({ + type: "chain-checkpointed", + block: { number: BlockNumber(4), hash: main.hashes[4] }, + checkpoint: { number: CheckpointNumber(4), hash: checkpointHash(4) }, + }), + }, + ])( + "stores no proposed tip that the pass did not send, at a height where the store holds $held", + async ({ hold }) => { + const x = new FakeNode("x", prefix(main, 4)); + x.tiers = { checkpointed: 4, proven: 4, finalized: 4 }; + const { store, sent, pass, head } = setup({ nodes: [x] }); + await hold(store); + + // Past the node's tip: the stream downloads nothing and reports the tip. + expect(await pass(6)).toBe(x.rpc); + + expect(sent).toEqual([]); + expect(await head()).toEqual({ number: 0, hash: genesis.toString() }); + expect(loggedTimes(logger.warn, "which this pass did not send")).toBe(1); + }, + ); + + it("refuses a prune to block 0 through heights the store holds no hash for", async () => { + const x = new FakeNode("x", await grow(base, 12)); + const { store, sent, lowered, pass } = setup({ nodes: [x] }); + // A first pass from block 10 that stopped before its tier events. + await store.handleBlockStreamEvent({ + type: "blocks-added", + blocks: main.blocks.slice(10, 12), + }); + const before = await store.getL2Tips(); + + expect(await pass()).toBe(x.rpc); + + expect(sent).toEqual([]); + expect(lowered).toEqual([]); + expect(await store.getL2Tips()).toEqual(before); + expect(loggedTimes(logger.error, "asks to prune to block 0")).toBe(1); + }); + + it("stores no tier from a snapshot with a proven tip off the stored chain, sets the node aside, and follows an honest node", async () => { + const honest = new FakeNode("honest", prefix(main, 6)); + honest.tiers = { checkpointed: 6, proven: 4, finalized: 4 }; + const faulty = new FakeNode("faulty", prefix(main, 10)); + faulty.tiers = { checkpointed: 10, proven: 6, finalized: 4 }; + faulty.chainTipsOverride = () => { + const tips = faulty.tips(); + return { + ...tips, + proven: { + ...tips.proven, + block: { number: BlockNumber(6), hash: main.hashes[5] }, + }, + }; + }; + const { store, world, pass } = setup({ + nodes: [honest, faulty], + online: [honest], + }); + await pass(); + + world.online = [faulty]; + expect(await pass()).toBe(faulty.rpc); + expect((await store.getL2Tips()).proven.block.number).toBe(4); + expect( + loggedTimes(logger.warn, "has another block at its proven height 6"), + ).toBe(1); + + honest.chain = prefix(main, 10); + honest.tiers = { checkpointed: 10, proven: 6, finalized: 4 }; + world.online = [faulty, honest]; + expect(await pass()).toBe(honest.rpc); + expect((await store.getL2Tips()).proven.block).toEqual({ + number: 6, + hash: main.hashes[6], + }); + }); + + it("stores nothing from a prune with another block as its lowered proven tip, sets the node aside, and follows an honest node", async () => { + const x = new FakeNode("x", prefix(main, 8)); + x.tiers = { checkpointed: 8, proven: 6, finalized: 4 }; + const y = new FakeNode("y", prefix(main, 8)); + y.tiers = x.tiers; + const { store, world, sent, lowered, pass } = setup({ + nodes: [x, y], + online: [x], + }); + await pass(); + sent.length = 0; + // A fork from block 5, below the stored proven tip 6 and above the stored + // finalized tip 4, with another block 4 as its proven tip. + const fork = await grow(prefix(main, 5), 9); + x.chain = fork; + x.chainTipsOverride = () => { + const tips = tipsOf(fork, { checkpointed: 9, proven: 4, finalized: 4 }); + return { + ...tips, + proven: { + ...tips.proven, + block: { ...tips.proven.block, hash: main.hashes[3] }, + }, + }; + }; + const before = await store.getL2Tips(); + + expect(await pass()).toBe(x.rpc); + expect(sent).toEqual([]); + expect(lowered).toEqual([]); + expect(await store.getL2Tips()).toEqual(before); + expect( + loggedTimes(logger.warn, "has another block at its proven height 4"), + ).toBe(1); + world.online = [x, y]; + expect(await pass()).toBe(y.rpc); + }); + + it.each([ + { + change: "a prune past a proof", + arrange: async (x: FakeNode) => { + x.chain = await grow(prefix(main, 6), 9); + x.tiers = { checkpointed: 9, proven: 5, finalized: 4 }; + }, + }, + { + change: "a proof that moves back", + arrange: (x: FakeNode) => { + x.tiers = { checkpointed: 8, proven: 5, finalized: 4 }; + return Promise.resolve(); + }, + }, + ])( + "moves the proven cursor back to the new proven tip on $change", + async ({ arrange }) => { + const x = new FakeNode("x", prefix(main, 8)); + x.tiers = { checkpointed: 8, proven: 6, finalized: 4 }; + const { store, lowered, pass } = setup({ nodes: [x] }); + await pass(); + await arrange(x); + + await pass(); + + expect(lowered).toEqual([5]); + expect((await store.getL2Tips()).proven.block.number).toBe(5); + }, + ); +}); diff --git a/services/aztec-listener/tests/unit/config-print.test.ts b/services/aztec-listener/tests/unit/config-print.test.ts new file mode 100644 index 000000000..50f08a998 --- /dev/null +++ b/services/aztec-listener/tests/unit/config-print.test.ts @@ -0,0 +1,28 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +describe("startup config print", () => { + beforeEach(() => { + vi.resetModules(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("prints each pool entry's name and its URL's origin, marking a path or query", async () => { + vi.stubEnv( + "AZTEC_RPC_URLS", + "keyed::https://operator9:pw456secret@node.example:8443/v1/key123secret?apikey=key789secret,plain::http://127.0.0.1:8080", + ); + const { getConfigStr } = await import("../../src/environment.js"); + const printed = getConfigStr(); + + expect(printed).toContain( + "Name: keyed\n URL: https://node.example:8443/…\n", + ); + expect(printed).toContain("Name: plain\n URL: http://127.0.0.1:8080\n"); + expect(printed).not.toMatch( + /operator9|pw456secret|key123secret|key789secret/, + ); + }); +}); diff --git a/services/aztec-listener/tests/unit/dev-node-error.test.ts b/services/aztec-listener/tests/unit/dev-node-error.test.ts index 3de8debff..9eb42f2bc 100644 --- a/services/aztec-listener/tests/unit/dev-node-error.test.ts +++ b/services/aztec-listener/tests/unit/dev-node-error.test.ts @@ -23,6 +23,9 @@ vi.mock("../../src/svcs/poller/network-client/index.js", () => ({ }, }), })); +vi.mock("../../src/svcs/poller/pollers/block_poller/index.js", () => ({ + init: vi.fn(), +})); describe("development start", () => { // Missing either field makes explorer-api's handler fail on every delivery. diff --git a/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts b/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts index b8736d0a6..89723c233 100644 --- a/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts +++ b/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts @@ -1,4 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type * as Environment from "../../src/environment.js"; +import { type StreamChain } from "../../src/svcs/poller/pollers/block_poller/index.js"; describe("full-sweep catchup config", () => { const originalEnv = process.env; @@ -16,7 +18,7 @@ describe("full-sweep catchup config", () => { delete process.env.AZTEC_ENABLE_FULL_SWEEP_CATCHUP; const { AZTEC_ENABLE_FULL_SWEEP_CATCHUP } = await import( - "../../src/environment.js", + "../../src/environment.js" ); expect(AZTEC_ENABLE_FULL_SWEEP_CATCHUP).toBe(false); @@ -26,113 +28,97 @@ describe("full-sweep catchup config", () => { process.env.AZTEC_ENABLE_FULL_SWEEP_CATCHUP = "true"; const { AZTEC_ENABLE_FULL_SWEEP_CATCHUP } = await import( - "../../src/environment.js", + "../../src/environment.js" ); expect(AZTEC_ENABLE_FULL_SWEEP_CATCHUP).toBe(true); }); }); -describe("block poller full-sweep behavior", () => { - const logger = { - info: vi.fn(), - warn: vi.fn(), - error: vi.fn(), - debug: vi.fn(), - }; - const getBlockHeights = vi.fn(); - const storeBlockHeights = vi.fn(); - const storeProcessedProposedBlockHeight = vi.fn(); - const storeProcessedProvenBlockHeight = vi.fn(); - const getBlock = vi.fn(); - const getLatestProposedHeight = vi.fn(); - const getLatestProvenHeight = vi.fn(); +describe("block poller full sweep", () => { + const node = { name: "pool-node", url: "http://pool-node.invalid" }; const onCatchupBlock = vi.fn(); - const onBlock = vi.fn(); - const handleProvenTransactions = vi.fn(); + const openAttestedReader = vi.fn(); + const storeProcessedProposedBlockHeight = vi.fn(); const importPoller = async (fullSweepEnabled: boolean) => { vi.resetModules(); - vi.doMock("../../src/environment.js", () => ({ + vi.doMock("../../src/environment.js", async (importOriginal) => ({ + ...(await importOriginal()), AZTEC_ENABLE_FULL_SWEEP_CATCHUP: fullSweepEnabled, - AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS: false, - AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS: false, - BLOCK_POLL_INTERVAL_MS: 60_000, - CATCHUP_POLL_WAIT_TIME_MS: 0, })); - vi.doMock("../../src/logger.js", () => ({ logger })); + vi.doMock("../../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + })); + vi.doMock("../../src/events/emitted/index.js", () => ({ + onCatchupBlock, + onOrderedBlock: vi.fn(), + })); vi.doMock("../../src/svcs/database/heights.controller.js", () => ({ - getBlockHeights, - storeBlockHeights, + getBlockHeights: () => + Promise.resolve({ processedProposedBlockHeight: 3 }), storeProcessedProposedBlockHeight, - storeProcessedProvenBlockHeight, })); - vi.doMock("../../src/svcs/poller/network-client/index.js", () => ({ - getBlock, - getLatestProposedHeight, - getLatestProvenHeight, + vi.doMock("../../src/svcs/poller/network-client/attested-reads.js", () => ({ + openAttestedReader, })); - vi.doMock("../../src/events/emitted/index.js", () => ({ - onBlock, - onCatchupBlock, + vi.doMock("../../src/svcs/poller/network-client/pool.js", () => ({ + getOnlineRpcNodes: () => [node], + getRpcNode: () => node, })); - vi.doMock( - "../../src/svcs/poller/pollers/block_poller/handle-proven-block-txs.js", - () => ({ handleProvenTransactions }), - ); - return import("../../src/svcs/poller/pollers/block_poller/index.js"); }; + // No node is eligible, so the pass reads nothing; the store's tip runs from `tips`. + const idleChain = (...tips: number[]) => + ({ + rollupVersion: 7, + store: { + getL2Tips: () => + Promise.resolve({ proposed: { number: tips.shift() ?? 3 } }), + holdsHashAtOrAbove: () => Promise.resolve(true), + }, + source: { elect: () => Promise.resolve(undefined) }, + publisher: {}, + }) as unknown as StreamChain; + beforeEach(() => { - vi.useFakeTimers(); vi.clearAllMocks(); - getLatestProposedHeight.mockResolvedValue(5); - getLatestProvenHeight.mockResolvedValue(5); - getBlockHeights.mockResolvedValue({ - processedProposedBlockHeight: 5, - processedProvenBlockHeight: 5, - chainProposedBlockHeight: 5, - chainProvenBlockHeight: 5, + // The node reader attests block 1 only. + openAttestedReader.mockResolvedValue({ + getBlock: (height: number) => + Promise.resolve({ block: { height }, finalized: height === 1 }), }); - storeBlockHeights.mockResolvedValue(undefined); - getBlock.mockResolvedValue({ number: 1 }); - onCatchupBlock.mockResolvedValue(undefined); - onBlock.mockResolvedValue(undefined); - handleProvenTransactions.mockResolvedValue(undefined); }); afterEach(() => { - vi.useRealTimers(); vi.resetModules(); }); - it("does not call full-sweep catchup when disabled", async () => { - const poller = await importPoller(false); + it("sweeps nothing when disabled", async () => { + const { runPass } = await importPoller(false); - poller.startPolling(); - await vi.waitFor(() => expect(storeBlockHeights).toHaveBeenCalled()); + await runPass(idleChain()); - expect(getBlock).not.toHaveBeenCalled(); + expect(openAttestedReader).not.toHaveBeenCalled(); expect(onCatchupBlock).not.toHaveBeenCalled(); - expect(logger.info).toHaveBeenCalledWith( - "Full-sweep catchup is disabled; request-driven reconciliation is the primary missing-block repair path.", - ); - - poller.stopPolling(); }); - it("keeps manual full-sweep catchup working when enabled", async () => { - const poller = await importPoller(true); - - poller.startPolling(); - await vi.waitFor(() => expect(onCatchupBlock).toHaveBeenCalled()); - - expect(getBlock).toHaveBeenCalledWith(1); - expect(logger.info).toHaveBeenCalledWith( - "Full-sweep catchup is enabled; listener will sweep historical blocks when live head is idle.", - ); - - poller.stopPolling(); + it("sweeps one block per pass that leaves the tip, below the store's tip, marking finalized what the node's reader attests", async () => { + const { runPass } = await importPoller(true); + + for (let pass = 0; pass < 3; pass++) { + await runPass(idleChain()); + } + await runPass(idleChain(3, 4)); + + expect(openAttestedReader).toHaveBeenCalledTimes(3); + expect(openAttestedReader).toHaveBeenCalledWith(node, 7); + expect(onCatchupBlock.mock.calls).toEqual([ + [{ height: 1 }, "proposed", { finalized: true }], + [{ height: 2 }, "proposed", {}], + [{ height: 1 }, "proposed", { finalized: true }], + ]); + expect(storeProcessedProposedBlockHeight).toHaveBeenCalledWith(4); }); }); diff --git a/services/aztec-listener/tests/unit/l2-block-range-request.test.ts b/services/aztec-listener/tests/unit/l2-block-range-request.test.ts index b78295ff9..24ef7d5c8 100644 --- a/services/aztec-listener/tests/unit/l2-block-range-request.test.ts +++ b/services/aztec-listener/tests/unit/l2-block-range-request.test.ts @@ -10,10 +10,13 @@ vi.mock("../../src/environment.js", () => ({ L2_BLOCK_RANGE_REQUEST_QUEUE_MIN_TIME_MS: 0, })); -vi.mock("../../src/events/emitted/index.js", () => ({ +const { onCatchupBlock, openAttestedReader } = vi.hoisted(() => ({ onCatchupBlock: vi.fn(), + openAttestedReader: vi.fn(), })); +vi.mock("../../src/events/emitted/index.js", () => ({ onCatchupBlock })); + vi.mock("../../src/logger.js", () => ({ logger: { info: vi.fn(), @@ -23,15 +26,21 @@ vi.mock("../../src/logger.js", () => ({ }, })); -vi.mock("../../src/svcs/poller/network-client/index.js", () => ({ - getBlock: vi.fn(), - getLatestProposedHeight: vi.fn(), - getLatestProvenHeight: vi.fn(), +vi.mock("../../src/svcs/poller/network-client/attested-reads.js", () => ({ + openAttestedReader, +})); +vi.mock("../../src/svcs/poller/network-client/pool.js", () => ({ + getRpcNode: () => ({ name: "pool-node" }), +})); +vi.mock("../../src/svcs/poller/pollers/block_poller/index.js", () => ({ + streamRollupVersion: () => 7, })); -const { clampRangeRequest, getL2BlockRangeRequestDedupKey } = await import( - "../../src/events/received/on-l2-block-range-request.js" -); +const { + clampRangeRequest, + getL2BlockRangeRequestDedupKey, + l2BlockRangeRequestHandler, +} = await import("../../src/events/received/on-l2-block-range-request.js"); describe("L2 block range request helpers", () => { it("clamps ranges to max width and chain tips", () => { @@ -96,3 +105,92 @@ describe("L2 block range request helpers", () => { expect(first).toBe("SANDBOX:cadence:1-3-proposed"); }); }); + +describe("L2 block range request", () => { + it("answers from one node, clamped to its tips, with finalized on the blocks its reader attests", async () => { + openAttestedReader.mockResolvedValue({ + tips: { proposed: { number: 3 }, proven: { block: { number: 2 } } }, + getBlock: (height: number) => + Promise.resolve({ block: { height }, finalized: height === 1 }), + }); + + await l2BlockRangeRequestHandler.cb( + { + requestId: "request-3", + requestedAt: Date.now(), + reason: "cadence", + ranges: [{ from: 1, to: 5 }], + }, + () => Promise.resolve(), + ); + + expect(openAttestedReader).toHaveBeenCalledWith( + { name: "pool-node" }, + 7, + expect.any(Function), + ); + expect(onCatchupBlock.mock.calls).toEqual( + [1, 2, 3].map((height) => [ + { height }, + "proposed", + { + requestId: "request-3", + catchupReason: "cadence", + ...(height === 1 ? { finalized: true } : {}), + }, + ]), + ); + }); + + it("hands its heartbeat to the reader's setup, heartbeats before each block read and each publish, and stops and rejects on a failed heartbeat", async () => { + const calls: string[] = []; + openAttestedReader.mockResolvedValue({ + tips: { proposed: { number: 4 }, proven: { block: { number: 4 } } }, + getBlock: (height: number) => { + calls.push(`read ${height}`); + return Promise.resolve({ block: { height }, finalized: false }); + }, + }); + onCatchupBlock.mockClear(); + onCatchupBlock.mockImplementation(({ height }: { height: number }) => { + calls.push(`publish ${height}`); + return Promise.resolve(); + }); + const rebalance = new Error("The group is rebalancing"); + let beats = 0; + const heartbeat = () => { + calls.push("heartbeat"); + return ++beats === 5 ? Promise.reject(rebalance) : Promise.resolve(); + }; + + await expect( + l2BlockRangeRequestHandler.cb( + { + requestId: "request-4", + requestedAt: Date.now(), + reason: "cadence", + ranges: [{ from: 1, to: 4 }], + }, + heartbeat, + ), + ).rejects.toBe(rebalance); + + expect(openAttestedReader).toHaveBeenLastCalledWith( + { name: "pool-node" }, + 7, + heartbeat, + ); + expect(calls).toEqual([ + "heartbeat", + "read 1", + "heartbeat", + "publish 1", + "heartbeat", + "read 2", + "heartbeat", + "publish 2", + "heartbeat", + ]); + expect(onCatchupBlock).toHaveBeenCalledTimes(2); + }); +}); diff --git a/services/aztec-listener/tests/unit/max-prune-depth.test.ts b/services/aztec-listener/tests/unit/max-prune-depth.test.ts new file mode 100644 index 000000000..8ba127187 --- /dev/null +++ b/services/aztec-listener/tests/unit/max-prune-depth.test.ts @@ -0,0 +1,22 @@ +import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +describe("AZTEC_MAX_PRUNE_DEPTH", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + // Each import evaluates the environment module afresh, which can take + // seconds on a loaded host. + it("defaults to the chain walk bound and refuses a depth past it", async () => { + vi.stubEnv("AZTEC_MAX_PRUNE_DEPTH", undefined); + const { AZTEC_MAX_PRUNE_DEPTH } = await import("../../src/environment.js"); + expect(AZTEC_MAX_PRUNE_DEPTH).toBe(CHAIN_WALK_BOUND); + + vi.resetModules(); + vi.stubEnv("AZTEC_MAX_PRUNE_DEPTH", String(CHAIN_WALK_BOUND + 1)); + await expect(import("../../src/environment.js")).rejects.toMatchObject({ + issues: [{ code: "too_big", maximum: CHAIN_WALK_BOUND }], + }); + }, 30_000); +}); diff --git a/services/aztec-listener/tests/unit/node-client.test.ts b/services/aztec-listener/tests/unit/node-client.test.ts new file mode 100644 index 000000000..0c70455ac --- /dev/null +++ b/services/aztec-listener/tests/unit/node-client.test.ts @@ -0,0 +1,180 @@ +import { + type IncomingMessage, + type ServerResponse, + createServer, +} from "node:http"; +import { type AddressInfo } from "node:net"; +import { Writable } from "node:stream"; +import { inspect } from "node:util"; +import { + overwriteLoggingStream, + setLogLevel, +} from "@aztec-labs/foundation/log"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { boundedElectionReaders } from "../../src/svcs/poller/network-client/election-probe.js"; +import { callNodeFunction } from "../../src/svcs/poller/network-client/index.js"; +import { nodeClient } from "../../src/svcs/poller/network-client/pool.js"; +import { readLatestRollupVersion } from "../../src/svcs/poller/network-client/rollup-version.js"; + +const logger = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), +})); +const events = vi.hoisted(() => ({ + onChainInfo: vi.fn(), + onL2RpcNodeAlive: vi.fn(), + onL2RpcNodeError: vi.fn(), + onL2RpcNodeInfo: vi.fn(), +})); +vi.mock("../../src/logger.js", () => ({ logger })); +vi.mock("../../src/events/emitted/index.js", () => events); +vi.mock("../../src/environment.js", async (importOriginal) => ({ + ...(await importOriginal()), + AZTEC_RPC_URLS: [{ name: "gateway", url: "http://gateway:8080" }], +})); + +const KEYS = /key123secret|key456secret/; +const sdkOutput: string[] = []; + +beforeAll(() => { + // Vitest runs the SDK's logger silent. + overwriteLoggingStream( + new Writable({ + write(chunk, _encoding, done) { + sdkOutput.push(String(chunk)); + done(); + }, + }), + ); + setLogLevel("info"); +}); + +beforeEach(() => { + vi.clearAllMocks(); + sdkOutput.length = 0; +}); + +/** A keyed node at a local server that answers each request with `answer`. */ +const keyedNode = async ( + answer: (req: IncomingMessage, res: ServerResponse) => void, +) => { + const server = createServer(answer); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", () => resolve()), + ); + const { port } = server.address() as AddressInfo; + const url = `http://127.0.0.1:${port}/v1/key123secret?apikey=key456secret`; + return { + node: { name: "keyed", url, instance: nodeClient(url) }, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +}; + +const ours = () => + [logger.info, logger.warn, logger.error] + .flatMap((log) => log.mock.calls.map(([message]) => String(message))) + .join("\n"); + +describe("node client", () => { + it("redacts the node's URL in a transport failure's error, the SDK's log and the listener's", async () => { + const { node, close } = await keyedNode((req) => req.socket.destroy()); + let failure: unknown; + try { + failure = await callNodeFunction("getNodeInfo", [], node).catch( + (e: unknown) => e, + ); + expect(await readLatestRollupVersion([node], 10_000)).toBeUndefined(); + } finally { + await close(); + } + + const thrown = inspect(failure, { depth: Infinity }); + expect(thrown).toContain( + "Error fetching from host : [TypeError: fetch failed]", + ); + expect(ours()).toContain( + "Node keyed reported no rollup version: Error fetching from host ", + ); + expect(sdkOutput.join("")).toContain( + "Failed to fetch from the remote server", + ); + expect(thrown + ours() + sdkOutput.join("")).not.toMatch(KEYS); + }); + + it("still marks a node offline on an answer naming Service Unavailable, the URL redacted in its error event", async () => { + const { node, close } = await keyedNode((_req, res) => { + res.writeHead(503, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { message: "Service Unavailable" } })); + }); + try { + await expect(callNodeFunction("getNodeInfo", [], node)).rejects.toThrow( + "Service Unavailable", + ); + } finally { + await close(); + } + + expect(events.onL2RpcNodeError).toHaveBeenCalledTimes(1); + const [error, rpcUrl] = events.onL2RpcNodeError.mock.calls[0] as [ + { message: string }, + string, + ]; + expect(error.message).toBe( + "Error 503 from server : Service Unavailable", + ); + expect(rpcUrl).toBe(node.url); + expect(JSON.stringify(error) + ours() + sdkOutput.join("")).not.toMatch( + KEYS, + ); + }); + + it("still marks a node offline on Bad Gateway when a pool host is named gateway", async () => { + const url = "http://gateway:8080"; + vi.stubGlobal("fetch", () => + Promise.resolve( + new Response(JSON.stringify({ error: { message: "Bad Gateway" } }), { + status: 502, + headers: { "content-type": "application/json" }, + }), + ), + ); + try { + await expect( + callNodeFunction("getNodeInfo", [], { + name: "gateway", + url, + instance: nodeClient(url), + }), + ).rejects.toThrow("Bad Gateway"); + } finally { + vi.unstubAllGlobals(); + } + + expect(events.onL2RpcNodeError).toHaveBeenCalledTimes(1); + const [error] = events.onL2RpcNodeError.mock.calls[0] as [ + { message: string }, + ]; + expect(error.message).toBe("Error 502 from server : Bad Gateway"); + }); + + it("redacts a userinfo URL in the election probe's errors", async () => { + const url = "http://operator:pw-key123secret@127.0.0.1:1/v1/key456secret"; + const failure = await boundedElectionReaders(10_000)({ + name: "userinfo", + url, + instance: nodeClient(url), + }) + .getChainTips() + .catch((e: unknown) => e); + + const thrown = inspect(failure, { depth: Infinity }); + expect(thrown).toContain("includes credentials: "); + expect(thrown + sdkOutput.join("")).not.toMatch(KEYS); + }); +}); diff --git a/services/aztec-listener/tests/unit/rollup-version.test.ts b/services/aztec-listener/tests/unit/rollup-version.test.ts new file mode 100644 index 000000000..a80b1e239 --- /dev/null +++ b/services/aztec-listener/tests/unit/rollup-version.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from "vitest"; +import { readLatestRollupVersion } from "../../src/svcs/poller/network-client/rollup-version.js"; +import { FakeNode, genesisChain } from "./support/chain.js"; + +vi.mock("../../src/logger.js", () => ({ + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, +})); +vi.mock("../../src/events/emitted/index.js", () => ({ + onChainInfo: vi.fn(), + onL2RpcNodeAlive: vi.fn(), + onL2RpcNodeError: vi.fn(), + onL2RpcNodeInfo: vi.fn(), +})); + +describe("readLatestRollupVersion", () => { + it("names the highest version a node reports in time, with that node, or none when no node answers", async () => { + const chain = await genesisChain(); + const [low, high, failing, hanging] = [ + "low", + "high", + "failing", + "hanging", + ].map((name) => new FakeNode(name, chain)); + low.rollupVersion = 7; + high.rollupVersion = 9; + failing.getNodeInfo = () => Promise.reject(new Error("connection refused")); + // Never answers, so the deadline ends its read. + hanging.getNodeInfo = () => new Promise(() => undefined); + + expect( + await readLatestRollupVersion( + [low, high, failing, hanging].map((n) => n.rpc), + 50, + ), + ).toEqual({ node: high.rpc, version: 9 }); + expect( + await readLatestRollupVersion([failing.rpc, hanging.rpc], 50), + ).toBeUndefined(); + }); +}); diff --git a/services/aztec-listener/tests/unit/stream-logger.test.ts b/services/aztec-listener/tests/unit/stream-logger.test.ts new file mode 100644 index 000000000..3a5fd2d1c --- /dev/null +++ b/services/aztec-listener/tests/unit/stream-logger.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it, vi } from "vitest"; +import { streamLogger } from "../../src/svcs/poller/pollers/block_poller/stream-logger.js"; + +const logger = vi.hoisted(() => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + debug: vi.fn(), +})); +vi.mock("../../src/logger.js", () => ({ logger })); + +describe("stream logger", () => { + it("redacts URLs in stream logs", () => { + streamLogger.error( + "Error processing block stream", + new Error( + "Error fetching from host https://node.example/v1/abc?x=1: fetch failed", + ), + { url: "http://192.0.2.1:8080/path" }, + ); + + const [line] = logger.error.mock.calls[0] as [string]; + expect(line).toMatch( + /^Error processing block stream Error: Error fetching from host : fetch failed/, + ); + expect(line).toContain("url: ''"); + expect(line).not.toMatch(/node\.example|abc|192\.0\.2\.1/); + }); +}); diff --git a/services/aztec-listener/tests/unit/support/chain.ts b/services/aztec-listener/tests/unit/support/chain.ts new file mode 100644 index 000000000..d8e1cc881 --- /dev/null +++ b/services/aztec-listener/tests/unit/support/chain.ts @@ -0,0 +1,253 @@ +import { + BlockNumber, + CheckpointNumber, +} from "@aztec-labs/foundation/branded-types"; +import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { type AztecNode } from "@aztec-labs/aztec.js/node"; +import { + type BlockHash, + type BlockParameter, + L2Block, + type L2Tips, + L2TipsMemoryStore, +} from "@aztec-labs/stdlib/block"; +import { type BlockResponse } from "@aztec-labs/stdlib/interfaces/client"; +import { vi } from "vitest"; +import { type OpenElectionReader } from "../../../src/svcs/poller/network-client/election-probe.js"; +import { type RpcNode } from "../../../src/svcs/poller/network-client/pool.js"; + +export const ROLLUP_VERSION = 7; + +export type Chain = { blocks: L2Block[]; hashes: string[] }; + +// An empty body's tx effects root is zero, so these blocks pass the body check. +export const emptyBlock = ( + n: number, + parent?: L2Block, + version = ROLLUP_VERSION, +) => + L2Block.random(BlockNumber(n), { + txsPerBlock: 0, + txEffectsTreeRoot: Fr.ZERO, + version: new Fr(version), + ...(parent === undefined ? {} : { lastArchive: parent.archive }), + }); + +export const chainOf = async (blocks: L2Block[]): Promise => ({ + blocks, + hashes: await Promise.all( + blocks.map(async (b) => (await b.hash()).toString()), + ), +}); + +/** `chain` extended to height `to`, each new block linked to the one below. */ +export const grow = async (chain: Chain, to: number): Promise => { + const blocks = [...chain.blocks]; + for (let n = blocks.length; n <= to; n++) { + blocks.push(await emptyBlock(n, blocks.at(-1))); + } + return chainOf(blocks); +}; + +export const prefix = (chain: Chain, to: number): Chain => ({ + blocks: chain.blocks.slice(0, to + 1), + hashes: chain.hashes.slice(0, to + 1), +}); + +export const genesisChain = async (): Promise => + chainOf([await emptyBlock(0)]); + +export const respond = async ( + block: L2Block, + withBody: boolean, +): Promise => ({ + header: block.header, + archive: block.archive, + hash: await block.hash(), + checkpointNumber: block.checkpointNumber, + indexWithinCheckpoint: block.indexWithinCheckpoint, + number: block.number, + ...(withBody ? { body: block.body } : {}), +}); + +export const blocksFrom = (chain: Chain, heights: number[]) => + Promise.all(heights.map((n) => respond(chain.blocks[n], true))); + +export const checkpointHash = (n: number) => + `0x${n.toString(16).padStart(64, "0")}`; + +/** The parts of an Aztec node the stream source and the election read. */ +export class FakeNode { + readonly rpc: RpcNode; + tiers = { checkpointed: 0, proven: 0, finalized: 0 }; + rollupVersion = ROLLUP_VERSION; + unreachable = false; + probes = 0; + headerReads = 0; + readonly calls: string[] = []; + /** Answers the pass's tips reads only; the election's probe still sees `tips()`. */ + chainTipsOverride?: () => L2Tips | undefined; + /** Answers the election's probe only. */ + probeTipsOverride?: () => L2Tips; + /** Serves the pass's block reads in place of `chain`. */ + servedChain?: Chain; + getBlocksOverride?: ( + from: number, + limit: number, + ) => Promise; + getBlockOverride?: ( + param: BlockParameter, + ) => Promise; + + constructor( + name: string, + public chain: Chain, + ) { + this.rpc = { + name, + url: `http://${name}.invalid`, + instance: this as unknown as AztecNode, + }; + } + + get tip() { + return this.chain.blocks.length - 1; + } + + tips(): L2Tips { + const id = (n: number) => ({ + number: BlockNumber(n), + hash: this.chain.hashes[n], + }); + const tier = (n: number) => ({ + block: id(n), + checkpoint: { number: CheckpointNumber(n), hash: checkpointHash(n) }, + }); + return { + proposed: id(this.tip), + checkpointed: tier(this.tiers.checkpointed), + proven: tier(this.tiers.proven), + finalized: tier(this.tiers.finalized), + }; + } + + getChainTips() { + this.calls.push("getChainTips"); + return Promise.resolve( + this.chainTipsOverride === undefined + ? this.tips() + : this.chainTipsOverride(), + ); + } + + getNodeInfo() { + this.calls.push("getNodeInfo"); + return Promise.resolve({ rollupVersion: this.rollupVersion }); + } + + getBlock( + param: BlockParameter, + options?: { includeTransactions?: boolean }, + ): Promise { + this.calls.push("getBlock"); + if (this.getBlockOverride !== undefined) { + return this.getBlockOverride(param); + } + const chain = this.servedChain ?? this.chain; + const height = + typeof param === "number" + ? param + : typeof param === "object" && "number" in param + ? param.number + : typeof param === "object" && "hash" in param + ? chain.hashes.indexOf(param.hash.toString()) + : -1; + if (height < 0 || height >= chain.blocks.length) { + return Promise.resolve(undefined); + } + return respond(chain.blocks[height], options?.includeTransactions === true); + } + + getBlocks(from: number, limit: number): Promise { + this.calls.push("getBlocks"); + if (this.getBlocksOverride !== undefined) { + return this.getBlocksOverride(from, limit); + } + return Promise.all( + (this.servedChain ?? this.chain).blocks + .slice(from, from + limit) + .map((block) => respond(block, true)), + ); + } +} + +export const tipsOf = (chain: Chain, tiers: FakeNode["tiers"]) => { + const view = new FakeNode("view", chain); + view.tiers = tiers; + return view.tips(); +}; + +/** Runs `work` while `node`'s next block range hangs, until the pinned read's deadline ends it. */ +export const pastDeadline = async ( + node: FakeNode, + work: () => Promise, +) => { + let reached: () => void = () => undefined; + const hanging = new Promise((resolve) => { + reached = resolve; + }); + node.getBlocksOverride = () => { + reached(); + return new Promise(() => undefined); + }; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + try { + const running = work(); + await hanging; + await vi.advanceTimersByTimeAsync(60_000); + return await running; + } finally { + vi.useRealTimers(); + } +}; + +export const readerOf = + (fakes: FakeNode[]): OpenElectionReader => + (node) => { + const fake = fakes.find((f) => f.rpc.url === node.url); + if (fake === undefined) { + throw new Error(`no fake node ${node.name}`); + } + return { + getChainTips: () => { + fake.probes++; + return fake.unreachable + ? Promise.reject(new Error("connection refused")) + : Promise.resolve(fake.probeTipsOverride?.() ?? fake.tips()); + }, + getBlockHash: (n) => { + fake.headerReads++; + return Promise.resolve(fake.chain.hashes.at(n)); + }, + }; + }; + +/** The SDK's memory store with the Postgres store's two extra reads, over heights up to `top`. */ +export const memoryStore = ( + genesis: BlockHash, + otherVersionStored: () => boolean, + top: number, +) => { + const memory = new L2TipsMemoryStore(genesis); + return Object.assign(memory, { + otherVersionStored: () => Promise.resolve(otherVersionStored()), + holdsHashAtOrAbove: async (height: number) => { + for (let n = Math.max(height, 1); n <= top; n++) { + if ((await memory.getL2BlockHash(BlockNumber(n))) !== undefined) { + return true; + } + } + return false; + }, + }); +}; diff --git a/services/network-smoke/src/services.ts b/services/network-smoke/src/services.ts index bd6c0f60d..c54369fd0 100644 --- a/services/network-smoke/src/services.ts +++ b/services/network-smoke/src/services.ts @@ -105,6 +105,9 @@ export const startServices = ( // its L1 proposal arrived for a minute. CACHE_TTL: "5", CACHE_LATEST_TTL: "2", + // The block stream starts an empty listener store at the finalized + // block, so the blocks below it reach the API through reconciliation. + L2_BLOCK_RECONCILIATION_INTERVAL_MS: "5000", }, "ethereum-listener": { INSTANCE_NAME: "smoke-ethereum-listener",