Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
809bb93
feat(aztec-listener): add a block stream handler that publishes in order
alejoamiras Nov 26, 2026
808d89c
feat(aztec-listener): follow the chain through the block stream
alejoamiras Nov 26, 2026
c8e1906
refactor(aztec-listener): drop the chain height writers
alejoamiras Nov 26, 2026
70ae88a
fix(aztec-listener): redact URLs in stream logs
alejoamiras Nov 27, 2026
3495848
fix(aztec-listener): check a prune's tiers before the store writes them
alejoamiras Nov 27, 2026
8fb2c15
fix(aztec-listener): never store a proposed tip the pass did not send
alejoamiras Nov 27, 2026
8c14ae8
fix(aztec-listener): run the proven side work only on stored blocks
alejoamiras Nov 27, 2026
72b39fb
fix(aztec-listener): fail the pass when a stream handler fails
alejoamiras Nov 27, 2026
29dccd4
fix(aztec-listener): keep the legacy proposed height on the store's tip
alejoamiras Nov 27, 2026
34c09db
docs(aztec-listener): trim comments that restate the code
alejoamiras Nov 27, 2026
03460cb
test(network-smoke): reconcile missing blocks every 5 s
alejoamiras Nov 27, 2026
54705b6
fix(aztec-listener): redact URLs in a failed pass's log
alejoamiras Nov 27, 2026
a867f8f
fix(aztec-listener): confirm a proposed tip against the store's tip
alejoamiras Nov 27, 2026
7164145
docs(aztec-listener): note the side work's trust below finality
alejoamiras Nov 27, 2026
f6ff9f7
fix(aztec-listener): end a pass on its own exit type only
alejoamiras Nov 27, 2026
e605df8
fix(aztec-listener): keep the legacy proposed height until the store …
alejoamiras Nov 27, 2026
066d5aa
fix(aztec-listener): call a store empty only when it holds no block
alejoamiras Nov 27, 2026
051d15e
fix(aztec-listener): redact URLs in the node client's errors
alejoamiras Nov 27, 2026
7770f04
fix(aztec-listener): redact the node pool's URLs exactly before the p…
alejoamiras Nov 27, 2026
5c51c4d
fix(aztec-listener): match the node pool's URL parts case-sensitively
alejoamiras Nov 27, 2026
cb12dcb
fix(aztec-listener): redact URLs in the election probe's errors
alejoamiras Nov 27, 2026
0e670e9
fix(aztec-listener): print only each pool URL's origin at startup
alejoamiras Nov 27, 2026
8213c88
fix(aztec-listener): send no batch whose pass's tip the node no longe…
alejoamiras Nov 27, 2026
229b7ac
fix(aztec-listener): refuse a prune depth past the API's chain walk b…
alejoamiras Nov 27, 2026
f63e23a
fix(aztec-listener): heartbeat between a range request's block reads
alejoamiras Nov 27, 2026
27adaa8
test(aztec-listener): cover a pass longer than one batch
alejoamiras Nov 27, 2026
e823487
fix(aztec-listener): store a batch only once every block in it is sent
alejoamiras Nov 27, 2026
0f9daad
fix(aztec-listener): bench a node whose tips name a block it does not…
alejoamiras Nov 27, 2026
dc9ecde
fix(aztec-listener): heartbeat between a range request's setup reads …
alejoamiras Nov 27, 2026
3ad8c14
fix(aztec-listener): keep a node whose blocks miss its tip out of the…
alejoamiras Nov 27, 2026
6b59bf7
refactor(aztec-listener): send proposedTip and finalized, and rename …
alejoamiras Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/message-registry/src/aztec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ export type NewBlockEvent = BlockEvent & {
ordered?: { proposedTip: number };
};

/**
* The deepest prune the listener follows and the longest chain walk the API
* takes: a prune within it leaves no more canonical blocks above the next
* ordered block's proposed tip than the API demotes.
*/
export const CHAIN_WALK_BOUND = 10_000;

export type PendingTxsEvent = {
txs: ChicmozL2PendingTx[];
};
Expand Down
43 changes: 31 additions & 12 deletions services/aztec-listener/src/environment.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry";
import {
l2NetworkIdSchema,
rpcNodePoolSchema,
type L2NetworkId,
} from "@chicmoz-pkg/types";
import { MAX_RPC_BLOCKS_LEN } from "@aztec-labs/stdlib/interfaces/api-limit";
import { z } from "zod";

/**
Expand All @@ -21,10 +23,6 @@ export const BLOCK_POLL_INTERVAL_MS = z.coerce
.number()
.default(3000)
.parse(process.env.BLOCK_POLL_INTERVAL_MS);
export const CATCHUP_POLL_WAIT_TIME_MS = z.coerce
.number()
.default(100)
.parse(process.env.CATCHUP_POLL_WAIT_TIME_MS);
export const TX_POLL_INTERVAL_MS = z.coerce
.number()
.default(4000) // NOTE: https://github.com/aztec-scan/chicmoz/issues/430#issuecomment-2841287541
Expand All @@ -33,10 +31,6 @@ export const CHAIN_INFO_POLL_INTERVAL_MS = z.coerce
.number()
.default(30000)
.parse(process.env.CHAIN_INFO_POLL_INTERVAL_MS);
export const L2_TIPS_POLL_INTERVAL_MS = z.coerce
.number()
.default(5000)
.parse(process.env.L2_TIPS_POLL_INTERVAL_MS);
export const L2_TIPS_HEARTBEAT_INTERVAL_MS = z.coerce
.number()
.default(60000)
Expand Down Expand Up @@ -79,7 +73,8 @@ export const AZTEC_MAX_PRUNE_DEPTH = z.coerce
.number()
.int()
.positive()
.default(10_000)
.max(CHAIN_WALK_BOUND)
.default(CHAIN_WALK_BOUND)
.parse(process.env.AZTEC_MAX_PRUNE_DEPTH);
export const AZTEC_STREAM_STALL_ALERT_MS = z.coerce
.number()
Expand All @@ -93,6 +88,20 @@ export const AZTEC_NODE_PROBE_TIMEOUT_MS = z.coerce
.positive()
.default(2_000)
.parse(process.env.AZTEC_NODE_PROBE_TIMEOUT_MS);
export const AZTEC_BLOCK_STREAM_BATCH_SIZE = z.coerce
.number()
.int()
.positive()
.max(MAX_RPC_BLOCKS_LEN)
.default(10)
.parse(process.env.AZTEC_BLOCK_STREAM_BATCH_SIZE);
/** The most proven blocks one pass runs the fee-juice balance work on. */
export const AZTEC_PROVEN_BLOCKS_PER_PASS = z.coerce
.number()
.int()
.positive()
.default(200)
.parse(process.env.AZTEC_PROVEN_BLOCKS_PER_PASS);
export const L2_BLOCK_RANGE_REQUEST_MAX_RANGES = z.coerce
.number()
.int()
Expand Down Expand Up @@ -152,11 +161,21 @@ export const L2_NETWORK_ID: L2NetworkId = l2NetworkIdSchema.parse(
export const AZTEC_RPC_URLS = rpcNodePoolSchema.parse(
process.env.AZTEC_RPC_URLS,
);
// A pool URL can carry a key in its userinfo, path or query.
const printedUrl = (url: string) => {
try {
const { protocol, host, pathname, search } = new URL(url);
const more = pathname.length > 1 || search !== "" ? "/…" : "";
return `${protocol}//${host}${more}`;
} catch {
return "(not a URL)";
}
};
const printPool = () => {
let finalString = "\n";
AZTEC_RPC_URLS.forEach(
(node) =>
(finalString = `${finalString} Name: ${node.name}\n URL: ${node.url}\n\n`),
(finalString = `${finalString} Name: ${node.name}\n URL: ${printedUrl(node.url)}\n\n`),
);
return finalString.trim();
};
Expand Down Expand Up @@ -187,15 +206,15 @@ 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 ? "✅" : "❌"
}
AZTEC_MAX_PRUNE_DEPTH: ${AZTEC_MAX_PRUNE_DEPTH}
AZTEC_STREAM_STALL_ALERT_MS: ${AZTEC_STREAM_STALL_ALERT_MS / 1000}s
AZTEC_NODE_PROBE_TIMEOUT_MS: ${AZTEC_NODE_PROBE_TIMEOUT_MS / 1000}s
AZTEC_BLOCK_STREAM_BATCH_SIZE: ${AZTEC_BLOCK_STREAM_BATCH_SIZE}
AZTEC_PROVEN_BLOCKS_PER_PASS: ${AZTEC_PROVEN_BLOCKS_PER_PASS}
MAX_BATCH_SIZE_FETCH_MISSED_BLOCKS: ${MAX_BATCH_SIZE_FETCH_MISSED_BLOCKS}
L2_BLOCK_RANGE_REQUEST_MAX_RANGES: ${L2_BLOCK_RANGE_REQUEST_MAX_RANGES}
L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS: ${L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS}
Expand Down
38 changes: 20 additions & 18 deletions services/aztec-listener/src/events/emitted/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -30,27 +32,26 @@ const toSafeBlockNumber = (value: bigint): number => {
return blockNumber;
};

export const onBlock = async (
block: L2Block,
statusHint: L2BlockStatusHint,
) => {
/**
* Sends a block of the ordered stream, keyed by the network so the topic
* keeps the send order. `proposedTip` is the proposed tip of the pass that
* sends it.
*/
export const onOrderedBlock = async (block: L2Block, proposedTip: number) => {
const height = BigInt(block.header.globalVariables.blockNumber.toString());
const heightNumber = toSafeBlockNumber(height);
const statusHintStr =
statusHint === "proposed"
? "🦊 publishing proposed block"
: "🐴 publishing proven block";
logger.info(
`${statusHintStr} ${height} (hash: ${(
`🦊 publishing block ${height} (hash: ${(
await block.hash()
).toString()})...`,
).toString()}, proposed tip ${proposedTip})...`,
);
const blockBuffer = block.toBuffer() as Uint8Array;
const blockStr = Buffer.from(blockBuffer).toString("hex");
await publishMessage("NEW_BLOCK_EVENT", {
await publishKeyedMessage("NEW_BLOCK_EVENT", L2_NETWORK_ID, {
block: blockStr,
statusHint,
statusHint: "proposed",
blockNumber: heightNumber,
ordered: { proposedTip },
});
const potentiallyIncludedTxs = await txsController.getTxs([
"pending",
Expand All @@ -61,12 +62,10 @@ export const onBlock = async (
);

for (const potentialTx of potentiallyIncludedTxs) {
const txFoundInBlock = blockTxHashes.includes(potentialTx.txHash);
if (txFoundInBlock) {
const newState = statusHint;
await txsController.storeOrUpdate(potentialTx, newState);
if (blockTxHashes.includes(potentialTx.txHash)) {
await txsController.storeOrUpdate(potentialTx, "proposed");
logger.info(
`✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to ${newState}`,
`✅ Transaction ${potentialTx.txHash} found in block ${height}, updated to proposed`,
);
}
}
Expand All @@ -75,7 +74,10 @@ export const onBlock = async (
export const onCatchupBlock = async (
block: L2Block,
statusHint: L2BlockStatusHint,
metadata: Pick<CatchupBlockEvent, "requestId" | "catchupReason"> = {},
metadata: Pick<
CatchupBlockEvent,
"requestId" | "catchupReason" | "finalized"
> = {},
) => {
const blockNumber = BigInt(
block.header.globalVariables.blockNumber.toString(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { EventHandler } from "@chicmoz-pkg/message-bus";
import { EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus";
import {
generateL2TopicName,
getConsumerGroupId,
Expand All @@ -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<string>();

Expand Down Expand Up @@ -85,16 +83,25 @@ 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(
`Skipping stale L2 block range request ${event.requestId}; ageMs=${requestAgeMs}`,
);
return;
}
const proposedHeight = toSafeHeight(await getLatestProposedHeight());
const provenHeight = toSafeHeight(await getLatestProvenHeight());
// One node answers the whole request, so its tips attest the blocks it serves.
const reader = await openAttestedReader(
getRpcNode(),
streamRollupVersion(),
heartbeat,
);
const proposedHeight = toSafeHeight(reader.tips.proposed.number);
const provenHeight = toSafeHeight(reader.tips.proven.block.number);
const maxBlocks = Math.min(
event.maxBlocks ?? L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS,
L2_BLOCK_RANGE_REQUEST_MAX_BLOCKS,
Expand All @@ -118,18 +125,23 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => {
}

for (let height = range.from; height <= range.to && publishedBlocks < maxBlocks; height++) {
const block = await getBlock(height);
if (!block) {
// Before every read and publish: two slow calls in a row can outlast the
// Kafka session.
await heartbeat();
const read = await reader.getBlock(height);
if (!read) {
failedHeights++;
logger.warn(`Requested catchup block ${height} not found for ${event.requestId}`);
continue;
}
await heartbeat();
await onCatchupBlock(
block,
read.block,
range.statusHint,
{
requestId: event.requestId,
catchupReason: event.reason === "tip_boundary_mismatch" ? "reorg_repair" : event.reason,
...(read.finalized ? { finalized: true as const } : {}),
},
);
publishedBlocks++;
Expand All @@ -141,7 +153,10 @@ const processL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => {
);
};

const onL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => {
const onL2BlockRangeRequest = async (
event: L2BlockRangeRequestEvent,
heartbeat: Heartbeat,
) => {
const dedupKey = getL2BlockRangeRequestDedupKey(event);
if (inFlightRequests.has(dedupKey)) {
logger.info(`Deduped in-flight L2 block range request ${event.requestId}; key=${dedupKey}`);
Expand All @@ -150,7 +165,9 @@ const onL2BlockRangeRequest = async (event: L2BlockRangeRequestEvent) => {

inFlightRequests.add(dedupKey);
try {
await requestLimiter.schedule(() => processL2BlockRangeRequest(event));
await requestLimiter.schedule(() =>
processL2BlockRangeRequest(event, heartbeat),
);
} catch (error) {
if (error instanceof Bottleneck.BottleneckError) {
logger.warn(`Skipped queued L2 block range request ${event.requestId}: ${error.message}`);
Expand All @@ -169,5 +186,8 @@ export const l2BlockRangeRequestHandler: EventHandler = {
handlerName: "blockRangeRequestHandler",
}),
topic: generateL2TopicName(L2_NETWORK_ID, "L2_BLOCK_RANGE_REQUEST_EVENT"),
cb: onL2BlockRangeRequest as (arg0: unknown) => Promise<void>,
cb: onL2BlockRangeRequest as (
arg0: unknown,
heartbeat: Heartbeat,
) => Promise<void>,
};
40 changes: 8 additions & 32 deletions services/aztec-listener/src/svcs/database/heights.controller.ts
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -17,38 +17,12 @@ export async function storeProcessedProvenBlockHeight(height: number) {
.where(eq(heightsTable.networkId, L2_NETWORK_ID));
}

export async function storeChainProposedBlockHeight(height: number) {
await db()
.update(heightsTable)
.set({ chainProposedBlockHeight: height })
.where(eq(heightsTable.networkId, L2_NETWORK_ID));
}

export async function storeChainProvenBlockHeight(height: number) {
await db()
.update(heightsTable)
.set({ chainProvenBlockHeight: height })
.where(eq(heightsTable.networkId, L2_NETWORK_ID));
}

export async function storeBlockHeights({
processedProposedBlockHeight,
chainProposedBlockHeight,
processedProvenBlockHeight,
chainProvenBlockHeight,
}: {
processedProposedBlockHeight: number;
chainProposedBlockHeight: number;
processedProvenBlockHeight: number;
chainProvenBlockHeight: number;
}) {
/** Moves the proven side work's cursor back to `height`; never forward. */
export async function lowerProcessedProvenBlockHeight(height: number) {
await db()
.update(heightsTable)
.set({
processedProposedBlockHeight,
chainProposedBlockHeight,
processedProvenBlockHeight,
chainProvenBlockHeight,
processedProvenBlockHeight: sql`LEAST(${heightsTable.processedProvenBlockHeight}, ${height})`,
})
.where(eq(heightsTable.networkId, L2_NETWORK_ID));
}
Expand All @@ -72,6 +46,8 @@ export async function getBlockHeights() {
.from(heightsTable)
.where(eq(heightsTable.networkId, L2_NETWORK_ID))
.limit(1);
if (result.length === 0) {throw new Error("FATAL: block heights not initialized");}
if (result.length === 0) {
throw new Error("FATAL: block heights not initialized");
}
return result[0];
}
2 changes: 2 additions & 0 deletions services/aztec-listener/src/svcs/database/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Loading
Loading