From 809bb93c26db40403faeca04460d7bba9e689c89 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:07:27 +0000 Subject: [PATCH 01/31] feat(aztec-listener): add a block stream handler that publishes in order ChainPublisher handles the block stream's events. It checks each one against the store and the pass's tips, and a rejected event sets the pinned node aside and ends the pass: - a batch must carry the stream's rollup version, link block to block, and extend the stored block below it, read again from the node; - a prune must land on a block the store holds, with a stored block above it, and stay within AZTEC_MAX_PRUNE_DEPTH; - a tier event needs ordered tips and the stored hash at its height. It sends a batch's blocks one by one, each with the pass's proposed tip, and stores the blocks that went out, so a failed send goes out again on the next pass. A prune, or a proven tip that moves back, lowers the proven side work's cursor in the store's transaction. A node with only a shorter copy of the stored chain ends the pass without a prune: the handler warns when that wait starts and alerts while it lasts. The source gains reads of the pinned node outside the walk bound and checks the block 0 a pass serves against the store's genesis block. Blocks go out keyed by the network id, so the topic keeps their order. Co-Authored-By: Claude Opus 5.5 --- .../src/events/emitted/index.ts | 44 +- .../src/svcs/database/heights.controller.ts | 18 +- .../src/svcs/message-bus/index.ts | 15 + .../network-client/block-stream-source.ts | 132 ++++-- .../pollers/block_poller/chain-publisher.ts | 283 ++++++++++++ .../chain-publisher.integration.test.ts | 188 ++++++++ services/aztec-listener/tests/mocks/index.ts | 2 + .../tests/unit/block-processing.test.ts | 39 +- .../tests/unit/block-stream-source.test.ts | 250 ++-------- .../tests/unit/chain-publisher.test.ts | 434 ++++++++++++++++++ .../tests/unit/support/chain.ts | 244 ++++++++++ 11 files changed, 1382 insertions(+), 267 deletions(-) create mode 100644 services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts create mode 100644 services/aztec-listener/tests/integration/chain-publisher.integration.test.ts create mode 100644 services/aztec-listener/tests/unit/chain-publisher.test.ts create mode 100644 services/aztec-listener/tests/unit/support/chain.ts diff --git a/services/aztec-listener/src/events/emitted/index.ts b/services/aztec-listener/src/events/emitted/index.ts index 909efc3e7..f2df0ac4f 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"; @@ -41,9 +43,7 @@ export const onBlock = async ( ? "🦊 publishing proposed block" : "🐴 publishing proven block"; logger.info( - `${statusHintStr} ${height} (hash: ${( - await block.hash() - ).toString()})...`, + `${statusHintStr} ${height} (hash: ${(await block.hash()).toString()})...`, ); const blockBuffer = block.toBuffer() as Uint8Array; const blockStr = Buffer.from(blockBuffer).toString("hex"); @@ -72,6 +72,44 @@ export const onBlock = async ( } }; +/** + * Sends a block of the ordered stream, keyed by the network so the topic + * keeps the send order. `tip` is the proposed tip of the pass that sends it. + */ +export const onOrderedBlock = async (block: L2Block, tip: number) => { + const height = BigInt(block.header.globalVariables.blockNumber.toString()); + const heightNumber = toSafeBlockNumber(height); + logger.info( + `🦊 publishing block ${height} (hash: ${( + await block.hash() + ).toString()}, tip ${tip})...`, + ); + const blockBuffer = block.toBuffer() as Uint8Array; + const blockStr = Buffer.from(blockBuffer).toString("hex"); + await publishKeyedMessage("NEW_BLOCK_EVENT", L2_NETWORK_ID, { + block: blockStr, + statusHint: "proposed", + blockNumber: heightNumber, + ordered: { tip }, + }); + const potentiallyIncludedTxs = await txsController.getTxs([ + "pending", + "suspected_dropped", + ]); + const blockTxHashes = block.body.txEffects.map((effect) => + effect.txHash.toString(), + ); + + for (const potentialTx of potentiallyIncludedTxs) { + if (blockTxHashes.includes(potentialTx.txHash)) { + await txsController.storeOrUpdate(potentialTx, "proposed"); + logger.info( + `✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to proposed`, + ); + } + } +}; + export const onCatchupBlock = async ( block: L2Block, statusHint: L2BlockStatusHint, diff --git a/services/aztec-listener/src/svcs/database/heights.controller.ts b/services/aztec-listener/src/svcs/database/heights.controller.ts index 7cfd52a9e..8b9e57b60 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,6 +17,16 @@ export async function storeProcessedProvenBlockHeight(height: number) { .where(eq(heightsTable.networkId, L2_NETWORK_ID)); } +/** Moves the proven side work's cursor back to `height`; never forward. */ +export async function lowerProcessedProvenBlockHeight(height: number) { + await db() + .update(heightsTable) + .set({ + processedProvenBlockHeight: sql`LEAST(${heightsTable.processedProvenBlockHeight}, ${height})`, + }) + .where(eq(heightsTable.networkId, L2_NETWORK_ID)); +} + export async function storeChainProposedBlockHeight(height: number) { await db() .update(heightsTable) @@ -72,6 +82,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/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/network-client/block-stream-source.ts b/services/aztec-listener/src/svcs/poller/network-client/block-stream-source.ts index f2d77d1fa..b267bfde9 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 @@ -68,8 +68,8 @@ 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 }; +/** `tips` are what the election's probe showed. */ +type Pin = { node: RpcNode; bounds: PassBounds; tips: L2Tips }; type Bench = { until: number } | { tip: L2BlockId }; type Probe = { node: RpcNode; tips?: L2Tips; eligible: boolean }; type Candidate = Probe & { tips: L2Tips }; @@ -252,6 +252,11 @@ export class StickySource implements L2BlockStreamSource { return this.pin?.node; } + /** The tips the pinned node's election probe showed. */ + get pinnedTips(): L2Tips | undefined { + return this.pin?.tips; + } + get lastTips(): L2Tips | undefined { return this.latestTips; } @@ -343,7 +348,7 @@ 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; } @@ -384,30 +389,31 @@ 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) }), + ); + } + + /** Calls the pinned node under the pinned reads' deadline; a failure benches no node. */ + async pinnedRead( + fnName: K, + args: Parameters, + ) { + const pin = this.pin; + if (pin === undefined) { + throw new AbortError(); + } + 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,6 +470,40 @@ export class StickySource implements L2BlockStreamSource { } } + private async readBlockData( + query: BlockQuery, + ): Promise { + 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)); + if ("number" in query && query.number === BlockNumber.ZERO) { + await this.check(pin.node, this.genesisFault(response.header)); + } + 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, @@ -473,30 +513,38 @@ export class StickySource implements L2BlockStreamSource { throw new AbortError(); } 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, + ) { + 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), @@ -551,7 +599,7 @@ export class StickySource implements L2BlockStreamSource { pin.node.url, until === "cooldown" ? { until: this.now() + SET_ASIDE_MS } - : { tip: pin.proposed }, + : { tip: pin.tips.proposed }, ); if (this.pin === pin) { this.pin = undefined; 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..da8991b28 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts @@ -0,0 +1,283 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { AbortError } from "@aztec-labs/foundation/error"; +import { + type L2Block, + type L2BlockStreamEvent, + type L2BlockStreamEventHandler, + type L2Tips, + type L2TipsStoreBase, +} from "@aztec-labs/stdlib/block"; +import { + AZTEC_MAX_PRUNE_DEPTH, + AZTEC_STREAM_PREFIX_ALERT_MS, +} from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { type StickySource } from "../../network-client/block-stream-source.js"; + +type PruneEvent = 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" + | "endPassOnPrefix" + | "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; +}; + +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 block stream's handler. It checks each event against the store and the + * pass's snapshot, publishes blocks before it stores them, and stores what it + * accepts. A rejected event sets the pinned node aside and ends the pass. + */ +export class ChainPublisher implements L2BlockStreamEventHandler { + private prefixWait: { since: number; alertedAt?: number } | undefined; + private endedOnPrefix = false; + private readonly now: () => number; + + constructor( + private readonly deps: ChainPublisherDeps, + private readonly config: ChainPublisherConfig = { + maxPruneDepth: AZTEC_MAX_PRUNE_DEPTH, + prefixAlertMs: AZTEC_STREAM_PREFIX_ALERT_MS, + }, + ) { + this.now = deps.now ?? (() => Date.now()); + } + + /** Call before each pass's `sync()`. */ + startPass(): void { + this.endedOnPrefix = false; + } + + /** Call after each pass's `sync()`; a pass that did not end on the prefix rule ends the wait. */ + finishPass(): void { + if (!this.endedOnPrefix) { + this.prefixWait = undefined; + } + } + + async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise { + switch (event.type) { + case "blocks-added": + return this.addBlocks(event.blocks); + case "chain-pruned": + return this.prune(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.number; + const rejection = await this.batchFault(blocks); + if (rejection !== undefined) { + this.reject(rejection); + } + const sent: L2Block[] = []; + try { + for (const block of blocks) { + await this.deps.publishBlock(block, tip); + sent.push(block); + } + } finally { + // The next pass resumes after the last stored block, so a block whose + // send failed goes out again. + if (sent.length > 0) { + await this.deps.store.handleBlockStreamEvent({ + type: "blocks-added", + blocks: sent, + }); + } + } + } + + 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 AbortError(); + } + 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; + } + + 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.endPassOnPrefix(); + throw new AbortError(); + } + 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, + }); + } + 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 AbortError(); + } + 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, + ); + }); + } + + private async moveTier(event: TierEvent) { + const snapshot = this.snapshot(); + if (!tiersOrdered(snapshot)) { + this.reject({ + reason: `sent tips out of order: proposed ${snapshot.proposed.number}, checkpointed ${snapshot.checkpointed.block.number}, proven ${snapshot.proven.block.number}, finalized ${snapshot.finalized.block.number}`, + }); + } + // The store writes a tier's hash over the one at its height, and the + // finalized tier deletes the hashes below it. + if ( + (await this.deps.store.getL2BlockHash(event.block.number)) !== + event.block.hash + ) { + this.reject({ + reason: `has another block at its ${event.type.slice("chain-".length)} height ${event.block.number} than the one the block stream stored`, + }); + } + 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 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 AbortError(message); + } + + // Warns on entering the wait, not on each pass, and alerts on a timer. + 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/tests/integration/chain-publisher.integration.test.ts b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts new file mode 100644 index 000000000..2a0a3662b --- /dev/null +++ b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts @@ -0,0 +1,188 @@ +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(), + endPassOnPrefix: 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/block-processing.test.ts b/services/aztec-listener/tests/unit/block-processing.test.ts index e6139b26d..7c5592ec7 100644 --- a/services/aztec-listener/tests/unit/block-processing.test.ts +++ b/services/aztec-listener/tests/unit/block-processing.test.ts @@ -18,6 +18,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,7 +26,43 @@ vi.mock("../../src/logger.js", () => ({ })); // Import the actual function after setting up mocks -import { onBlock } from "../../src/events/emitted/index.js"; +import { onBlock, onOrderedBlock } from "../../src/events/emitted/index.js"; + +describe("onOrderedBlock", () => { + beforeEach(() => { + resetAllMocks(); + }); + + 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-3", "suspected_dropped"), + ]); + + await onOrderedBlock( + // @ts-expect-error - Mock object doesn't implement full L2Block interface + createMockL2Block(100, ["tx-1", "tx-2"]), + 104, + ); + + expect(mockMessageBus.publishKeyedMessage).toHaveBeenCalledWith( + "NEW_BLOCK_EVENT", + "SANDBOX", + { + block: Buffer.from("mock-block-100").toString("hex"), + statusHint: "proposed", + blockNumber: 100, + ordered: { tip: 104 }, + }, + ); + expect(mockMessageBus.publishMessage).not.toHaveBeenCalled(); + expect(mockTxsController.storeOrUpdate).toHaveBeenCalledTimes(1); + expect(mockTxsController.storeOrUpdate).toHaveBeenCalledWith( + expect.objectContaining({ txHash: "tx-1" }), + "proposed", + ); + }); +}); describe("onBlock Function", () => { beforeEach(() => { 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..711f5e234 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), @@ -1018,6 +820,18 @@ describe("StickySource passes", () => { expect((await store.getL2Tips()).proposed.number).toBe(8); }); + it("sets a node aside whose 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((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..a8a9d4500 --- /dev/null +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -0,0 +1,434 @@ +import { BlockNumber } 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, + 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 () => { + const pinned = await source.elect(); + if (pinned !== undefined) { + publisher.startPass(); + await new L2BlockStream(source, source.localData, publisher, undefined, { + batchSize: 10, + }).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("stops the pass at a failed send, and the next pass sends again from that block", 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(7); + await pass(); + expect(sent).toEqual(sentOf(main, [6], 9)); + expect((await head()).number).toBe(6); + + await pass(); + expect(sent).toEqual([ + ...sentOf(main, [6], 9), + ...sentOf(main, [7, 8, 9], 9), + ]); + }); +}); + +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("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.each([ + { + fault: "a proven tip off the stored chain", + reason: "has another block at its proven height 6", + tips: () => { + const tips = tipsOf(prefix(main, 10), { + checkpointed: 10, + proven: 6, + finalized: 4, + }); + return { + ...tips, + proven: { + ...tips.proven, + block: { number: BlockNumber(6), hash: main.hashes[5] }, + }, + }; + }, + }, + { + fault: "tiers out of order", + reason: "sent tips out of order", + tips: () => + tipsOf(prefix(main, 10), { checkpointed: 5, proven: 6, finalized: 4 }), + }, + ])( + "stores no tier from a snapshot with $fault, sets the node aside, and follows an honest node", + async ({ reason, tips }) => { + 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 = tips; + 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, reason)).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.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/support/chain.ts b/services/aztec-listener/tests/unit/support/chain.ts new file mode 100644 index 000000000..2dbcc96a4 --- /dev/null +++ b/services/aztec-listener/tests/unit/support/chain.ts @@ -0,0 +1,244 @@ +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 }; + 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(), + ); + } + + getBlock(param: BlockParameter): 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], false); + } + + 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; + }, + }); +}; From 808d89cb47c893caa85a92474529c84da67a22f8 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:44:40 +0000 Subject: [PATCH 02/31] feat(aztec-listener): follow the chain through the block stream Each tick of the block poller now runs one pass of the SDK block stream over the elected node, through ChainPublisher, in place of the proposed and proven height loops. After the pass: - tips go out only when the store reached the pass's snapshot, taken from that snapshot, when they changed or the heartbeat is due; the separate tips timer is gone; - heights.processedProposedBlockHeight follows the store's tip; - after such a pass the fee juice balance work runs on the proven blocks above its cursor, at most AZTEC_PROVEN_SIDE_WORK_MAX of them, read from the pinned node, with balances read at each block's hash. A block that fails stops the run and goes again on the next pass. It covers every stored tx of the block, whatever its state, and the cursor drops to the store's proven tip when it is above it, as the heights of a new rollup version start over; - an empty store starts at the elected node's finalized block. The rollup version comes from the nodes' node info, read again every CHAIN_INFO_POLL_INTERVAL_MS. A new version starts a new store from the reporting node's block 0; a node without block 0 stops the listener at start, and a pass that serves another block 0 alerts. Range requests and the full sweep read one node per request, its tips and version first, and mark a block final at or below that node's finalized tip on the stream's rollup version. The sweep stays at or below the store's tip. The stream's own logs go through the listener's logger: a failed send shows only there. AZTEC_BLOCK_STREAM_BATCH_SIZE (10, at most 50) and AZTEC_PROVEN_SIDE_WORK_MAX (200) are new; L2_TIPS_POLL_INTERVAL_MS and CATCHUP_POLL_WAIT_TIME_MS are gone. AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS now stops the whole stream, with its tips and its proven work. Co-Authored-By: Claude Opus 5.5 --- services/aztec-listener/src/environment.ts | 27 +- .../src/events/emitted/index.ts | 45 +-- .../received/on-l2-block-range-request.ts | 21 +- .../src/svcs/database/txs.controller.ts | 25 +- .../aztec-listener/src/svcs/poller/index.ts | 7 +- .../poller/network-client/attested-reads.ts | 83 ++++ .../network-client/block-stream-source.ts | 29 +- .../svcs/poller/network-client/deadline.ts | 18 + .../src/svcs/poller/network-client/index.ts | 40 -- .../poller/network-client/rollup-version.ts | 48 +++ .../block_poller/handle-proven-block-txs.ts | 218 +++++------ .../svcs/poller/pollers/block_poller/index.ts | 361 ++++++++++-------- .../pollers/block_poller/proven-side-work.ts | 63 +++ .../pollers/block_poller/stream-logger.ts | 32 ++ .../src/svcs/poller/pollers/l2-tips-poller.ts | 31 +- .../producer-payloads.corpus.test.ts | 25 +- .../tests/unit/attested-reads.test.ts | 107 ++++++ .../tests/unit/block-poller-cursor.test.ts | 266 ++++++++----- .../tests/unit/block-poller.test.ts | 195 ++++++++++ .../tests/unit/block-processing.test.ts | 169 +------- .../tests/unit/block-stream-source.test.ts | 5 +- .../tests/unit/dev-node-error.test.ts | 3 + .../tests/unit/full-sweep-catchup.test.ts | 133 +++---- .../tests/unit/l2-block-range-request.test.ts | 58 ++- .../tests/unit/rollup-version.test.ts | 40 ++ .../tests/unit/support/chain.ts | 13 +- 26 files changed, 1260 insertions(+), 802 deletions(-) create mode 100644 services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts create mode 100644 services/aztec-listener/src/svcs/poller/network-client/deadline.ts create mode 100644 services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts create mode 100644 services/aztec-listener/src/svcs/poller/pollers/block_poller/proven-side-work.ts create mode 100644 services/aztec-listener/src/svcs/poller/pollers/block_poller/stream-logger.ts create mode 100644 services/aztec-listener/tests/unit/attested-reads.test.ts create mode 100644 services/aztec-listener/tests/unit/block-poller.test.ts create mode 100644 services/aztec-listener/tests/unit/rollup-version.test.ts diff --git a/services/aztec-listener/src/environment.ts b/services/aztec-listener/src/environment.ts index 1d12262e3..8c6270e4f 100644 --- a/services/aztec-listener/src/environment.ts +++ b/services/aztec-listener/src/environment.ts @@ -3,6 +3,7 @@ import { 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 +22,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 +30,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) @@ -93,6 +86,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_SIDE_WORK_MAX = z.coerce + .number() + .int() + .positive() + .default(200) + .parse(process.env.AZTEC_PROVEN_SIDE_WORK_MAX); export const L2_BLOCK_RANGE_REQUEST_MAX_RANGES = z.coerce .number() .int() @@ -187,8 +194,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 +201,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_SIDE_WORK_MAX: ${AZTEC_PROVEN_SIDE_WORK_MAX} 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 f2df0ac4f..933581bc8 100644 --- a/services/aztec-listener/src/events/emitted/index.ts +++ b/services/aztec-listener/src/events/emitted/index.ts @@ -32,46 +32,6 @@ const toSafeBlockNumber = (value: bigint): number => { return blockNumber; }; -export const onBlock = async ( - block: L2Block, - statusHint: L2BlockStatusHint, -) => { - 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: ${(await block.hash()).toString()})...`, - ); - const blockBuffer = block.toBuffer() as Uint8Array; - const blockStr = Buffer.from(blockBuffer).toString("hex"); - await publishMessage("NEW_BLOCK_EVENT", { - block: blockStr, - statusHint, - blockNumber: heightNumber, - }); - const potentiallyIncludedTxs = await txsController.getTxs([ - "pending", - "suspected_dropped", - ]); - const blockTxHashes = block.body.txEffects.map((effect) => - effect.txHash.toString(), - ); - - for (const potentialTx of potentiallyIncludedTxs) { - const txFoundInBlock = blockTxHashes.includes(potentialTx.txHash); - if (txFoundInBlock) { - const newState = statusHint; - await txsController.storeOrUpdate(potentialTx, newState); - logger.info( - `✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to ${newState}`, - ); - } - } -}; - /** * Sends a block of the ordered stream, keyed by the network so the topic * keeps the send order. `tip` is the proposed tip of the pass that sends it. @@ -113,7 +73,10 @@ export const onOrderedBlock = async (block: L2Block, tip: number) => { export const onCatchupBlock = async ( block: L2Block, statusHint: L2BlockStatusHint, - metadata: Pick = {}, + metadata: Pick< + CatchupBlockEvent, + "requestId" | "catchupReason" | "final" + > = {}, ) => { 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..a377b56db 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 @@ -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(); @@ -93,8 +91,10 @@ 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()); + 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 +118,19 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { } for (let height = range.from; height <= range.to && publishedBlocks < maxBlocks; height++) { - const block = await getBlock(height); - if (!block) { + const read = await reader.getBlock(height); + if (!read) { failedHeights++; logger.warn(`Requested catchup block ${height} not found for ${event.requestId}`); continue; } await onCatchupBlock( - block, + read.block, range.statusHint, { requestId: event.requestId, catchupReason: event.reason === "tip_boundary_mismatch" ? "reorg_repair" : event.reason, + ...(read.final ? { final: true as const } : {}), }, ); publishedBlocks++; 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/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..257604df1 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts @@ -0,0 +1,83 @@ +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"; + +/** `final`: at or below the serving node's own finalized tip, on the stream's rollup version. */ +export type AttestedBlock = { block: L2Block; final: 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 `final` holds for every + * block read after them. Only the stream's own `rollupVersion` gets `final`. + */ +export const openAttestedReader = async ( + node: RpcNode, + rollupVersion: number | undefined, +): Promise => { + const tips = await callNodeFunction("getChainTips", [], node); + 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, + final: + 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 b267bfde9..45562fc02 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, @@ -119,24 +120,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. @@ -406,7 +389,7 @@ export class StickySource implements L2BlockStreamSource { async pinnedRead( fnName: K, args: Parameters, - ) { + ): Promise>> { const pin = this.pin; if (pin === undefined) { throw new AbortError(); @@ -486,7 +469,11 @@ export class StickySource implements L2BlockStreamSource { } await this.check(pin.node, blockDataFault(query, response.header)); if ("number" in query && query.number === BlockNumber.ZERO) { - await this.check(pin.node, this.genesisFault(response.header)); + 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, @@ -524,7 +511,7 @@ export class StickySource implements L2BlockStreamSource { pin: Pin, fnName: K, args: Parameters, - ) { + ): Promise>> { const result = await withDeadline( callNodeFunction(fnName, args, pin.node), PINNED_READ_TIMEOUT_MS, 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/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/rollup-version.ts b/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts new file mode 100644 index 000000000..3c3be397e --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts @@ -0,0 +1,48 @@ +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"; + +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: ${(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/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..b638ee448 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,240 @@ import { - AZTEC_ENABLE_FULL_SWEEP_CATCHUP, + L2BlockStream, + type L2TipsStoreBase, + localTipsMatch, +} from "@aztec-labs/stdlib/block"; +import { + 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_TIPS_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 { + StickySource, + readGenesisBlockHash, +} from "../../network-client/block-stream-source.js"; +import { getOnlineRpcNodes, getRpcNode } from "../../network-client/pool.js"; import { - getBlock, - getLatestProposedHeight, - getLatestProvenHeight, -} from "../../network-client/index.js"; -import { handleProvenTransactions } from "./handle-proven-block-txs.js"; + 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"; -let timeoutId: number | undefined; +/** One rollup version's block stream. */ +export type StreamChain = { + rollupVersion: number; + store: Pick; + source: StickySource; + publisher: ChainPublisher; +}; + +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_TIPS_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.final ? { final: 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 tips, the heights, 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(); 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}`, - ); - } - 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); + await new L2BlockStream( + source, + source.localData, + publisher, + streamLogger, + { + batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, + // From the elected node's finalized block, inclusive: no history is replayed. + startingBlock: + before.proposed.number === 0 + ? source.pinnedTips?.finalized.block.number + : undefined, + }, + ).sync(); + } finally { + publisher.finishPass(); } - } 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 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"); + const after = await store.getL2Tips(); + const snapshot = source.lastTips; + const settled = snapshot !== undefined && localTipsMatch(after, snapshot); + if (settled && AZTEC_LISTEN_FOR_L2_TIPS) { + await publishTipsIfDue(snapshot); + } + const moved = after.proposed.number !== before.proposed.number; + if (moved) { + await storeProcessedProposedBlockHeight(after.proposed.number); + } + if (settled && !AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS) { + await runProvenSideWork({ + source, + provenTip: after.proven.block.number, + readCursor: readProvenCursor, + storeCursor: storeProcessedProvenBlockHeight, + }); + } + if (!moved) { + await sweepOnce(after.proposed.number, rollupVersion); } - 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 runPass(await currentChain()); + } catch (e) { + // A read with no node pinned; the next pass elects one. + if ((e as Error).name !== "AbortError") { + logger.error(`🐻 block stream pass failed: ${(e as Error).stack}`); + } + } 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..bd5641709 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/proven-side-work.ts @@ -0,0 +1,63 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { + AZTEC_BLOCK_STREAM_BATCH_SIZE, + AZTEC_PROVEN_SIDE_WORK_MAX, +} from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { type StickySource } from "../../network-client/block-stream-source.js"; +import { + type ReadPublicStorage, + handleProvenTransactions, +} from "./handle-proven-block-txs.js"; + +export type ProvenSideWorkDeps = { + source: Pick; + /** The pinned node's proven tip, as the store holds it after a settled pass. */ + provenTip: number; + readCursor: () => Promise; + storeCursor: (height: number) => Promise; +}; + +/** + * 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 stops the run, so the next pass retries it. + */ +export const runProvenSideWork = async ( + { source, provenTip, readCursor, storeCursor }: ProvenSideWorkDeps, + { max, batchSize } = { + max: AZTEC_PROVEN_SIDE_WORK_MAX, + batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, + }, +) => { + 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) { + const outcome = await handleProvenTransactions(block, readStorage); + if (!outcome.ok) { + logger.warn( + `Proven side work stopped at block ${block.number}, which the next pass retries: ${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..158a15281 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/pollers/block_poller/stream-logger.ts @@ -0,0 +1,32 @@ +import { inspect } from "node:util"; +import { type Logger as SdkLogger } from "@aztec-labs/foundation/log"; +import { logger } from "../../../../logger.js"; + +// The stream's data carries bigints and field elements, which JSON rejects. +const line = (msg: string, ...data: unknown[]) => + [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 + * a handler's failure only here, so it 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..b7d2c1fd7 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,9 @@ const normalizeTips = (tips: RawL2Tips): ChicmozL2Tips => finalized: normalizeCheckpointTip(tips.finalized), }); -const pollOnce = async () => { - const tips = normalizeTips((await getL2Tips()) as unknown as RawL2Tips); +/** Publishes `raw` unless it equals the last tips published and the heartbeat is not due. */ +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 +75,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/unit/attested-reads.test.ts b/services/aztec-listener/tests/unit/attested-reads.test.ts new file mode 100644 index 000000000..65f7f96ff --- /dev/null +++ b/services/aztec-listener/tests/unit/attested-reads.test.ts @@ -0,0 +1,107 @@ +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, and marks a block final only at or below its finalized tip", async () => { + const node = nodeAt(2); + const reader = await openAttestedReader(node.rpc, ROLLUP_VERSION); + + const [two, three] = [await reader.getBlock(2), await reader.getBlock(3)]; + + expect(node.calls).toEqual([ + "getChainTips", + "getNodeInfo", + "getBlock", + "getBlock", + ]); + expect(await two?.block.hash()).toEqual(await chain.blocks[2].hash()); + expect([two?.final, three?.final]).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 final 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))?.final).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..a63c8981c 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,196 @@ -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)}`; + +// The side work reads a block's number, tx hashes, hash and fee recipient. +const blockAt = (n: number, txHashes: string[] = []) => + ({ + number: n, + body: { + txEffects: txHashes.map((hash) => ({ txHash: { toString: () => hash } })), + }, + header: { + globalVariables: { + blockNumber: n, + 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(); + }, + }; +}; + +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({ source, provenTip: 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({ source, provenTip: 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({ source, provenTip: 2, ...cursors }); + expect(cursor.value).toBe(2); + await runProvenSideWork({ source, provenTip: 3, ...cursors }); + expect(cursor.value).toBe(3); + }); + + 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({ source, provenTip: 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..1c7a39288 --- /dev/null +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -0,0 +1,195 @@ +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, + 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, +} from "./support/chain.js"; + +const mocks = vi.hoisted(() => ({ + publishTipsIfDue: vi.fn(), + storeProcessedProposedBlockHeight: vi.fn(), + 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/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({ + 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(); +}); + +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, + }; +}; + +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("logs a failed send through the listener's logger and publishes no tips", async () => { + const x = new FakeNode("x", prefix(main, 3)); + const { chain } = chainOver([x], () => + Promise.reject(new Error("broker down")), + ); + + await runPass(chain); + + expect(logger.error).toHaveBeenCalledWith( + expect.stringMatching(/^Error processing block stream .*broker down/s), + ); + expect(mocks.publishTipsIfDue).not.toHaveBeenCalled(); + }); + + 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); + + 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("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 7c5592ec7..83412022f 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, @@ -26,7 +23,7 @@ vi.mock("../../src/logger.js", () => ({ })); // Import the actual function after setting up mocks -import { onBlock, onOrderedBlock } from "../../src/events/emitted/index.js"; +import { onOrderedBlock } from "../../src/events/emitted/index.js"; describe("onOrderedBlock", () => { beforeEach(() => { @@ -63,167 +60,3 @@ describe("onOrderedBlock", () => { ); }); }); - -describe("onBlock Function", () => { - 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 = [ - 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); - - // Execute with proposed block - await onBlock( - // @ts-expect-error - Mock object doesn't implement full L2Block interface - mockBlock, - "proposed", - ); - - // Verify: NEW_BLOCK_EVENT published - expect(mockMessageBus.publishMessage).toHaveBeenCalledWith( - "NEW_BLOCK_EVENT", - expect.objectContaining({ - blockNumber: 100, - statusHint: "proposed", - }), - ); - - // Verify: Transactions found in block promoted to "proposed" - 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 711f5e234..556b414a5 100644 --- a/services/aztec-listener/tests/unit/block-stream-source.test.ts +++ b/services/aztec-listener/tests/unit/block-stream-source.test.ts @@ -820,7 +820,7 @@ describe("StickySource passes", () => { expect((await store.getL2Tips()).proposed.number).toBe(8); }); - it("sets a node aside whose pass serves another block 0 than the store's genesis block", async () => { + 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] }); @@ -828,6 +828,9 @@ describe("StickySource passes", () => { 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(); }); 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..0f76fa26b 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,94 @@ 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, 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 } }), + }, + 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 }, final: 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 final 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", { final: true }], + [{ height: 2 }, "proposed", {}], + [{ height: 1 }, "proposed", { final: 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..ddaf809d4 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,36 @@ 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 final on the blocks its reader attests", async () => { + openAttestedReader.mockResolvedValue({ + tips: { proposed: { number: 3 }, proven: { block: { number: 2 } } }, + getBlock: (height: number) => + Promise.resolve({ block: { height }, final: 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(onCatchupBlock.mock.calls).toEqual( + [1, 2, 3].map((height) => [ + { height }, + "proposed", + { + requestId: "request-3", + catchupReason: "cadence", + ...(height === 1 ? { final: true } : {}), + }, + ]), + ); + }); +}); 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/support/chain.ts b/services/aztec-listener/tests/unit/support/chain.ts index 2dbcc96a4..d8e1cc881 100644 --- a/services/aztec-listener/tests/unit/support/chain.ts +++ b/services/aztec-listener/tests/unit/support/chain.ts @@ -80,6 +80,7 @@ export const checkpointHash = (n: number) => export class FakeNode { readonly rpc: RpcNode; tiers = { checkpointed: 0, proven: 0, finalized: 0 }; + rollupVersion = ROLLUP_VERSION; unreachable = false; probes = 0; headerReads = 0; @@ -139,7 +140,15 @@ export class FakeNode { ); } - getBlock(param: BlockParameter): Promise { + 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); @@ -156,7 +165,7 @@ export class FakeNode { if (height < 0 || height >= chain.blocks.length) { return Promise.resolve(undefined); } - return respond(chain.blocks[height], false); + return respond(chain.blocks[height], options?.includeTransactions === true); } getBlocks(from: number, limit: number): Promise { From c8e1906d04846744b5ffc6e856e42a2b3dfa251b Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Thu, 26 Nov 2026 23:56:21 +0000 Subject: [PATCH 03/31] refactor(aztec-listener): drop the chain height writers Nothing calls storeBlockHeights, storeChainProposedBlockHeight or storeChainProvenBlockHeight since the block stream replaced the height loops. heights.chainProvenBlockHeight now keeps the old listener's last value, which the stream's first start reads as its floor, so no writer of it stays behind. Co-Authored-By: Claude Opus 5.5 --- .../src/svcs/database/heights.controller.ts | 36 ------------------- .../src/svcs/database/schema.ts | 2 ++ 2 files changed, 2 insertions(+), 36 deletions(-) diff --git a/services/aztec-listener/src/svcs/database/heights.controller.ts b/services/aztec-listener/src/svcs/database/heights.controller.ts index 8b9e57b60..20254b789 100644 --- a/services/aztec-listener/src/svcs/database/heights.controller.ts +++ b/services/aztec-listener/src/svcs/database/heights.controller.ts @@ -27,42 +27,6 @@ export async function lowerProcessedProvenBlockHeight(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; -}) { - await db() - .update(heightsTable) - .set({ - processedProposedBlockHeight, - chainProposedBlockHeight, - processedProvenBlockHeight, - chainProvenBlockHeight, - }) - .where(eq(heightsTable.networkId, L2_NETWORK_ID)); -} - export async function ensureInitializedBlockHeights() { await db() .insert(heightsTable) 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(), From 70ae88af395535a4a8b3a67a5b58f5cff4756b60 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:18:25 +0000 Subject: [PATCH 04/31] fix(aztec-listener): redact URLs in stream logs Every URL in a line the SDK block stream logs, in its message, an error or its data, is replaced with before the line reaches the listener's logger. Co-Authored-By: Claude Opus 5.5 --- .../pollers/block_poller/stream-logger.ts | 10 +++++-- .../tests/unit/stream-logger.test.ts | 29 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) create mode 100644 services/aztec-listener/tests/unit/stream-logger.test.ts 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 index 158a15281..45036923b 100644 --- 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 @@ -2,11 +2,15 @@ import { inspect } from "node:util"; import { type Logger as SdkLogger } from "@aztec-labs/foundation/log"; import { logger } from "../../../../logger.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. +const URL_PATTERN = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*[^\s"'<>.,:;)]/gi; + // The stream's data carries bigints and field elements, which JSON rejects. const line = (msg: string, ...data: unknown[]) => - [msg, ...data.filter((d) => d !== undefined).map((d) => inspect(d))].join( - " ", - ); + [msg, ...data.filter((d) => d !== undefined).map((d) => inspect(d))] + .join(" ") + .replace(URL_PATTERN, ""); /** * The SDK block stream's logger, routed to the listener's. The stream reports 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/); + }); +}); From 3495848e384dc0842c22634226f5c10bbd4eae85 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:21:09 +0000 Subject: [PATCH 05/31] fix(aztec-listener): check a prune's tiers before the store writes them The store lowers the checkpointed and proven tips to the ones a prune carries and writes their hashes over the stored ones at those heights. At or below the prune target no block of the pass writes them back, so a wrong hash there stayed, the finalized block's included. ChainPublisher now checks a prune as it checks a tier event before the store sees it: the pass's tips must be in order, and each tier at or below the target must name the block the store holds at its height. Otherwise the node is set aside and nothing is stored. Co-Authored-By: Claude Opus 5.5 --- .../pollers/block_poller/chain-publisher.ts | 45 +++++++++++----- .../tests/unit/chain-publisher.test.ts | 54 +++++++++++++++++++ 2 files changed, 85 insertions(+), 14 deletions(-) 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 index da8991b28..34a89e615 100644 --- 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 @@ -2,6 +2,7 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { AbortError } from "@aztec-labs/foundation/error"; import { type L2Block, + type L2BlockId, type L2BlockStreamEvent, type L2BlockStreamEventHandler, type L2Tips, @@ -195,6 +196,18 @@ export class ChainPublisher implements L2BlockStreamEventHandler { alert: true, }); } + this.checkOrder(snapshot); + // 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( @@ -214,22 +227,10 @@ export class ChainPublisher implements L2BlockStreamEventHandler { } private async moveTier(event: TierEvent) { - const snapshot = this.snapshot(); - if (!tiersOrdered(snapshot)) { - this.reject({ - reason: `sent tips out of order: proposed ${snapshot.proposed.number}, checkpointed ${snapshot.checkpointed.block.number}, proven ${snapshot.proven.block.number}, finalized ${snapshot.finalized.block.number}`, - }); - } + this.checkOrder(this.snapshot()); // The store writes a tier's hash over the one at its height, and the // finalized tier deletes the hashes below it. - if ( - (await this.deps.store.getL2BlockHash(event.block.number)) !== - event.block.hash - ) { - this.reject({ - reason: `has another block at its ${event.type.slice("chain-".length)} height ${event.block.number} than the one the block stream stored`, - }); - } + 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) { @@ -243,6 +244,22 @@ export class ChainPublisher implements L2BlockStreamEventHandler { await this.deps.store.handleBlockStreamEvent(event); } + private checkOrder(snapshot: L2Tips) { + if (!tiersOrdered(snapshot)) { + this.reject({ + reason: `sent tips out of order: proposed ${snapshot.proposed.number}, checkpointed ${snapshot.checkpointed.block.number}, proven ${snapshot.proven.block.number}, finalized ${snapshot.finalized.block.number}`, + }); + } + } + + 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) { diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index a8a9d4500..ac0ca2fba 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -401,6 +401,60 @@ describe("ChainPublisher checks", () => { }, ); + // The node forks from block 5, below the stored proven tip 6 and above the + // stored finalized tip 4. + it.each([ + { + fault: "another block 4 as its proven tip", + reason: "has another block at its proven height 4", + tiers: { checkpointed: 9, proven: 4, finalized: 4 }, + provenHash: () => main.hashes[3], + }, + { + fault: "tiers out of order", + reason: "sent tips out of order", + tiers: { checkpointed: 6, proven: 7, finalized: 4 }, + provenHash: undefined, + }, + ])( + "stores nothing from a prune with $fault, sets the node aside, and follows an honest node", + async ({ reason, tiers, provenHash }) => { + 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; + const fork = await grow(prefix(main, 5), 9); + x.chain = fork; + x.chainTipsOverride = () => { + const tips = tipsOf(fork, tiers); + return provenHash === undefined + ? tips + : { + ...tips, + proven: { + ...tips.proven, + block: { ...tips.proven.block, hash: provenHash() }, + }, + }; + }; + 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, reason)).toBe(1); + world.online = [x, y]; + expect(await pass()).toBe(y.rpc); + }, + ); + it.each([ { change: "a prune past a proof", From 8fb2c153c3a06f36eb8ea42ed0360c696702729d Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:24:28 +0000 Subject: [PATCH 06/31] fix(aztec-listener): never store a proposed tip the pass did not send On an empty store the stream started at the election probe's finalized block. When the pass's own snapshot then showed a lower tip, the stream downloaded nothing, still reported that tip, and the store recorded it although no block up to it had been sent; later passes resumed above it. The start now comes from the snapshot the stream itself read, which it reads before it plans the downloads. ChainPublisher also ends the pass on a proposed tip the store does not hold with that hash, so a tip is stored only once its block was sent. Co-Authored-By: Claude Opus 5.5 --- .../network-client/block-stream-source.ts | 5 ----- .../pollers/block_poller/chain-publisher.ts | 19 +++++++++++++++++++ .../svcs/poller/pollers/block_poller/index.ts | 12 +++++++----- .../tests/unit/block-poller.test.ts | 18 ++++++++++++++++++ .../tests/unit/chain-publisher.test.ts | 16 +++++++++++++++- 5 files changed, 59 insertions(+), 11 deletions(-) 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 45562fc02..949aebba8 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 @@ -235,11 +235,6 @@ export class StickySource implements L2BlockStreamSource { return this.pin?.node; } - /** The tips the pinned node's election probe showed. */ - get pinnedTips(): L2Tips | undefined { - return this.pin?.tips; - } - get lastTips(): L2Tips | undefined { return this.latestTips; } 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 index 34a89e615..93082caed 100644 --- 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 @@ -16,6 +16,7 @@ import { logger } from "../../../../logger.js"; import { 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" } @@ -94,6 +95,8 @@ export class ChainPublisher implements L2BlockStreamEventHandler { 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": @@ -226,6 +229,22 @@ export class ChainPublisher implements L2BlockStreamEventHandler { }); } + // The stream reports the snapshot's tip even when it downloaded nothing up + // to it, as from a `startingBlock` past that tip; the store would then hold + // a tip whose block was never sent. + private async confirmProposed(event: ProposedEvent) { + if ( + (await this.deps.store.getL2BlockHash(event.block.number)) !== + 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 AbortError(); + } + await this.deps.store.handleBlockStreamEvent(event); + } + private async moveTier(event: TierEvent) { this.checkOrder(this.snapshot()); // The store writes a tier's hash over the one at its height, and the 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 b638ee448..28653833d 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 @@ -150,6 +150,7 @@ export const runPass = async ({ const before = await store.getL2Tips(); if ((await source.elect()) !== undefined) { publisher.startPass(); + const empty = before.proposed.number === 0; try { await new L2BlockStream( source, @@ -158,11 +159,12 @@ export const runPass = async ({ streamLogger, { batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, - // From the elected node's finalized block, inclusive: no history is replayed. - startingBlock: - before.proposed.number === 0 - ? source.pinnedTips?.finalized.block.number - : undefined, + // 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 { diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index 1c7a39288..7f0b3e039 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -18,6 +18,7 @@ import { memoryStore, prefix, readerOf, + tipsOf, } from "./support/chain.js"; const mocks = vi.hoisted(() => ({ @@ -135,6 +136,23 @@ describe("block poller pass", () => { 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("logs a failed send through the listener's logger and publishes no tips", async () => { const x = new FakeNode("x", prefix(main, 3)); const { chain } = chainOver([x], () => diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index ac0ca2fba..83d68712e 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -103,12 +103,13 @@ const setup = ({ { maxPruneDepth, prefixAlertMs: 60_000 }, ); /** One listener pass: the election, then the stream when a node is pinned. */ - const pass = async () => { + 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(); } @@ -328,6 +329,19 @@ describe("ChainPublisher checks", () => { }, ); + it("stores no proposed tip that the pass did not send", async () => { + const x = new FakeNode("x", prefix(main, 4)); + x.tiers = { checkpointed: 4, proven: 4, finalized: 4 }; + const { sent, pass, head } = setup({ nodes: [x] }); + + // 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()).number).toBe(0); + 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] }); From 8c14ae8b262d8f705d386a9bd54601d584c3d9ad Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:27:58 +0000 Subject: [PATCH 07/31] fix(aztec-listener): run the proven side work only on stored blocks The side work reads proven blocks from the pinned node by height after the pass settled, and the node can serve another block at a height by then. Before a block's balances and tx states, the side work now requires the stream's rollup version and the hash the store holds at that height; below the store's finalized tip, where it keeps no hashes and a block cannot change, the version alone. Any other block ends the side work for the pass, which the next pass retries. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/index.ts | 6 +- .../pollers/block_poller/proven-side-work.ts | 34 ++++++- .../tests/unit/block-poller-cursor.test.ts | 91 +++++++++++++++++-- .../tests/unit/block-poller.test.ts | 7 ++ 4 files changed, 128 insertions(+), 10 deletions(-) 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 28653833d..485b1424b 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,3 +1,4 @@ +import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { L2BlockStream, type L2TipsStoreBase, @@ -44,7 +45,7 @@ import { streamLogger } from "./stream-logger.js"; /** One rollup version's block stream. */ export type StreamChain = { rollupVersion: number; - store: Pick; + store: Pick; source: StickySource; publisher: ChainPublisher; }; @@ -184,7 +185,10 @@ export const runPass = async ({ 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, }); 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 index bd5641709..f2a9e49f4 100644 --- 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 @@ -1,4 +1,5 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { type L2Block } from "@aztec-labs/stdlib/block"; import { AZTEC_BLOCK_STREAM_BATCH_SIZE, AZTEC_PROVEN_SIDE_WORK_MAX, @@ -12,24 +13,47 @@ import { 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 the store keeps no hash, and a block cannot change. +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 stops the run, so the next pass retries it. + * block, or one off the stored chain, stops the run, so the next pass retries + * it. */ export const runProvenSideWork = async ( - { source, provenTip, readCursor, storeCursor }: ProvenSideWorkDeps, + deps: ProvenSideWorkDeps, { max, batchSize } = { max: AZTEC_PROVEN_SIDE_WORK_MAX, 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) { @@ -49,6 +73,12 @@ export const runProvenSideWork = async ( 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( 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 a63c8981c..e1079898b 100644 --- a/services/aztec-listener/tests/unit/block-poller-cursor.test.ts +++ b/services/aztec-listener/tests/unit/block-poller-cursor.test.ts @@ -45,9 +45,10 @@ vi.mock("../../src/svcs/message-bus/index.js", () => ({ })); const PAYER = `0x${"11".repeat(32)}`; +const VERSION = 7; -// The side work reads a block's number, tx hashes, hash and fee recipient. -const blockAt = (n: number, txHashes: string[] = []) => +// 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: { @@ -56,6 +57,7 @@ const blockAt = (n: number, txHashes: string[] = []) => header: { globalVariables: { blockNumber: n, + version: { toBigInt: () => BigInt(version) }, feeRecipient: { toString: () => "0xfee" }, }, }, @@ -93,6 +95,24 @@ const cursorAt = (start: number) => { }; }; +/** 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 }) => ({ @@ -115,7 +135,7 @@ describe("proven side work", () => { Array.from({ length: 201 }, (_, i) => blockAt(i + 1)), ); const { cursor, ...cursors } = cursorAt(0); - const run = () => runProvenSideWork({ source, provenTip: 201, ...cursors }); + const run = () => runProvenSideWork(depsOf(source, 201, cursors)); await run(); expect(cursor.value).toBe(200); @@ -137,7 +157,7 @@ describe("proven side work", () => { new Set([2]), ); const { cursor, ...cursors } = cursorAt(0); - const run = () => runProvenSideWork({ source, provenTip: 3, ...cursors }); + const run = () => runProvenSideWork(depsOf(source, 3, cursors)); await run(); expect(cursor.value).toBe(1); @@ -162,17 +182,74 @@ describe("proven side work", () => { const { source } = sourceOf([blockAt(1), blockAt(2), blockAt(3)]); const { cursor, ...cursors } = cursorAt(50); - await runProvenSideWork({ source, provenTip: 2, ...cursors }); + await runProvenSideWork(depsOf(source, 2, cursors)); expect(cursor.value).toBe(2); - await runProvenSideWork({ source, provenTip: 3, ...cursors }); + 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({ source, provenTip: 2, ...cursors }); + const run = () => runProvenSideWork(depsOf(source, 2, cursors)); await run(); const first = balances(); diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index 7f0b3e039..f81d28c3d 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -178,6 +178,13 @@ describe("block poller pass", () => { }); 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); From 72b39fbd0a92d29dcd3b81fa68b242890fae149b Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:31:21 +0000 Subject: [PATCH 08/31] fix(aztec-listener): fail the pass when a stream handler fails The SDK block stream catches a handler's error, logs it and resolves, so a pass whose send or store write failed went on to publish tips and run the proven side work. ChainPublisher now keeps the first such error of a pass, ends the pass quietly for the stream, and rethrows the error from finishPass(), after sync() and before any post-pass work. A pass that ends on the prefix rule, or on a rejected event, stays quiet. Co-Authored-By: Claude Opus 5.5 --- .../pollers/block_poller/chain-publisher.ts | 27 ++++++++++++++++++- .../pollers/block_poller/stream-logger.ts | 2 +- .../tests/unit/block-poller.test.ts | 9 +++---- .../tests/unit/chain-publisher.test.ts | 2 +- 4 files changed, 32 insertions(+), 8 deletions(-) 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 index 93082caed..fd5cdc1e1 100644 --- 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 @@ -65,6 +65,7 @@ const tiersOrdered = ({ proposed, checkpointed, proven, finalized }: L2Tips) => export class ChainPublisher implements L2BlockStreamEventHandler { private prefixWait: { since: number; alertedAt?: number } | undefined; private endedOnPrefix = false; + private failure: Error | undefined; private readonly now: () => number; constructor( @@ -80,16 +81,40 @@ export class ChainPublisher implements L2BlockStreamEventHandler { /** Call before each pass's `sync()`. */ startPass(): void { this.endedOnPrefix = false; + this.failure = undefined; } - /** Call after each pass's `sync()`; a pass that did not end on the prefix rule ends the wait. */ + /** + * 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 as Error).name === "AbortError") { + throw e; + } + // The stream would only log it and end the pass; finishPass() rethrows it. + const error = e instanceof Error ? e : new Error(String(e)); + this.failure ??= error; + throw new AbortError(error.message, { cause: error }); + } + } + + private handle(event: L2BlockStreamEvent): Promise { switch (event.type) { case "blocks-added": return this.addBlocks(event.blocks); 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 index 45036923b..5d032f11c 100644 --- 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 @@ -14,7 +14,7 @@ const line = (msg: string, ...data: unknown[]) => /** * The SDK block stream's logger, routed to the listener's. The stream reports - * a handler's failure only here, so it must not go to the SDK's own output. + * its own failures only here, so they must not go to the SDK's own output. */ export const streamLogger: SdkLogger = { silent: () => undefined, diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index f81d28c3d..c48183055 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -153,18 +153,17 @@ describe("block poller pass", () => { }); }); - it("logs a failed send through the listener's logger and publishes no tips", async () => { + it("fails the pass on a failed send, before any post-pass work", async () => { const x = new FakeNode("x", prefix(main, 3)); const { chain } = chainOver([x], () => Promise.reject(new Error("broker down")), ); - await runPass(chain); + await expect(runPass(chain)).rejects.toThrow("broker down"); - expect(logger.error).toHaveBeenCalledWith( - expect.stringMatching(/^Error processing block stream .*broker down/s), - ); expect(mocks.publishTipsIfDue).not.toHaveBeenCalled(); + expect(runProvenSideWork).not.toHaveBeenCalled(); + expect(logger.error).not.toHaveBeenCalled(); }); 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 () => { diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index 83d68712e..53b7b80b1 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -177,7 +177,7 @@ describe("ChainPublisher after the node replaces published heights", () => { x.chain = prefix(main, 9); failing.add(7); - await pass(); + await expect(pass()).rejects.toThrow("send rejected"); expect(sent).toEqual(sentOf(main, [6], 9)); expect((await head()).number).toBe(6); From 29dccd40ef9c1d075442b4917d98d8d494b74190 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:33:59 +0000 Subject: [PATCH 09/31] fix(aztec-listener): keep the legacy proposed height on the store's tip Nothing in this listener reads heights.processedProposedBlockHeight; the listener's previous version resumes from it after a rollback. It was written only by a pass that moved the store's tip, so a pass that failed after storing blocks left it behind for good. Each pass now writes the store's proposed tip whenever the stored height differs, before it publishes tips. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/index.ts | 16 +++++--- .../tests/unit/block-poller.test.ts | 40 +++++++++++++++---- .../tests/unit/full-sweep-catchup.test.ts | 2 + 3 files changed, 45 insertions(+), 13 deletions(-) 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 485b1424b..945d6f0be 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 @@ -137,7 +137,7 @@ const readProvenCursor = async () => (await getBlockHeights()).processedProvenBlockHeight; /** - * One pass: the election and the stream, then the tips, the heights, the + * 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. @@ -173,15 +173,19 @@ export const runPass = async ({ } } 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. + if ( + (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); } - const moved = after.proposed.number !== before.proposed.number; - if (moved) { - await storeProcessedProposedBlockHeight(after.proposed.number); - } if (settled && !AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS) { await runProvenSideWork({ source, @@ -193,7 +197,7 @@ export const runPass = async ({ storeCursor: storeProcessedProvenBlockHeight, }); } - if (!moved) { + if (after.proposed.number === before.proposed.number) { await sweepOnce(after.proposed.number, rollupVersion); } }; diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index c48183055..8d3e18be5 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -21,13 +21,20 @@ import { tipsOf, } from "./support/chain.js"; -const mocks = vi.hoisted(() => ({ - publishTipsIfDue: vi.fn(), - storeProcessedProposedBlockHeight: vi.fn(), - readLatestRollupVersion: vi.fn(), - readGenesisBlockHash: vi.fn(), - stores: [] as { version: number; genesis: unknown }[], -})); +const mocks = vi.hoisted(() => { + const heights = { processedProposedBlockHeight: 0 }; + return { + heights, + 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(), @@ -50,6 +57,7 @@ vi.mock("../../src/svcs/poller/pollers/l2-tips-poller.js", () => ({ vi.mock("../../src/svcs/database/heights.controller.js", () => ({ getBlockHeights: () => Promise.resolve({ + processedProposedBlockHeight: mocks.heights.processedProposedBlockHeight, processedProvenBlockHeight: 0, chainProvenBlockHeight: 0, }), @@ -93,6 +101,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); + mocks.heights.processedProposedBlockHeight = 0; }); const chainOver = ( @@ -192,6 +201,23 @@ describe("block poller pass", () => { 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("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 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 0f76fa26b..83273f877 100644 --- a/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts +++ b/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts @@ -55,6 +55,8 @@ describe("block poller full sweep", () => { onOrderedBlock: vi.fn(), })); vi.doMock("../../src/svcs/database/heights.controller.js", () => ({ + getBlockHeights: () => + Promise.resolve({ processedProposedBlockHeight: 3 }), storeProcessedProposedBlockHeight, })); vi.doMock("../../src/svcs/poller/network-client/attested-reads.js", () => ({ From 34c09db7f8e4dda97bdb3be2f0faf1e659865f80 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:35:31 +0000 Subject: [PATCH 10/31] docs(aztec-listener): trim comments that restate the code ChainPublisher's doc keeps its one invariant, the prefix wait and the tips publisher lose comments that narrate their code, and the stream logger's names only bigints, since field elements implement toJSON. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/chain-publisher.ts | 7 +------ .../src/svcs/poller/pollers/block_poller/stream-logger.ts | 2 +- .../src/svcs/poller/pollers/l2-tips-poller.ts | 1 - 3 files changed, 2 insertions(+), 8 deletions(-) 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 index fd5cdc1e1..6b90f0cbe 100644 --- 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 @@ -57,11 +57,7 @@ const tiersOrdered = ({ proposed, checkpointed, proven, finalized }: L2Tips) => proven.block.number <= checkpointed.block.number && checkpointed.block.number <= proposed.number; -/** - * The block stream's handler. It checks each event against the store and the - * pass's snapshot, publishes blocks before it stores them, and stores what it - * accepts. A rejected event sets the pinned node aside and ends the pass. - */ +/** The block stream's handler: it stores a block only once the block is sent. */ export class ChainPublisher implements L2BlockStreamEventHandler { private prefixWait: { since: number; alertedAt?: number } | undefined; private endedOnPrefix = false; @@ -323,7 +319,6 @@ export class ChainPublisher implements L2BlockStreamEventHandler { throw new AbortError(message); } - // Warns on entering the wait, not on each pass, and alerts on a timer. private notePrefixWait(target: number, stored: number) { const now = this.now(); const entering = this.prefixWait === undefined; 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 index 5d032f11c..d4e0b70b1 100644 --- 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 @@ -6,7 +6,7 @@ import { logger } from "../../../../logger.js"; // character class keeps a trailing colon or period out of the match. const URL_PATTERN = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*[^\s"'<>.,:;)]/gi; -// The stream's data carries bigints and field elements, which JSON rejects. +// The stream's data carries bigints, which JSON rejects. const line = (msg: string, ...data: unknown[]) => [msg, ...data.filter((d) => d !== undefined).map((d) => inspect(d))] .join(" ") 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 b7d2c1fd7..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 @@ -63,7 +63,6 @@ const normalizeTips = (tips: RawL2Tips): ChicmozL2Tips => finalized: normalizeCheckpointTip(tips.finalized), }); -/** Publishes `raw` unless it equals the last tips published and the heartbeat is not due. */ export const publishTipsIfDue = async (raw: L2Tips) => { const tips = normalizeTips(raw as unknown as RawL2Tips); const serialized = jsonStringify(tips); From 03460cb8bd1b51f76a38007e5eb9251024159876 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 00:43:41 +0000 Subject: [PATCH 11/31] test(network-smoke): reconcile missing blocks every 5 s The listener's block stream starts an empty store at the finalized block, so a fresh explorer-api gets the blocks below it only through its block reconciliation. When the API's startup reconciliation runs before any block has arrived it has no upper bound and skips, and the next request came on the 120 s default cadence, at the edge of the 120 s wait for block 1. The run's explorer-api now reconciles every 5 s. Co-Authored-By: Claude Opus 5.5 --- services/network-smoke/src/services.ts | 3 +++ 1 file changed, 3 insertions(+) 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", From 54705b6bb961a653bcf56b1e7e80f630f860b08c Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:12:21 +0000 Subject: [PATCH 12/31] fix(aztec-listener): redact URLs in a failed pass's log A handler failure from a node read reaches the poll loop through finishPass(), which logged its stack raw. The loop now logs the error through inspect(), so its cause is included, and through the stream logger's URL redaction. File URLs are left alone, as Node prints an ES module's stack frames as file URLs. The loop's pass is exported as pollOnce() to test that path. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/index.ts | 19 ++++++++--- .../pollers/block_poller/stream-logger.ts | 17 +++++++--- .../tests/unit/block-poller.test.ts | 33 +++++++++++++++++++ 3 files changed, 60 insertions(+), 9 deletions(-) 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 945d6f0be..6d72c4862 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,3 +1,4 @@ +import { inspect } from "node:util"; import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { L2BlockStream, @@ -40,7 +41,7 @@ import { 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"; +import { redactUrls, streamLogger } from "./stream-logger.js"; /** One rollup version's block stream. */ export type StreamChain = { @@ -202,14 +203,24 @@ export const runPass = async ({ } }; -const tick = async () => { +/** One poll: the pass of the stream `chain` gives, logging its failure. */ +export const pollOnce = async ( + chain: () => Promise = currentChain, +) => { try { - await runPass(await currentChain()); + await runPass(await chain()); } catch (e) { // A read with no node pinned; the next pass elects one. if ((e as Error).name !== "AbortError") { - logger.error(`🐻 block stream pass failed: ${(e as Error).stack}`); + // A node read's error names the node's URL; inspect() adds the cause. + logger.error(`🐻 block stream pass failed: ${redactUrls(inspect(e))}`); } + } +}; + +const tick = async () => { + try { + await pollOnce(); } finally { if (!cancelPolling) { timeoutId = setTimeout(() => void tick(), BLOCK_POLL_INTERVAL_MS); 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 index d4e0b70b1..be40b362e 100644 --- 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 @@ -3,14 +3,21 @@ import { type Logger as SdkLogger } from "@aztec-labs/foundation/log"; import { logger } from "../../../../logger.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. -const URL_PATTERN = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]*[^\s"'<>.,:;)]/gi; +// 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; + +/** `text` with each URL replaced by ``, but for a file URL. */ +export const redactUrls = (text: string) => text.replace(URL_PATTERN, ""); // The stream's data carries bigints, which JSON rejects. const line = (msg: string, ...data: unknown[]) => - [msg, ...data.filter((d) => d !== undefined).map((d) => inspect(d))] - .join(" ") - .replace(URL_PATTERN, ""); + 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 diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index 8d3e18be5..7d22d05a5 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -5,6 +5,7 @@ import { StickySource } from "../../src/svcs/poller/network-client/block-stream- 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"; @@ -18,6 +19,7 @@ import { memoryStore, prefix, readerOf, + respond, tipsOf, } from "./support/chain.js"; @@ -175,6 +177,37 @@ describe("block poller pass", () => { expect(logger.error).not.toHaveBeenCalled(); }); + 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 url = "https://user:secret@node.example/v1/key123?apikey=key456"; + const failure = new Error(`Error fetching from host ${url}: fetch failed`, { + cause: new Error(`connect ECONNREFUSED ${url}`), + }); + // 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 "); + expect(line).not.toMatch(/secret|key123|key456|node\.example/); + }); + 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]); From a867f8f6caf37e34aa3f79f12732663d20cff331 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:16:05 +0000 Subject: [PATCH 13/31] fix(aztec-listener): confirm a proposed tip against the store's tip The handler accepted the stream's proposed tip when the store held the same hash at that height. A prune writes each tier it lowers, hash included, before any block of the pass is sent, so after an interrupted prune that hash can sit above the stored tip; a later pass that downloads nothing would then move the tip over unsent blocks. The handler now requires the store's tip to already equal the event, which every valid pass has reached through its blocks, and writes nothing. The tier-order check moves from the handler to the stream source's snapshot checks, so the election and every pass refuse tips out of order before any block is read. The handler's check could no longer fire. Co-Authored-By: Claude Opus 5.5 --- .../network-client/block-stream-source.ts | 18 +- .../pollers/block_poller/chain-publisher.ts | 26 +-- .../tests/unit/block-stream-source.test.ts | 28 +++ .../tests/unit/chain-publisher.test.ts | 217 ++++++++---------- 4 files changed, 151 insertions(+), 138 deletions(-) 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 949aebba8..e0815bb6b 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 @@ -75,7 +75,7 @@ type Bench = { until: number } | { tip: L2BlockId }; 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; }; @@ -95,12 +95,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 { 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 index 6b90f0cbe..693a3854b 100644 --- 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 @@ -52,11 +52,6 @@ export type ChainPublisherConfig = { prefixAlertMs: number; }; -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 block stream's handler: it stores a block only once the block is sent. */ export class ChainPublisher implements L2BlockStreamEventHandler { private prefixWait: { since: number; alertedAt?: number } | undefined; @@ -220,7 +215,6 @@ export class ChainPublisher implements L2BlockStreamEventHandler { alert: true, }); } - this.checkOrder(snapshot); // 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. @@ -251,23 +245,23 @@ export class ChainPublisher implements L2BlockStreamEventHandler { } // The stream reports the snapshot's tip even when it downloaded nothing up - // to it, as from a `startingBlock` past that tip; the store would then hold - // a tip whose block was never sent. + // 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 ( - (await this.deps.store.getL2BlockHash(event.block.number)) !== - event.block.hash + 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 AbortError(); } - await this.deps.store.handleBlockStreamEvent(event); } private async moveTier(event: TierEvent) { - this.checkOrder(this.snapshot()); // 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); @@ -284,14 +278,6 @@ export class ChainPublisher implements L2BlockStreamEventHandler { await this.deps.store.handleBlockStreamEvent(event); } - private checkOrder(snapshot: L2Tips) { - if (!tiersOrdered(snapshot)) { - this.reject({ - reason: `sent tips out of order: proposed ${snapshot.proposed.number}, checkpointed ${snapshot.checkpointed.block.number}, proven ${snapshot.proven.block.number}, finalized ${snapshot.finalized.block.number}`, - }); - } - } - private async checkStored(tier: string, block: L2BlockId) { if ((await this.deps.store.getL2BlockHash(block.number)) !== block.hash) { this.reject({ 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 556b414a5..4d1765d07 100644 --- a/services/aztec-listener/tests/unit/block-stream-source.test.ts +++ b/services/aztec-listener/tests/unit/block-stream-source.test.ts @@ -540,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)); diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index 53b7b80b1..63c24eea2 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -1,4 +1,7 @@ -import { BlockNumber } from "@aztec-labs/foundation/branded-types"; +import { + BlockNumber, + CheckpointNumber, +} from "@aztec-labs/foundation/branded-types"; import { type BlockHash, type L2Block, @@ -13,6 +16,7 @@ import { ROLLUP_VERSION, blocksFrom, chainOf, + checkpointHash, emptyBlock, genesisChain, grow, @@ -329,18 +333,34 @@ describe("ChainPublisher checks", () => { }, ); - it("stores no proposed tip that the pass did not send", async () => { - const x = new FakeNode("x", prefix(main, 4)); - x.tiers = { checkpointed: 4, proven: 4, finalized: 4 }; - const { sent, pass, head } = setup({ nodes: [x] }); + 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); + // 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()).number).toBe(0); - expect(loggedTimes(logger.warn, "which this pass did not send")).toBe(1); - }); + 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)); @@ -360,114 +380,81 @@ describe("ChainPublisher checks", () => { expect(loggedTimes(logger.error, "asks to prune to block 0")).toBe(1); }); - it.each([ - { - fault: "a proven tip off the stored chain", - reason: "has another block at its proven height 6", - tips: () => { - const tips = tipsOf(prefix(main, 10), { - checkpointed: 10, - proven: 6, - finalized: 4, - }); - return { - ...tips, - proven: { - ...tips.proven, - block: { number: BlockNumber(6), hash: main.hashes[5] }, - }, - }; - }, - }, - { - fault: "tiers out of order", - reason: "sent tips out of order", - tips: () => - tipsOf(prefix(main, 10), { checkpointed: 5, proven: 6, finalized: 4 }), - }, - ])( - "stores no tier from a snapshot with $fault, sets the node aside, and follows an honest node", - async ({ reason, tips }) => { - 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 = tips; - 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, reason)).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(); - 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], - }); - }, - ); + 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], + }); + }); - // The node forks from block 5, below the stored proven tip 6 and above the - // stored finalized tip 4. - it.each([ - { - fault: "another block 4 as its proven tip", - reason: "has another block at its proven height 4", - tiers: { checkpointed: 9, proven: 4, finalized: 4 }, - provenHash: () => main.hashes[3], - }, - { - fault: "tiers out of order", - reason: "sent tips out of order", - tiers: { checkpointed: 6, proven: 7, finalized: 4 }, - provenHash: undefined, - }, - ])( - "stores nothing from a prune with $fault, sets the node aside, and follows an honest node", - async ({ reason, tiers, provenHash }) => { - 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; - const fork = await grow(prefix(main, 5), 9); - x.chain = fork; - x.chainTipsOverride = () => { - const tips = tipsOf(fork, tiers); - return provenHash === undefined - ? tips - : { - ...tips, - proven: { - ...tips.proven, - block: { ...tips.proven.block, hash: provenHash() }, - }, - }; + 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(); + }; + 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, reason)).toBe(1); - world.online = [x, y]; - expect(await pass()).toBe(y.rpc); - }, - ); + 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([ { From 716414541f4405d2fef3ea326fd496e18811e9a1 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:20:03 +0000 Subject: [PATCH 14/31] docs(aztec-listener): note the side work's trust below finality Below the store's finalized tip there is no stored hash to compare, so the proven side work takes the pinned node's block as it is served. Co-Authored-By: Claude Opus 5.5 --- .../src/svcs/poller/pollers/block_poller/proven-side-work.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 index f2a9e49f4..5856173f2 100644 --- 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 @@ -24,7 +24,8 @@ export type ProvenSideWorkDeps = { }; // The node can serve another block at a height once the pass has settled. -// Below the finalized tip the store keeps no hash, and a block cannot change. +// 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, From f6ff9f7fab4798432188af8829b0d638cc2501a1 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:24:35 +0000 Subject: [PATCH 15/31] fix(aztec-listener): end a pass on its own exit type only The handler and the poll loop took any error named AbortError for an intentional end of the pass. One from a dependency, such as the send, was rethrown unrecorded; the stream dropped it, and the pass went on to write the legacy height and sweep as if it had succeeded. The stream source and the handler now throw PassExit, an AbortError subclass, so the SDK's stream still ends the pass without logging. Only that type is an exit: any other error, an AbortError included, is recorded, rethrown after the pass and logged. Co-Authored-By: Claude Opus 5.5 --- .../network-client/block-stream-source.ts | 15 +++-- .../pollers/block_poller/chain-publisher.ts | 23 ++++--- .../svcs/poller/pollers/block_poller/index.ts | 3 +- .../tests/unit/block-poller.test.ts | 64 ++++++++++++++++--- 4 files changed, 80 insertions(+), 25 deletions(-) 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 e0815bb6b..f4d7545c6 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 @@ -44,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" @@ -371,7 +378,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; @@ -399,7 +406,7 @@ export class StickySource implements L2BlockStreamSource { ): Promise>> { const pin = this.pin; if (pin === undefined) { - throw new AbortError(); + throw new PassExit(); } return this.boundedCall(pin, fnName, args); } @@ -504,7 +511,7 @@ export class StickySource implements L2BlockStreamSource { ) { const pin = this.pin; if (pin === undefined) { - throw new AbortError(); + throw new PassExit(); } try { return { pin, result: await this.boundedCall(pin, fnName, args) }; @@ -558,7 +565,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`); } 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 index 693a3854b..624c09e74 100644 --- 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 @@ -1,5 +1,4 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; -import { AbortError } from "@aztec-labs/foundation/error"; import { type L2Block, type L2BlockId, @@ -13,7 +12,10 @@ import { AZTEC_STREAM_PREFIX_ALERT_MS, } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; -import { type StickySource } from "../../network-client/block-stream-source.js"; +import { + PassExit, + type StickySource, +} from "../../network-client/block-stream-source.js"; type PruneEvent = Extract; type ProposedEvent = Extract; @@ -95,13 +97,14 @@ export class ChainPublisher implements L2BlockStreamEventHandler { try { await this.handle(event); } catch (e) { - if ((e as Error).name === "AbortError") { + if (e instanceof PassExit) { throw e; } - // The stream would only log it and end the pass; finishPass() rethrows it. + // 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 AbortError(error.message, { cause: error }); + throw new PassExit(error.message, { cause: error }); } } @@ -176,7 +179,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { // 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 AbortError(); + throw new PassExit(); } if ((await parent.header.hash()).toString() !== stored) { return { @@ -201,7 +204,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { this.endedOnPrefix = true; this.notePrefixWait(target.number, local.proposed.number); this.deps.source.endPassOnPrefix(); - throw new AbortError(); + throw new PassExit(); } const [atTarget, above] = await Promise.all([ this.deps.store.getL2BlockHash(target.number), @@ -231,7 +234,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { 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 AbortError(); + throw new PassExit(); } const provenBack = event.proven.block.number < local.proven.block.number; await this.deps.transaction(async () => { @@ -257,7 +260,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { logger.warn( `Node ${this.pinnedName()} has proposed tip ${event.block.number}, which this pass did not send; the pass ends`, ); - throw new AbortError(); + throw new PassExit(); } } @@ -302,7 +305,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { logger.error(message); } this.deps.source.setAsidePinned(message); - throw new AbortError(message); + throw new PassExit(message); } private notePrefixWait(target: number, stored: number) { 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 6d72c4862..851afcfed 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 @@ -30,6 +30,7 @@ import { PostgresL2TipsStore } from "../../../database/l2-tips-store.js"; import { inTransaction } from "../../../database/transaction.js"; import { openAttestedReader } from "../../network-client/attested-reads.js"; import { + PassExit, StickySource, readGenesisBlockHash, } from "../../network-client/block-stream-source.js"; @@ -211,7 +212,7 @@ export const pollOnce = async ( await runPass(await chain()); } catch (e) { // A read with no node pinned; the next pass elects one. - if ((e as Error).name !== "AbortError") { + 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))}`); } diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index 7d22d05a5..431fedbc1 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -1,3 +1,4 @@ +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"; @@ -27,6 +28,10 @@ const mocks = vi.hoisted(() => { const heights = { processedProposedBlockHeight: 0 }; return { heights, + sweep: false, + openAttestedReader: vi.fn(() => + Promise.resolve({ getBlock: () => Promise.resolve(undefined) }), + ), publishTipsIfDue: vi.fn(), storeProcessedProposedBlockHeight: vi.fn((height: number) => { heights.processedProposedBlockHeight = height; @@ -45,6 +50,24 @@ const logger = vi.hoisted(() => ({ })); vi.mock("../../src/logger.js", () => ({ logger })); +vi.mock("../../src/environment.js", async (importOriginal) => ({ + ...(await importOriginal()), + 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(), @@ -104,6 +127,7 @@ beforeAll(async () => { beforeEach(() => { vi.clearAllMocks(); mocks.heights.processedProposedBlockHeight = 0; + mocks.sweep = false; }); const chainOver = ( @@ -164,18 +188,38 @@ describe("block poller pass", () => { }); }); - it("fails the pass on a failed send, before any post-pass work", async () => { - const x = new FakeNode("x", prefix(main, 3)); - const { chain } = chainOver([x], () => - Promise.reject(new Error("broker down")), - ); + 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.toThrow("broker down"); + await expect(runPass(chain)).rejects.toBe(failure); - expect(mocks.publishTipsIfDue).not.toHaveBeenCalled(); - expect(runProvenSideWork).not.toHaveBeenCalled(); - expect(logger.error).not.toHaveBeenCalled(); - }); + 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)); From e605df8b20802c0b4e978caa7e7c8044713b9126 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:26:58 +0000 Subject: [PATCH 16/31] fix(aztec-listener): keep the legacy proposed height until the store has a block A pass that elects no node, or follows one at block 0, leaves the new store empty, and the listener wrote its tip, 0, over the previous version's proposed height. After a rollback that version lifts a 0 to the chain's proven height and sends again the blocks it had sent above it. The height is now written only once the store holds a block. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/index.ts | 7 +++++-- .../tests/unit/block-poller.test.ts | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) 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 851afcfed..2e160b1f1 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 @@ -176,10 +176,13 @@ export const runPass = async ({ } 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. + // 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 ( + after.proposed.number > 0 && (await getBlockHeights()).processedProposedBlockHeight !== - after.proposed.number + after.proposed.number ) { await storeProcessedProposedBlockHeight(after.proposed.number); } diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index 431fedbc1..e22c4d213 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -295,6 +295,25 @@ describe("block poller pass", () => { ]); }); + 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 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 From 066d5aa72fa17d76161ed766322121f5443e5916 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:37:51 +0000 Subject: [PATCH 17/31] fix(aztec-listener): call a store empty only when it holds no block A store started at the snapshot's finalized block whenever its proposed tip was 0. A prune to block 0 leaves the tip at 0 over the hashes above it, so after such a prune whose first send failed, the next pass skipped the new chain's blocks below its finalized block. A store is now empty only when it holds no block hash at or above 1, and the next pass starts at block 1. The legacy proposed height waits on the same predicate, so a store pruned to block 0 writes its tip there. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/pollers/block_poller/index.ts | 21 ++++++---- .../tests/unit/block-poller.test.ts | 39 +++++++++++++++++++ .../tests/unit/full-sweep-catchup.test.ts | 1 + 3 files changed, 53 insertions(+), 8 deletions(-) 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 2e160b1f1..9256025c8 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,10 +1,6 @@ import { inspect } from "node:util"; import { BlockNumber } from "@aztec-labs/foundation/branded-types"; -import { - L2BlockStream, - type L2TipsStoreBase, - localTipsMatch, -} from "@aztec-labs/stdlib/block"; +import { L2BlockStream, localTipsMatch } from "@aztec-labs/stdlib/block"; import { AZTEC_BLOCK_STREAM_BATCH_SIZE, AZTEC_DISABLE_LISTEN_FOR_PROPOSED_BLOCKS, @@ -30,6 +26,7 @@ import { PostgresL2TipsStore } from "../../../database/l2-tips-store.js"; import { inTransaction } from "../../../database/transaction.js"; import { openAttestedReader } from "../../network-client/attested-reads.js"; import { + type ElectionStore, PassExit, StickySource, readGenesisBlockHash, @@ -47,11 +44,19 @@ import { redactUrls, streamLogger } from "./stream-logger.js"; /** One rollup version's block stream. */ export type StreamChain = { rollupVersion: number; - store: Pick; + 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 started = false; let cancelPolling = false; let timeoutId: ReturnType | undefined; @@ -153,7 +158,7 @@ export const runPass = async ({ const before = await store.getL2Tips(); if ((await source.elect()) !== undefined) { publisher.startPass(); - const empty = before.proposed.number === 0; + const empty = !(await holdsBlocks(store)); try { await new L2BlockStream( source, @@ -180,7 +185,7 @@ export const runPass = async ({ // 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 ( - after.proposed.number > 0 && + (await holdsBlocks(store)) && (await getBlockHeights()).processedProposedBlockHeight !== after.proposed.number ) { diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index e22c4d213..efed9450a 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -1,3 +1,4 @@ +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"; @@ -159,6 +160,23 @@ const chainOver = ( }; }; +/** 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)); @@ -314,6 +332,27 @@ describe("block poller pass", () => { }, ); + 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 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 83273f877..9f3ad0905 100644 --- a/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts +++ b/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts @@ -76,6 +76,7 @@ describe("block poller full sweep", () => { store: { getL2Tips: () => Promise.resolve({ proposed: { number: tips.shift() ?? 3 } }), + holdsHashAtOrAbove: () => Promise.resolve(true), }, source: { elect: () => Promise.resolve(undefined) }, publisher: {}, From 051d15e3512796e72df45e4885e05733b1f44ba2 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:55:53 +0000 Subject: [PATCH 18/31] fix(aztec-listener): redact URLs in the node client's errors The SDK's fetch names the node's URL in the errors it throws, and the listener logs those errors from many places: the poll loop, the stream source's election, node info, validator stats and the RPC-node error event. The pool's client now wraps the fetch so that every error it throws has its URLs redacted, in place, before the SDK client or any caller sees it. The offline markers that callNodeFunction looks for name no URL and stay. The redaction moves to network-client/redact-urls.ts, and the rollup version and proven side work warnings go through it too. The RPC-node error event's message, cause and stack are now redacted as well. Co-Authored-By: Claude Opus 5.5 --- .../src/svcs/poller/network-client/pool.ts | 24 +++- .../svcs/poller/network-client/redact-urls.ts | 23 +++ .../poller/network-client/rollup-version.ts | 3 +- .../svcs/poller/pollers/block_poller/index.ts | 3 +- .../pollers/block_poller/proven-side-work.ts | 3 +- .../pollers/block_poller/stream-logger.ts | 10 +- .../tests/unit/node-client.test.ts | 131 ++++++++++++++++++ 7 files changed, 182 insertions(+), 15 deletions(-) create mode 100644 services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts create mode 100644 services/aztec-listener/tests/unit/node-client.test.ts 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..35f598fa2 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,25 @@ export const withV5NodeNamespaceFallback = return await send(host, rewrittenBody, extraHeaders, noRetry); }; +// The SDK's fetch names the node's URL in its errors, and its client logs a +// failed fetch's error through the SDK's logger before any caller sees it. +// The offline markers callNodeFunction looks for in the message name no URL. +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 +137,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..f60562c39 --- /dev/null +++ b/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts @@ -0,0 +1,23 @@ +// 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; + +/** `text` with each URL replaced by ``, but for a file URL. */ +export const redactUrls = (text: string) => text.replace(URL_PATTERN, ""); + +/** + * `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 index 3c3be397e..5fc2a9a6f 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/rollup-version.ts @@ -3,6 +3,7 @@ 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 }; @@ -32,7 +33,7 @@ export const readLatestRollupVersion = async ( : undefined; } catch (e) { logger.info( - `Node ${node.name} reported no rollup version: ${(e as Error).message}`, + `Node ${node.name} reported no rollup version: ${redactUrls((e as Error).message)}`, ); return undefined; } 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 9256025c8..9edab3076 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 @@ -32,6 +32,7 @@ import { 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, @@ -39,7 +40,7 @@ import { import { publishTipsIfDue } from "../l2-tips-poller.js"; import { ChainPublisher } from "./chain-publisher.js"; import { runProvenSideWork } from "./proven-side-work.js"; -import { redactUrls, streamLogger } from "./stream-logger.js"; +import { streamLogger } from "./stream-logger.js"; /** One rollup version's block stream. */ export type StreamChain = { 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 index 5856173f2..5e8964dcb 100644 --- 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 @@ -6,6 +6,7 @@ import { } 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, @@ -83,7 +84,7 @@ export const runProvenSideWork = async ( const outcome = await handleProvenTransactions(block, readStorage); if (!outcome.ok) { logger.warn( - `Proven side work stopped at block ${block.number}, which the next pass retries: ${outcome.error.message}`, + `Proven side work stopped at block ${block.number}, which the next pass retries: ${redactUrls(outcome.error.message)}`, ); return; } 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 index be40b362e..ec2fef427 100644 --- 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 @@ -1,15 +1,7 @@ import { inspect } from "node:util"; import { type Logger as SdkLogger } from "@aztec-labs/foundation/log"; import { logger } from "../../../../logger.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; - -/** `text` with each URL replaced by ``, but for a file URL. */ -export const redactUrls = (text: string) => text.replace(URL_PATTERN, ""); +import { redactUrls } from "../../network-client/redact-urls.js"; // The stream's data carries bigints, which JSON rejects. const line = (msg: string, ...data: unknown[]) => 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..b344266a5 --- /dev/null +++ b/services/aztec-listener/tests/unit/node-client.test.ts @@ -0,0 +1,131 @@ +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 { 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); + +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, + ); + }); +}); From 7770f04f650afe6c2e8264f1499079ab112a0d53 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 01:58:57 +0000 Subject: [PATCH 19/31] fix(aztec-listener): redact the node pool's URLs exactly before the pattern The generic URL pattern stops at an apostrophe, which a path can hold, so the rest of such a URL stayed in the text. The redactor now first replaces each AZTEC_RPC_URLS entry and its parts, longest first: the URL as configured and its href, host, hostname, path, query, user and password, raw and decoded, and each path segment and query value of 8 characters or more. The generic pattern then runs as before, and file URLs still stay. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/network-client/redact-urls.ts | 75 ++++++++++++++++++- .../tests/unit/block-poller.test.ts | 22 ++++-- 2 files changed, 89 insertions(+), 8 deletions(-) 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 index f60562c39..8535bfdaf 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts @@ -1,11 +1,82 @@ +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; -/** `text` with each URL replaced by ``, but for a file URL. */ -export const redactUrls = (text: string) => text.replace(URL_PATTERN, ""); +// 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); + const exact = + parts.length === 0 + ? undefined + : new RegExp( + parts.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), + "gi", + ); + 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 diff --git a/services/aztec-listener/tests/unit/block-poller.test.ts b/services/aztec-listener/tests/unit/block-poller.test.ts index efed9450a..56503ca51 100644 --- a/services/aztec-listener/tests/unit/block-poller.test.ts +++ b/services/aztec-listener/tests/unit/block-poller.test.ts @@ -29,6 +29,9 @@ 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) }), @@ -53,6 +56,7 @@ const logger = vi.hoisted(() => ({ 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; }, @@ -244,10 +248,14 @@ describe("block poller pass", () => { const { chain } = chainOver([x]); await runPass(chain); x.chain = prefix(main, 5); - const url = "https://user:secret@node.example/v1/key123?apikey=key456"; - const failure = new Error(`Error fetching from host ${url}: fetch failed`, { - cause: new Error(`connect ECONNREFUSED ${url}`), - }); + 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. @@ -266,8 +274,10 @@ describe("block poller pass", () => { 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 "); - expect(line).not.toMatch(/secret|key123|key456|node\.example/); + 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 () => { From 5c51c4d5addcbff1587f31188eb546c78296ae87 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:14:26 +0000 Subject: [PATCH 20/31] fix(aztec-listener): match the node pool's URL parts case-sensitively The redactor replaced each part of the pool's URLs ignoring case, so a host named `gateway` turned "Bad Gateway" into "Bad " in every node's errors, and callNodeFunction no longer set a node offline on that answer. The parts now match as written: an error names a part as configured or as the URL parser normalized it, and the redactor lists both. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/network-client/redact-urls.ts | 5 ++- .../tests/unit/node-client.test.ts | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) 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 index 8535bfdaf..9ce2e9609 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/redact-urls.ts @@ -61,12 +61,15 @@ 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("|"), - "gi", + "g", ); return (text: string) => (exact === undefined ? text : text.replace(exact, "")).replace( diff --git a/services/aztec-listener/tests/unit/node-client.test.ts b/services/aztec-listener/tests/unit/node-client.test.ts index b344266a5..2974ecb9b 100644 --- a/services/aztec-listener/tests/unit/node-client.test.ts +++ b/services/aztec-listener/tests/unit/node-client.test.ts @@ -29,6 +29,10 @@ const events = vi.hoisted(() => ({ })); 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[] = []; @@ -128,4 +132,33 @@ describe("node client", () => { 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"); + }); }); From cb12dcb78664a4476a5985e779158616b03bfb8e Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:15:59 +0000 Subject: [PATCH 21/31] fix(aztec-listener): redact URLs in the election probe's errors Node's fetch refuses a URL with userinfo and names the whole URL in its error, and the election logs that error's message when a probe fails. Such a URL never works, but it can be configured by mistake. The probe's client now wraps its fetch like the pool's, so its errors have their URLs redacted before the SDK client or the election sees them. Co-Authored-By: Claude Opus 5.5 --- .../svcs/poller/network-client/election-probe.ts | 12 +++++++++--- .../src/svcs/poller/network-client/pool.ts | 11 +++++++---- .../tests/unit/node-client.test.ts | 16 ++++++++++++++++ 3 files changed, 32 insertions(+), 7 deletions(-) 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/pool.ts b/services/aztec-listener/src/svcs/poller/network-client/pool.ts index 35f598fa2..8480cc601 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/pool.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/pool.ts @@ -100,10 +100,13 @@ export const withV5NodeNamespaceFallback = return await send(host, rewrittenBody, extraHeaders, noRetry); }; -// The SDK's fetch names the node's URL in its errors, and its client logs a -// failed fetch's error through the SDK's logger before any caller sees it. -// The offline markers callNodeFunction looks for in the message name no URL. -const withRedactedErrors = +/** + * `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 { diff --git a/services/aztec-listener/tests/unit/node-client.test.ts b/services/aztec-listener/tests/unit/node-client.test.ts index 2974ecb9b..0c70455ac 100644 --- a/services/aztec-listener/tests/unit/node-client.test.ts +++ b/services/aztec-listener/tests/unit/node-client.test.ts @@ -11,6 +11,7 @@ import { 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"; @@ -161,4 +162,19 @@ describe("node client", () => { ]; 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); + }); }); From 0e670e9a0e67d68aba191cdfe71f99c662838e4e Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 02:17:45 +0000 Subject: [PATCH 22/31] fix(aztec-listener): print only each pool URL's origin at startup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The startup config printed each pool entry's URL whole. It now prints the entry's name and the URL's scheme, host and port, with "/…" when the URL has a path or query, and never its userinfo, path or query. The print predates the block stream. Co-Authored-By: Claude Opus 5.5 --- services/aztec-listener/src/environment.ts | 12 +++++++- .../tests/unit/config-print.test.ts | 28 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 services/aztec-listener/tests/unit/config-print.test.ts diff --git a/services/aztec-listener/src/environment.ts b/services/aztec-listener/src/environment.ts index 8c6270e4f..1c9f402ab 100644 --- a/services/aztec-listener/src/environment.ts +++ b/services/aztec-listener/src/environment.ts @@ -159,11 +159,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(); }; 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/, + ); + }); +}); From 8213c88d85cb1de5f6cbbd7595b0c24596b22803 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:06:30 +0000 Subject: [PATCH 23/31] fix(aztec-listener): send no batch whose pass's tip the node no longer holds The stream emits each batch before it checks the snapshot's tip, so blocks went out with a tip the node had since dropped, and the API kept dead blocks below that tip canonical. Each batch now first confirms that tip against the pinned node, and the pass ends, sending nothing, when the node no longer holds it. Co-Authored-By: Claude Opus 5.5 --- .../pollers/block_poller/chain-publisher.ts | 26 ++++++++++++-- .../tests/unit/chain-publisher.test.ts | 34 +++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) 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 index 624c09e74..4d71f7b0e 100644 --- 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 @@ -126,15 +126,16 @@ export class ChainPublisher implements L2BlockStreamEventHandler { } private async addBlocks(blocks: L2Block[]) { - const tip = this.snapshot().proposed.number; + const tip = this.snapshot().proposed; const rejection = await this.batchFault(blocks); if (rejection !== undefined) { this.reject(rejection); } + await this.confirmTip(tip, blocks); const sent: L2Block[] = []; try { for (const block of blocks) { - await this.deps.publishBlock(block, tip); + await this.deps.publishBlock(block, tip.number); sent.push(block); } } finally { @@ -194,6 +195,27 @@ export class ChainPublisher implements L2BlockStreamEventHandler { 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. + private async confirmTip(tip: L2BlockId, blocks: L2Block[]) { + // Before the read, which unpins a node that has no block at the tip. + const name = this.pinnedName(); + const last = blocks[blocks.length - 1]; + const held = + last.number === tip.number + ? last.hash() + : this.deps.source + .pinnedBlockData(tip.number) + .then((data) => data?.header.hash()); + if ((await held)?.toString() !== tip.hash) { + logger.warn( + `Node ${name} no longer holds this pass's proposed tip ${tip.number}; the pass ends before sending blocks ${blocks[0].number}-${last.number}`, + ); + throw new PassExit(); + } + } + private async prune(event: PruneEvent) { const snapshot = this.snapshot(); const target = event.block; diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index 63c24eea2..3159073bf 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -173,6 +173,40 @@ describe("ChainPublisher after the node replaces published heights", () => { }, ); + 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("stops the pass at a failed send, and the next pass sends again from that block", async () => { const x = new FakeNode("x", prefix(main, 5)); const { sent, failing, pass, head } = setup({ nodes: [x] }); From 229b7ac4516c081743173ab4cd70816431a9ecac Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:11:21 +0000 Subject: [PATCH 24/31] fix(aztec-listener): refuse a prune depth past the API's chain walk bound AZTEC_MAX_PRUNE_DEPTH had no maximum, so a deeper prune could leave more canonical blocks above an ordered block's tip than the API demotes, halting its ordered topic. The bound now lives in @chicmoz-pkg/message-registry as CHAIN_WALK_BOUND, and the listener's env takes it as both its maximum and its default. Co-Authored-By: Claude Opus 5.5 --- packages/message-registry/src/aztec.ts | 7 ++++++ services/aztec-listener/src/environment.ts | 4 +++- .../tests/unit/max-prune-depth.test.ts | 22 +++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 services/aztec-listener/tests/unit/max-prune-depth.test.ts diff --git a/packages/message-registry/src/aztec.ts b/packages/message-registry/src/aztec.ts index fbce100b3..517ac817e 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 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 1c9f402ab..aad2a776d 100644 --- a/services/aztec-listener/src/environment.ts +++ b/services/aztec-listener/src/environment.ts @@ -1,3 +1,4 @@ +import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry"; import { l2NetworkIdSchema, rpcNodePoolSchema, @@ -72,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() 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); +}); From f63e23af949bb4c471d601c51a20715c94050938 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:14:14 +0000 Subject: [PATCH 25/31] fix(aztec-listener): heartbeat between a range request's block reads A range request read up to 200 blocks serially without a heartbeat, so a slow one outlasted the Kafka session and was redelivered and rerun, delaying later repairs. The handler now awaits the bus's heartbeat before each block read, and a failed heartbeat stops the request and rejects it. Co-Authored-By: Claude Opus 5.5 --- .../received/on-l2-block-range-request.ts | 23 ++++++++--- .../tests/unit/l2-block-range-request.test.ts | 39 +++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) 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 a377b56db..e74ea02a4 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, @@ -83,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( @@ -118,6 +121,8 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => { } for (let height = range.from; height <= range.to && publishedBlocks < maxBlocks; height++) { + // Hundreds of serial reads can outlast the Kafka session. + await heartbeat(); const read = await reader.getBlock(height); if (!read) { failedHeights++; @@ -142,7 +147,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}`); @@ -151,7 +159,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}`); @@ -170,5 +180,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/tests/unit/l2-block-range-request.test.ts b/services/aztec-listener/tests/unit/l2-block-range-request.test.ts index ddaf809d4..8df9453fd 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 @@ -137,4 +137,43 @@ describe("L2 block range request", () => { ]), ); }); + + it("heartbeats before each block read, 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 }, final: false }); + }, + }); + onCatchupBlock.mockClear(); + const rebalance = new Error("The group is rebalancing"); + let beats = 0; + const heartbeat = () => { + calls.push("heartbeat"); + return ++beats === 3 ? 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(calls).toEqual([ + "heartbeat", + "read 1", + "heartbeat", + "read 2", + "heartbeat", + ]); + expect(onCatchupBlock).toHaveBeenCalledTimes(2); + }); }); From 27adaa83d50cc931a23177b2fc61ad0694ca8a10 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:37:31 +0000 Subject: [PATCH 26/31] test(aztec-listener): cover a pass longer than one batch A normal pass of 15 blocks at batch size 10 sends every block once, each with the pass's tip, and stores the pass's tip. Co-Authored-By: Claude Opus 5.5 --- .../tests/unit/chain-publisher.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index 3159073bf..033685f19 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -207,6 +207,20 @@ describe("ChainPublisher after the node replaces published heights", () => { }, ); + 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("stops the pass at a failed send, and the next pass sends again from that block", async () => { const x = new FakeNode("x", prefix(main, 5)); const { sent, failing, pass, head } = setup({ nodes: [x] }); From e823487ebe794ddeabd80928d45c56ed663f9f45 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:40:55 +0000 Subject: [PATCH 27/31] fix(aztec-listener): store a batch only once every block in it is sent Storing the sent part of a batch let the next pass skip those blocks, so a tip the node had dropped since stayed theirs. A failed send now stores nothing, and the next pass sends the whole batch again with its own tip. Co-Authored-By: Claude Opus 5.5 --- .../pollers/block_poller/chain-publisher.ts | 26 +++++++------------ .../tests/unit/chain-publisher.test.ts | 15 ++++++----- 2 files changed, 19 insertions(+), 22 deletions(-) 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 index 4d71f7b0e..bf9f19d7c 100644 --- 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 @@ -54,7 +54,7 @@ export type ChainPublisherConfig = { prefixAlertMs: number; }; -/** The block stream's handler: it stores a block only once the block is sent. */ +/** 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; @@ -132,22 +132,16 @@ export class ChainPublisher implements L2BlockStreamEventHandler { this.reject(rejection); } await this.confirmTip(tip, blocks); - const sent: L2Block[] = []; - try { - for (const block of blocks) { - await this.deps.publishBlock(block, tip.number); - sent.push(block); - } - } finally { - // The next pass resumes after the last stored block, so a block whose - // send failed goes out again. - if (sent.length > 0) { - await this.deps.store.handleBlockStreamEvent({ - type: "blocks-added", - blocks: sent, - }); - } + 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 { diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index 033685f19..a6387e41f 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -221,23 +221,26 @@ describe("ChainPublisher after the node replaces published heights", () => { expect(await head()).toEqual({ number: 20, hash: main.hashes[20] }); }); - it("stops the pass at a failed send, and the next pass sends again from that block", async () => { + 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(7); + failing.add(8); await expect(pass()).rejects.toThrow("send rejected"); - expect(sent).toEqual(sentOf(main, [6], 9)); - expect((await head()).number).toBe(6); + 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], 9), - ...sentOf(main, [7, 8, 9], 9), + ...sentOf(main, [6, 7], 9), + ...sentOf(main, [6, 7], 7), ]); + expect(await head()).toEqual({ number: 7, hash: main.hashes[7] }); }); }); From 0f9daad7036a45c7eeba5bf26169ef5464eabaa9 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:44:34 +0000 Subject: [PATCH 28/31] fix(aztec-listener): bench a node whose tips name a block it does not serve The pass ended, yet the node kept its pin: the sticky election keeps it while no node leads it by more than two blocks. It is now benched until its tip changes, through the prefix rule's bench, renamed benchPinnedUntilNewTip. Co-Authored-By: Claude Opus 5.5 --- .../poller/network-client/block-stream-source.ts | 11 ++++++----- .../poller/pollers/block_poller/chain-publisher.ts | 9 ++++++--- .../chain-publisher.integration.test.ts | 2 +- .../tests/unit/block-stream-source.test.ts | 2 +- .../tests/unit/chain-publisher.test.ts | 14 ++++++++++++++ 5 files changed, 28 insertions(+), 10 deletions(-) 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 f4d7545c6..4a14e665f 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 @@ -203,9 +203,10 @@ 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 - * once no eligible node is outside the bench. + * five minutes; the prefix rule, an empty range, no block at a height its + * snapshot covers, or a block at its tip's height other than its tip bench it + * until its tip changes. Benched nodes are all back once no eligible node is + * outside the bench. */ export class StickySource implements L2BlockStreamSource { /** The store as the stream must read it: its hash lookups count against the walk bound. */ @@ -349,8 +350,8 @@ export class StickySource implements L2BlockStreamSource { 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"); } 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 index bf9f19d7c..2c3f8a8dc 100644 --- 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 @@ -36,7 +36,7 @@ export type ChainPublisherDeps = { | "pinned" | "lastTips" | "pinnedBlockData" - | "endPassOnPrefix" + | "benchPinnedUntilNewTip" | "setAsidePinned" >; /** Sends one block of the ordered stream; resolves once it is sent. */ @@ -191,7 +191,9 @@ export class ChainPublisher implements L2BlockStreamEventHandler { // 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. + // that moved since its tips were read is not at fault, so a mismatch benches + // it only until its tip changes: enough to move the sticky election off a + // node whose tips and blocks keep disagreeing. private async confirmTip(tip: L2BlockId, blocks: L2Block[]) { // Before the read, which unpins a node that has no block at the tip. const name = this.pinnedName(); @@ -206,6 +208,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { logger.warn( `Node ${name} no longer holds this pass's proposed tip ${tip.number}; the pass ends before sending blocks ${blocks[0].number}-${last.number}`, ); + this.deps.source.benchPinnedUntilNewTip(); throw new PassExit(); } } @@ -219,7 +222,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { // has a shorter copy of the stored chain. this.endedOnPrefix = true; this.notePrefixWait(target.number, local.proposed.number); - this.deps.source.endPassOnPrefix(); + this.deps.source.benchPinnedUntilNewTip(); throw new PassExit(); } const [atTarget, above] = await Promise.all([ diff --git a/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts index 2a0a3662b..a765913cb 100644 --- a/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts +++ b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts @@ -113,7 +113,7 @@ const arrange = async (failCursor: boolean) => { pinned: undefined, lastTips: snapshot, pinnedBlockData: vi.fn(), - endPassOnPrefix: vi.fn(), + benchPinnedUntilNewTip: vi.fn(), setAsidePinned: vi.fn(), }, publishBlock: () => Promise.resolve(), 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 4d1765d07..9986e94cd 100644 --- a/services/aztec-listener/tests/unit/block-stream-source.test.ts +++ b/services/aztec-listener/tests/unit/block-stream-source.test.ts @@ -581,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); diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index a6387e41f..f6c232319 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -207,6 +207,20 @@ describe("ChainPublisher after the node replaces published heights", () => { }, ); + 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("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] }); From dc9ecdeecfa26b75a7603b0d68bfbb1ef93a4a01 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 07:49:39 +0000 Subject: [PATCH 29/31] fix(aztec-listener): heartbeat between a range request's setup reads and before each publish The reader's tips and node-info reads ran back to back before the first heartbeat, and a slow block read was followed by its publish with none between; either pair can outlast the Kafka session. Co-Authored-By: Claude Opus 5.5 --- .../received/on-l2-block-range-request.ts | 10 ++++++-- .../poller/network-client/attested-reads.ts | 4 ++++ .../tests/unit/attested-reads.test.ts | 8 +++++-- .../tests/unit/l2-block-range-request.test.ts | 23 ++++++++++++++++--- 4 files changed, 38 insertions(+), 7 deletions(-) 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 e74ea02a4..797620682 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 @@ -95,7 +95,11 @@ const processL2BlockRangeRequest = async ( return; } // One node answers the whole request, so its tips attest the blocks it serves. - const reader = await openAttestedReader(getRpcNode(), streamRollupVersion()); + 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( @@ -121,7 +125,8 @@ const processL2BlockRangeRequest = async ( } for (let height = range.from; height <= range.to && publishedBlocks < maxBlocks; height++) { - // Hundreds of serial reads can outlast the Kafka session. + // 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) { @@ -129,6 +134,7 @@ const processL2BlockRangeRequest = async ( logger.warn(`Requested catchup block ${height} not found for ${event.requestId}`); continue; } + await heartbeat(); await onCatchupBlock( read.block, range.statusHint, 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 index 257604df1..7023e06f9 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts @@ -20,12 +20,16 @@ export type AttestedReader = { * Pins `node` for one request. Its tips and rollup version are read before * its blocks, and a finalized block cannot change, so `final` holds for every * block read after them. Only the stream's own `rollupVersion` gets `final`. + * 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) { diff --git a/services/aztec-listener/tests/unit/attested-reads.test.ts b/services/aztec-listener/tests/unit/attested-reads.test.ts index 65f7f96ff..c1988b4b9 100644 --- a/services/aztec-listener/tests/unit/attested-reads.test.ts +++ b/services/aztec-listener/tests/unit/attested-reads.test.ts @@ -36,14 +36,18 @@ const nodeAt = (finalized: number) => { }; describe("openAttestedReader", () => { - it("reads the node's tips and version before its blocks, and marks a block final only at or below its finalized tip", async () => { + it("reads the node's tips and version before its blocks, with the caller's heartbeat between the two, and marks a block final only at or below its finalized tip", async () => { const node = nodeAt(2); - const reader = await openAttestedReader(node.rpc, ROLLUP_VERSION); + 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", 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 8df9453fd..3dc2514b4 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 @@ -124,7 +124,11 @@ describe("L2 block range request", () => { () => Promise.resolve(), ); - expect(openAttestedReader).toHaveBeenCalledWith({ name: "pool-node" }, 7); + expect(openAttestedReader).toHaveBeenCalledWith( + { name: "pool-node" }, + 7, + expect.any(Function), + ); expect(onCatchupBlock.mock.calls).toEqual( [1, 2, 3].map((height) => [ { height }, @@ -138,7 +142,7 @@ describe("L2 block range request", () => { ); }); - it("heartbeats before each block read, and stops and rejects on a failed heartbeat", async () => { + 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 } } }, @@ -148,11 +152,15 @@ describe("L2 block range request", () => { }, }); 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 === 3 ? Promise.reject(rebalance) : Promise.resolve(); + return ++beats === 5 ? Promise.reject(rebalance) : Promise.resolve(); }; await expect( @@ -167,12 +175,21 @@ describe("L2 block range request", () => { ), ).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); }); From 3ad8c14e010cb6148662c962696f982def4d28fe Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 08:11:58 +0000 Subject: [PATCH 30/31] fix(aztec-listener): keep a node whose blocks miss its tip out of the next election A tip mismatch benched the node only until its tip changed. A node that kept advancing cleared that bench at its next probe and, still the most advanced, won every election while each of its passes failed the check, so a healthy node never got the pin. The mismatch now also costs the node the next election, which hands the pin to any other eligible node; the sticky election then keeps that node while the benched one leads it by no more than the pin's lead. A single node still runs every pass, since a bench holding every eligible node clears. The tip check still reads the tip's block through the checked block read, but without that read's own bench, which had already unpinned a node with no block at its tip. Co-Authored-By: Claude Opus 5.5 --- .../network-client/block-stream-source.ts | 56 ++++++++++++++----- .../pollers/block_poller/chain-publisher.ts | 15 ++--- .../chain-publisher.integration.test.ts | 2 + .../tests/unit/chain-publisher.test.ts | 28 ++++++++++ 4 files changed, 80 insertions(+), 21 deletions(-) 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 4a14e665f..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 @@ -78,7 +78,7 @@ export type StickySourceConfig = { type PassBounds = { finalized: L2BlockId; floor: number | undefined }; /** `tips` are what the election's probe showed. */ type Pin = { node: RpcNode; bounds: PassBounds; tips: L2Tips }; -type Bench = { until: number } | { tip: L2BlockId }; +type Bench = { until: number } | { tip: L2BlockId; sitsOutNext: boolean }; type Probe = { node: RpcNode; tips?: L2Tips; eligible: boolean }; type Candidate = Probe & { tips: L2Tips }; type Fault = { @@ -203,10 +203,10 @@ 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, no block at a height its - * snapshot covers, or a block at its tip's height other than its tip bench it - * until its tip changes. Benched nodes are all back once no eligible node is - * outside the bench. + * 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 { /** The store as the stream must read it: its hash lookups count against the walk bound. */ @@ -291,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); } } @@ -357,6 +361,17 @@ export class StickySource implements L2BlockStreamSource { } } + /** + * 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) { @@ -400,6 +415,13 @@ export class StickySource implements L2BlockStreamSource { ); } + /** 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, @@ -470,13 +492,19 @@ 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 ("number" in query && tip !== undefined && query.number <= tip) { + 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"); } @@ -596,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.tips.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/pollers/block_poller/chain-publisher.ts b/services/aztec-listener/src/svcs/poller/pollers/block_poller/chain-publisher.ts index 2c3f8a8dc..c03223d08 100644 --- 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 @@ -36,7 +36,9 @@ export type ChainPublisherDeps = { | "pinned" | "lastTips" | "pinnedBlockData" + | "pinnedBlockDataUnbenched" | "benchPinnedUntilNewTip" + | "benchPinnedPastNextElection" | "setAsidePinned" >; /** Sends one block of the ordered stream; resolves once it is sent. */ @@ -192,23 +194,22 @@ export class ChainPublisher implements L2BlockStreamEventHandler { // 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 only until its tip changes: enough to move the sticky election off a - // node whose tips and blocks keep disagreeing. + // 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[]) { - // Before the read, which unpins a node that has no block at the tip. - const name = this.pinnedName(); const last = blocks[blocks.length - 1]; const held = last.number === tip.number ? last.hash() : this.deps.source - .pinnedBlockData(tip.number) + .pinnedBlockDataUnbenched(tip.number) .then((data) => data?.header.hash()); if ((await held)?.toString() !== tip.hash) { logger.warn( - `Node ${name} no longer holds this pass's proposed tip ${tip.number}; the pass ends before sending blocks ${blocks[0].number}-${last.number}`, + `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.benchPinnedUntilNewTip(); + this.deps.source.benchPinnedPastNextElection(); throw new PassExit(); } } diff --git a/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts index a765913cb..698686c17 100644 --- a/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts +++ b/services/aztec-listener/tests/integration/chain-publisher.integration.test.ts @@ -113,7 +113,9 @@ const arrange = async (failCursor: boolean) => { pinned: undefined, lastTips: snapshot, pinnedBlockData: vi.fn(), + pinnedBlockDataUnbenched: vi.fn(), benchPinnedUntilNewTip: vi.fn(), + benchPinnedPastNextElection: vi.fn(), setAsidePinned: vi.fn(), }, publishBlock: () => Promise.resolve(), diff --git a/services/aztec-listener/tests/unit/chain-publisher.test.ts b/services/aztec-listener/tests/unit/chain-publisher.test.ts index f6c232319..b643dc1f3 100644 --- a/services/aztec-listener/tests/unit/chain-publisher.test.ts +++ b/services/aztec-listener/tests/unit/chain-publisher.test.ts @@ -221,6 +221,34 @@ describe("ChainPublisher after the node replaces published heights", () => { 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] }); From 6b59bf7bf3a3dc33616432ac6ad7dd54e9b0a3e8 Mon Sep 17 00:00:00 2001 From: alejoamiras Date: Fri, 27 Nov 2026 16:32:23 +0000 Subject: [PATCH 31/31] refactor(aztec-listener): send proposedTip and finalized, and rename the proven batch setting Ordered blocks go out with `ordered: { proposedTip }`, and catch-up blocks a node's reader attests with `finalized: true`, the registry's new field names. The attested reader's flag is `finalized` too. AZTEC_PROVEN_SIDE_WORK_MAX becomes AZTEC_PROVEN_BLOCKS_PER_PASS, and the prefix wait and the rollup version read use the renamed stall alert and node probe settings. Defaults are unchanged. Co-Authored-By: Claude Opus 5.5 --- packages/message-registry/src/aztec.ts | 2 +- services/aztec-listener/src/environment.ts | 6 +++--- .../aztec-listener/src/events/emitted/index.ts | 11 ++++++----- .../events/received/on-l2-block-range-request.ts | 2 +- .../svcs/poller/network-client/attested-reads.ts | 14 +++++++------- .../poller/pollers/block_poller/chain-publisher.ts | 4 ++-- .../src/svcs/poller/pollers/block_poller/index.ts | 6 +++--- .../pollers/block_poller/proven-side-work.ts | 4 ++-- .../tests/unit/attested-reads.test.ts | 8 ++++---- .../tests/unit/block-processing.test.ts | 2 +- .../tests/unit/full-sweep-catchup.test.ts | 8 ++++---- .../tests/unit/l2-block-range-request.test.ts | 8 ++++---- 12 files changed, 38 insertions(+), 37 deletions(-) diff --git a/packages/message-registry/src/aztec.ts b/packages/message-registry/src/aztec.ts index 517ac817e..6efaac011 100644 --- a/packages/message-registry/src/aztec.ts +++ b/packages/message-registry/src/aztec.ts @@ -29,7 +29,7 @@ export type NewBlockEvent = BlockEvent & { /** * 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 tip than the API demotes. + * ordered block's proposed tip than the API demotes. */ export const CHAIN_WALK_BOUND = 10_000; diff --git a/services/aztec-listener/src/environment.ts b/services/aztec-listener/src/environment.ts index aad2a776d..46c87b13c 100644 --- a/services/aztec-listener/src/environment.ts +++ b/services/aztec-listener/src/environment.ts @@ -96,12 +96,12 @@ export const AZTEC_BLOCK_STREAM_BATCH_SIZE = z.coerce .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_SIDE_WORK_MAX = z.coerce +export const AZTEC_PROVEN_BLOCKS_PER_PASS = z.coerce .number() .int() .positive() .default(200) - .parse(process.env.AZTEC_PROVEN_SIDE_WORK_MAX); + .parse(process.env.AZTEC_PROVEN_BLOCKS_PER_PASS); export const L2_BLOCK_RANGE_REQUEST_MAX_RANGES = z.coerce .number() .int() @@ -214,7 +214,7 @@ AZTEC_MAX_PRUNE_DEPTH: ${AZTEC_MAX_PRUNE_DEP 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_SIDE_WORK_MAX: ${AZTEC_PROVEN_SIDE_WORK_MAX} +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 933581bc8..193bbcddb 100644 --- a/services/aztec-listener/src/events/emitted/index.ts +++ b/services/aztec-listener/src/events/emitted/index.ts @@ -34,15 +34,16 @@ const toSafeBlockNumber = (value: bigint): number => { /** * Sends a block of the ordered stream, keyed by the network so the topic - * keeps the send order. `tip` is the proposed tip of the pass that sends it. + * keeps the send order. `proposedTip` is the proposed tip of the pass that + * sends it. */ -export const onOrderedBlock = async (block: L2Block, tip: number) => { +export const onOrderedBlock = async (block: L2Block, proposedTip: number) => { const height = BigInt(block.header.globalVariables.blockNumber.toString()); const heightNumber = toSafeBlockNumber(height); logger.info( `🦊 publishing block ${height} (hash: ${( await block.hash() - ).toString()}, tip ${tip})...`, + ).toString()}, proposed tip ${proposedTip})...`, ); const blockBuffer = block.toBuffer() as Uint8Array; const blockStr = Buffer.from(blockBuffer).toString("hex"); @@ -50,7 +51,7 @@ export const onOrderedBlock = async (block: L2Block, tip: number) => { block: blockStr, statusHint: "proposed", blockNumber: heightNumber, - ordered: { tip }, + ordered: { proposedTip }, }); const potentiallyIncludedTxs = await txsController.getTxs([ "pending", @@ -75,7 +76,7 @@ export const onCatchupBlock = async ( statusHint: L2BlockStatusHint, metadata: Pick< CatchupBlockEvent, - "requestId" | "catchupReason" | "final" + "requestId" | "catchupReason" | "finalized" > = {}, ) => { const blockNumber = BigInt( 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 797620682..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 @@ -141,7 +141,7 @@ const processL2BlockRangeRequest = async ( { requestId: event.requestId, catchupReason: event.reason === "tip_boundary_mismatch" ? "reorg_repair" : event.reason, - ...(read.final ? { final: true as const } : {}), + ...(read.finalized ? { finalized: true as const } : {}), }, ); publishedBlocks++; 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 index 7023e06f9..3d03a5fdc 100644 --- a/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts +++ b/services/aztec-listener/src/svcs/poller/network-client/attested-reads.ts @@ -5,8 +5,8 @@ import { NodeCheckError, bodyFault } from "./block-stream-source.js"; import { callNodeFunction } from "./index.js"; import { type RpcNode } from "./pool.js"; -/** `final`: at or below the serving node's own finalized tip, on the stream's rollup version. */ -export type AttestedBlock = { block: L2Block; final: boolean }; +/** `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; @@ -18,10 +18,10 @@ export type AttestedReader = { /** * Pins `node` for one request. Its tips and rollup version are read before - * its blocks, and a finalized block cannot change, so `final` holds for every - * block read after them. Only the stream's own `rollupVersion` gets `final`. - * A caller whose session two slow reads can outlast passes its `heartbeat`, - * which runs between them. + * 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, @@ -77,7 +77,7 @@ export const openAttestedReader = async ( } return { block, - final: + finalized: version !== undefined && block.header.globalVariables.version.toBigInt() === version && height <= tips.finalized.block.number, 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 index c03223d08..00d634a50 100644 --- 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 @@ -9,7 +9,7 @@ import { } from "@aztec-labs/stdlib/block"; import { AZTEC_MAX_PRUNE_DEPTH, - AZTEC_STREAM_PREFIX_ALERT_MS, + AZTEC_STREAM_STALL_ALERT_MS, } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; import { @@ -67,7 +67,7 @@ export class ChainPublisher implements L2BlockStreamEventHandler { private readonly deps: ChainPublisherDeps, private readonly config: ChainPublisherConfig = { maxPruneDepth: AZTEC_MAX_PRUNE_DEPTH, - prefixAlertMs: AZTEC_STREAM_PREFIX_ALERT_MS, + prefixAlertMs: AZTEC_STREAM_STALL_ALERT_MS, }, ) { this.now = deps.now ?? (() => Date.now()); 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 9edab3076..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 @@ -7,7 +7,7 @@ import { AZTEC_DISABLE_LISTEN_FOR_PROVEN_BLOCKS, AZTEC_ENABLE_FULL_SWEEP_CATCHUP, AZTEC_LISTEN_FOR_L2_TIPS, - AZTEC_TIPS_PROBE_TIMEOUT_MS, + AZTEC_NODE_PROBE_TIMEOUT_MS, BLOCK_POLL_INTERVAL_MS, CHAIN_INFO_POLL_INTERVAL_MS, } from "../../../../environment.js"; @@ -103,7 +103,7 @@ export const currentChain = async (now = Date.now()): Promise => { latest = (await readLatestRollupVersion( getOnlineRpcNodes(), - AZTEC_TIPS_PROBE_TIMEOUT_MS, + AZTEC_NODE_PROBE_TIMEOUT_MS, )) ?? latest; versionReadAt = now; } @@ -136,7 +136,7 @@ const sweepOnce = async (storeTip: number, rollupVersion: number) => { await onCatchupBlock( read.block, "proposed", - read.final ? { final: true } : {}, + read.finalized ? { finalized: true } : {}, ); sweepHeight = (height + 1) % storeTip || 1; }; 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 index 5e8964dcb..254572615 100644 --- 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 @@ -2,7 +2,7 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { type L2Block } from "@aztec-labs/stdlib/block"; import { AZTEC_BLOCK_STREAM_BATCH_SIZE, - AZTEC_PROVEN_SIDE_WORK_MAX, + AZTEC_PROVEN_BLOCKS_PER_PASS, } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; import { type StickySource } from "../../network-client/block-stream-source.js"; @@ -51,7 +51,7 @@ const onStoredChain = async ( export const runProvenSideWork = async ( deps: ProvenSideWorkDeps, { max, batchSize } = { - max: AZTEC_PROVEN_SIDE_WORK_MAX, + max: AZTEC_PROVEN_BLOCKS_PER_PASS, batchSize: AZTEC_BLOCK_STREAM_BATCH_SIZE, }, ) => { diff --git a/services/aztec-listener/tests/unit/attested-reads.test.ts b/services/aztec-listener/tests/unit/attested-reads.test.ts index c1988b4b9..76f6278c4 100644 --- a/services/aztec-listener/tests/unit/attested-reads.test.ts +++ b/services/aztec-listener/tests/unit/attested-reads.test.ts @@ -36,7 +36,7 @@ const nodeAt = (finalized: number) => { }; 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 final only at or below its finalized tip", async () => { + 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"); @@ -53,7 +53,7 @@ describe("openAttestedReader", () => { "getBlock", ]); expect(await two?.block.hash()).toEqual(await chain.blocks[2].hash()); - expect([two?.final, three?.final]).toEqual([true, false]); + expect([two?.finalized, three?.finalized]).toEqual([true, false]); expect(reader.tips.proposed.number).toBe(4); }); @@ -77,7 +77,7 @@ describe("openAttestedReader", () => { streamVersion: undefined, }, ])( - "marks no block final on $on", + "marks no block finalized on $on", async ({ nodeVersion, blockVersion, streamVersion }) => { const node = nodeAt(4); node.rollupVersion = nodeVersion; @@ -85,7 +85,7 @@ describe("openAttestedReader", () => { node.getBlockOverride = () => respond(block, true); const reader = await openAttestedReader(node.rpc, streamVersion); - expect((await reader.getBlock(1))?.final).toBe(false); + expect((await reader.getBlock(1))?.finalized).toBe(false); }, ); diff --git a/services/aztec-listener/tests/unit/block-processing.test.ts b/services/aztec-listener/tests/unit/block-processing.test.ts index 83412022f..825fd9129 100644 --- a/services/aztec-listener/tests/unit/block-processing.test.ts +++ b/services/aztec-listener/tests/unit/block-processing.test.ts @@ -49,7 +49,7 @@ describe("onOrderedBlock", () => { block: Buffer.from("mock-block-100").toString("hex"), statusHint: "proposed", blockNumber: 100, - ordered: { tip: 104 }, + ordered: { proposedTip: 104 }, }, ); expect(mockMessageBus.publishMessage).not.toHaveBeenCalled(); 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 9f3ad0905..89723c233 100644 --- a/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts +++ b/services/aztec-listener/tests/unit/full-sweep-catchup.test.ts @@ -87,7 +87,7 @@ describe("block poller full sweep", () => { // The node reader attests block 1 only. openAttestedReader.mockResolvedValue({ getBlock: (height: number) => - Promise.resolve({ block: { height }, final: height === 1 }), + Promise.resolve({ block: { height }, finalized: height === 1 }), }); }); @@ -104,7 +104,7 @@ describe("block poller full sweep", () => { expect(onCatchupBlock).not.toHaveBeenCalled(); }); - it("sweeps one block per pass that leaves the tip, below the store's tip, marking final what the node's reader attests", async () => { + 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++) { @@ -115,9 +115,9 @@ describe("block poller full sweep", () => { expect(openAttestedReader).toHaveBeenCalledTimes(3); expect(openAttestedReader).toHaveBeenCalledWith(node, 7); expect(onCatchupBlock.mock.calls).toEqual([ - [{ height: 1 }, "proposed", { final: true }], + [{ height: 1 }, "proposed", { finalized: true }], [{ height: 2 }, "proposed", {}], - [{ height: 1 }, "proposed", { final: true }], + [{ 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 3dc2514b4..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 @@ -107,11 +107,11 @@ describe("L2 block range request helpers", () => { }); describe("L2 block range request", () => { - it("answers from one node, clamped to its tips, with final on the blocks its reader attests", async () => { + 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 }, final: height === 1 }), + Promise.resolve({ block: { height }, finalized: height === 1 }), }); await l2BlockRangeRequestHandler.cb( @@ -136,7 +136,7 @@ describe("L2 block range request", () => { { requestId: "request-3", catchupReason: "cadence", - ...(height === 1 ? { final: true } : {}), + ...(height === 1 ? { finalized: true } : {}), }, ]), ); @@ -148,7 +148,7 @@ describe("L2 block range request", () => { tips: { proposed: { number: 4 }, proven: { block: { number: 4 } } }, getBlock: (height: number) => { calls.push(`read ${height}`); - return Promise.resolve({ block: { height }, final: false }); + return Promise.resolve({ block: { height }, finalized: false }); }, }); onCatchupBlock.mockClear();