diff --git a/services/explorer-api/src/events/received/on-block/index.ts b/services/explorer-api/src/events/received/on-block/index.ts index 7bec3f7ac..5bcb92a84 100644 --- a/services/explorer-api/src/events/received/on-block/index.ts +++ b/services/explorer-api/src/events/received/on-block/index.ts @@ -11,6 +11,7 @@ import { z } from "zod"; import { SERVICE_NAME } from "../../../constants.js"; import { L2_NETWORK_ID } from "../../../environment.js"; import { logger } from "../../../logger.js"; +import { bumpChainRevision } from "../../../svcs/cache/chain-revision.js"; import { observeRollupVersion } from "../../../svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { applyCatchupBlock, @@ -52,6 +53,9 @@ const afterCommit = async ( { block }: IncomingBlock, { canonical }: ChainOutcome, ) => { + // Any applied block can change a cached chain read: the statuses it + // changed, the txs and contracts it took, its children's orphan flags. + await bumpChainRevision(); if (!canonical) { return; } diff --git a/services/explorer-api/src/events/received/on-dropped-txs.ts b/services/explorer-api/src/events/received/on-dropped-txs.ts index ccd365cd7..b5e87f745 100644 --- a/services/explorer-api/src/events/received/on-dropped-txs.ts +++ b/services/explorer-api/src/events/received/on-dropped-txs.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { DroppedTxsEvent, generateL2TopicName, @@ -7,36 +7,29 @@ import { import { SERVICE_NAME } from "../../constants.js"; import { L2_NETWORK_ID } from "../../environment.js"; import { logger } from "../../logger.js"; +import { withChainLock } from "../../svcs/database/controllers/chain-lock.js"; import { storeDroppedTx } from "../../svcs/database/controllers/dropped-tx/store.js"; import { deleteTx } from "../../svcs/database/controllers/l2Tx/index.js"; import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js"; import { deletePublicCall } from "../../svcs/database/controllers/l2Public-call/delete.js"; import { deleteL2ToL1Msgs } from "../../svcs/database/controllers/l2PendingL2ToL1Msg/delete.js"; -const onDroppedTxs = async ({ txs }: DroppedTxsEvent) => { +const onDroppedTxs = async ({ txs }: DroppedTxsEvent, heartbeat: Heartbeat) => { logger.info(`๐Ÿ—‘๏ธ Received ${txs.length} dropped txs to handle`); for (const droppedTx of txs) { - const isAlreadyStored = await txEffectExists(droppedTx.txHash); - if (isAlreadyStored) { - logger.info(`๐Ÿ—‘๏ธ Dropped tx ${droppedTx.txHash} already exists, skipping`); - continue; - } - try { - // Store as dropped transaction - await storeDroppedTx(droppedTx); - - // Delete public call data - await deletePublicCall(droppedTx.txHash); - - // Delete L2-to-L1 messages - await deleteL2ToL1Msgs(droppedTx.txHash); - - // Delete from pending transactions - await deleteTx(droppedTx.txHash); - } catch (error) { - logger.error(`Error processing dropped tx ${droppedTx.txHash}:`, error); - } + // Each tx waits for the chain lock on its own. + await heartbeat(); + await withChainLock(async (dbTx) => { + if (await txEffectExists(droppedTx.txHash, dbTx)) { + logger.info(`๐Ÿ—‘๏ธ Dropped tx ${droppedTx.txHash} is mined, skipping`); + return; + } + await storeDroppedTx(droppedTx, dbTx); + await deletePublicCall(droppedTx.txHash, dbTx); + await deleteL2ToL1Msgs(droppedTx.txHash, dbTx); + await deleteTx(droppedTx.txHash, dbTx); + }); } }; @@ -47,5 +40,5 @@ export const droppedTxHandler: EventHandler = { handlerName: "droppedTxHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "DROPPED_TXS_EVENT"), - cb: onDroppedTxs as (arg0: unknown) => Promise, + cb: onDroppedTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/src/events/received/on-pending-txs.ts b/services/explorer-api/src/events/received/on-pending-txs.ts index 7e854b831..c58e2bc05 100644 --- a/services/explorer-api/src/events/received/on-pending-txs.ts +++ b/services/explorer-api/src/events/received/on-pending-txs.ts @@ -1,4 +1,4 @@ -import { EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { PendingTxsEvent, generateL2TopicName, @@ -8,30 +8,40 @@ import { chicmozL2PendingTxSchema } from "@chicmoz-pkg/types"; import { SERVICE_NAME } from "../../constants.js"; import { L2_NETWORK_ID } from "../../environment.js"; import { logger } from "../../logger.js"; +import { withChainLock } from "../../svcs/database/controllers/chain-lock.js"; import { storeOrUpdateL2Tx } from "../../svcs/database/controllers/l2Tx/index.js"; import { removeDroppedTxByHash } from "../../svcs/database/controllers/dropped-tx/index.js"; -import { handleDuplicateError } from "./utils.js"; +import { txEffectExists } from "../../svcs/database/controllers/l2TxEffect/get-tx-effect.js"; -const onPendingTxs = async ({ txs }: PendingTxsEvent) => { +const onPendingTxs = async ({ txs }: PendingTxsEvent, heartbeat: Heartbeat) => { logger.info(`๐Ÿ• Received ${txs.length} pending txs to store`); for (const tx of txs) { - try { - const res = chicmozL2PendingTxSchema.parse(tx); - + // Each tx waits for the chain lock on its own. + await heartbeat(); + const parsed = chicmozL2PendingTxSchema.safeParse(tx); + if (!parsed.success) { + logger.error( + `Failed to parse pending tx ${tx.txHash}: ${parsed.error.message}`, + ); + continue; + } + const res = parsed.data; + await withChainLock(async (dbTx) => { + if (await txEffectExists(res.txHash, dbTx)) { + logger.info(`๐Ÿ• Pending tx ${res.txHash} is mined, skipping`); + return; + } // Handle resubmissions: remove from dropped table if exists - const removedCount = await removeDroppedTxByHash(res.txHash); + const removedCount = await removeDroppedTxByHash(res.txHash, dbTx); if (removedCount > 0) { logger.info( `๐Ÿ”„ Resubmitted tx ${res.txHash}: removed from dropped table`, ); } - // Store/update in pending table (handles both new and resubmitted transactions) - await storeOrUpdateL2Tx(res); + await storeOrUpdateL2Tx(res, dbTx); logger.debug(`โœ… Stored/updated pending tx: ${res.txHash}`); - } catch (e) { - handleDuplicateError(e as Error, `tx ${tx.txHash}`); - } + }); } }; @@ -42,5 +52,5 @@ export const pendingTxHandler: EventHandler = { handlerName: "pendingTxHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "PENDING_TXS_EVENT"), - cb: onPendingTxs as (arg0: unknown) => Promise, + cb: onPendingTxs as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/src/start.ts b/services/explorer-api/src/start.ts index d8cae475f..6bf730e7d 100644 --- a/services/explorer-api/src/start.ts +++ b/services/explorer-api/src/start.ts @@ -7,7 +7,8 @@ import { } from "./environment.js"; import { subscribeHandlers } from "./events/received/index.js"; import { logger } from "./logger.js"; -import { removeDroppedThatHaveTxEffects } from "./svcs/database/controllers/dropped-tx/remove.js"; +import { bumpChainRevision } from "./svcs/cache/chain-revision.js"; +import { removeMinedDroppedTxs } from "./svcs/database/controllers/dropped-tx/remove.js"; import { updateContractInstanceAztecScanNotes } from "./svcs/database/controllers/l2/aztec-scan-notes.js"; import { initializeRollupVersionCache } from "./svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { deleteAllTxs } from "./svcs/database/controllers/l2Tx/delete-all-txs.js"; @@ -23,7 +24,7 @@ import { export const start = async () => { await deleteAllTxs(); // TODO: perhaps a more specific deleteAllTxs should be created, also some logs could be good. - await removeDroppedThatHaveTxEffects(); + await removeMinedDroppedTxs(); await initializeRollupVersionCache(); await initializeProtocolContracts(); const aztecScanNotes = AZTEC_SCAN_NOTES[L2_NETWORK_ID]; @@ -39,6 +40,9 @@ ORIGIN: ${notes.origin}`); }); } } + // In archive mode too: a crash between a block's commit and its bump left + // that bump undone, and the writes above change cached reads as well. + await bumpChainRevision(); if (ARCHIVE_MODE) { logger.info( diff --git a/services/explorer-api/src/svcs/cache/chain-revision.ts b/services/explorer-api/src/svcs/cache/chain-revision.ts new file mode 100644 index 000000000..c9bf03a5e --- /dev/null +++ b/services/explorer-api/src/svcs/cache/chain-revision.ts @@ -0,0 +1,31 @@ +import { getEntry, setEntry } from "@chicmoz-pkg/redis-helper"; +import { randomUUID } from "node:crypto"; +import { logger } from "../../logger.js"; + +const CHAIN_REVISION = "chainRevision"; +const NO_REVISION = "none"; +// Longer than any entry it keys lives: a revision that expired back to +// NO_REVISION would serve the entries cached under it before the last bump. +const CHAIN_REVISION_TTL_SECONDS = 7 * 24 * 60 * 60; + +/** The last part of a chain read's cache key: a chain change retires it. */ +export const getChainRevision = async (): Promise => + (await getEntry([CHAIN_REVISION])).value ?? NO_REVISION; + +/** + * Retires every chain read cached so far. A random value, not a counter: the + * cache client has no atomic increment, and the keys only need a value never + * used before. A failed bump is logged, and those reads live out their TTL. + */ +export const bumpChainRevision = async (): Promise => { + const stored = await setEntry( + [CHAIN_REVISION], + randomUUID(), + CHAIN_REVISION_TTL_SECONDS, + ); + if (!stored) { + logger.warn( + "Could not bump the chain revision: cached chain reads live out their TTL", + ); + } +}; diff --git a/services/explorer-api/src/svcs/database/controllers/chain-lock.ts b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts new file mode 100644 index 000000000..658d9ddb3 --- /dev/null +++ b/services/explorer-api/src/svcs/database/controllers/chain-lock.ts @@ -0,0 +1,22 @@ +import { getDb as db } from "@chicmoz-pkg/postgres-helper"; +import { sql } from "drizzle-orm"; +import { L2_NETWORK_ID } from "../../../environment.js"; +import { type DbTx } from "./utils.js"; + +const LOCK_NAMESPACE = 1_815_307_112; + +/** + * Runs `fn` in one transaction that takes the network's chain lock before + * any other: every write that depends on which blocks are canonical takes + * it first, so those writers queue on it rather than deadlock over rows. + * `lock_timeout` bounds every lock wait in the transaction, this one + * included: a wait over 10 s throws. + */ +export const withChainLock = (fn: (dbTx: DbTx) => Promise): Promise => + db().transaction(async (dbTx) => { + await dbTx.execute(sql`SET LOCAL lock_timeout = '10s'`); + await dbTx.execute( + sql`SELECT pg_advisory_xact_lock(${LOCK_NAMESPACE}::int4, hashtext(${L2_NETWORK_ID}))`, + ); + return fn(dbTx); + }); diff --git a/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts b/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts index ac95cffae..73890ff19 100644 --- a/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts +++ b/services/explorer-api/src/svcs/database/controllers/dropped-tx/remove.ts @@ -1,10 +1,10 @@ import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { HexString } from "@chicmoz-pkg/types"; -import { eq } from "drizzle-orm"; +import { and, eq, exists, isNull, sql } from "drizzle-orm"; import { logger } from "../../../../logger.js"; import { droppedTx } from "../../../database/schema/dropped-tx/index.js"; -import { txEffect } from "../../schema/index.js"; -import { getDroppedTxs } from "./get-tx.js"; +import { body, l2Block, txEffect } from "../../schema/index.js"; +import { withChainLock } from "../chain-lock.js"; /** * Removes a dropped transaction by its hash @@ -14,8 +14,9 @@ import { getDroppedTxs } from "./get-tx.js"; */ export const removeDroppedTxByHash = async ( txHash: HexString, + executor: ReturnType = db(), ): Promise => { - const deletedEntries = await db() + const deletedEntries = await executor .delete(droppedTx) .where(eq(droppedTx.txHash, txHash)) .returning(); @@ -27,20 +28,25 @@ export const removeDroppedTxByHash = async ( return deletedEntries.length; }; -export const removeDroppedThatHaveTxEffects = async (): Promise => { - const allDroppedTxs = await getDroppedTxs(); - let count = 0; - for (const tx of allDroppedTxs) { - const txEffectRes = await db() - .select() - .from(txEffect) - .where(eq(txEffect.txHash, tx.txHash)) - .limit(1); - if (txEffectRes.length > 0) { - await removeDroppedTxByHash(tx.txHash); - count++; - } - } - logger.info(`๐Ÿ—‘๏ธ๐Ÿ—‘๏ธ๐Ÿ”ฅ๐Ÿ”ฅ removed ${count} dropped txs that already had a txEffect`); - return count; +/** Removes the dropped rows of txs a canonical block holds: those are mined. */ +export const removeMinedDroppedTxs = async (): Promise => { + const { rowCount } = await withChainLock((dbTx) => + dbTx.delete(droppedTx).where( + exists( + dbTx + .select({ one: sql`1` }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where( + and( + eq(txEffect.txHash, droppedTx.txHash), + isNull(l2Block.orphan_timestamp), + ), + ), + ), + ), + ); + logger.info(`๐Ÿ—‘๏ธ๐Ÿ—‘๏ธ๐Ÿ”ฅ๐Ÿ”ฅ removed ${rowCount ?? 0} dropped txs that are mined`); + return rowCount ?? 0; }; diff --git a/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts b/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts index afa9636a5..5f1180c47 100644 --- a/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/dropped-tx/store.ts @@ -3,8 +3,11 @@ import { ChicmozL2DroppedTx } from "@chicmoz-pkg/types"; import { logger } from "../../../../logger.js"; import { droppedTx } from "../../schema/dropped-tx/index.js"; -export const storeDroppedTx = async (tx: ChicmozL2DroppedTx): Promise => { - const res = await db() +export const storeDroppedTx = async ( + tx: ChicmozL2DroppedTx, + executor: ReturnType = db(), +): Promise => { + const res = await executor .insert(droppedTx) .values(tx) .onConflictDoNothing() diff --git a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts index 0cdb00926..73b3dd653 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2/tips.ts @@ -8,15 +8,18 @@ import { L2NetworkId, chicmozL2TipsSchema, } from "@chicmoz-pkg/types"; -import { and, desc, eq, isNull, sql } from "drizzle-orm"; +import { and, desc, eq, exists, isNull, lt, or, sql } from "drizzle-orm"; import { L2_NETWORK_ID } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; +import { l2ReorgBlockTable } from "../../schema/l2/reorg.js"; import { l2TipBoundaryMismatchTable, l2TipsTable, StoredL2Tips, } from "../../schema/l2/tips.js"; import { l2Block } from "../../schema/l2block/index.js"; +import { withChainLock } from "../chain-lock.js"; +import { type DbTx } from "../utils.js"; import { getCurrentRollupVersionNumber } from "./chain-info/rollup-version-cache.js"; type TipBucket = "finalized" | "proven" | "checkpointed" | "proposed"; @@ -103,10 +106,16 @@ const flattenTips = ( updatedAt: new Date(), }); -const getBoundaryBlock = async (height: number, rollupVersion: number | null) => { +type Executor = ReturnType; + +const getBoundaryBlock = async ( + executor: Executor, + height: number, + rollupVersion: number | null, +) => { const versionFilter = rollupVersion !== null ? eq(l2Block.version, rollupVersion) : undefined; - const rows = await db() + const rows = await executor .select({ hash: l2Block.hash }) .from(l2Block) .where( @@ -120,20 +129,33 @@ const getBoundaryBlock = async (height: number, rollupVersion: number | null) => return rows[0]?.hash; }; +const missingBoundaryReason = (bucket: TipBucket, height: number) => + `${bucket} boundary block ${height} is missing`; + const validateBoundary = async ( + executor: Executor, bucket: TipBucket, tips: ChicmozL2Tips, rollupVersion: number | null, ): Promise => { const tip = bucket === "proposed" ? tips.proposed : tips[bucket].block; - const boundaryHash = await getBoundaryBlock(tip.number, rollupVersion); + // A tier at block 0 names the genesis block, which is never stored: there + // is nothing to check it against. + if (tip.number === 0) { + return null; + } + const boundaryHash = await getBoundaryBlock( + executor, + tip.number, + rollupVersion, + ); if (!boundaryHash) { return { bucket, height: tip.number, expectedHash: tip.hash, observedDbHash: null, - reason: `${bucket} boundary block ${tip.number} is missing`, + reason: missingBoundaryReason(bucket, tip.number), }; } if (boundaryHash !== tip.hash) { @@ -148,6 +170,30 @@ const validateBoundary = async ( return null; }; +const findBoundaryMismatch = async ( + executor: Executor, + tips: ChicmozL2Tips, + rollupVersion: number | null, +): Promise => { + for (const bucket of [ + "finalized", + "proven", + "checkpointed", + "proposed", + ] as const) { + const mismatch = await validateBoundary( + executor, + bucket, + tips, + rollupVersion, + ); + if (mismatch) { + return mismatch; + } + } + return null; +}; + const mismatchId = ({ bucket, height, @@ -156,7 +202,11 @@ const mismatchId = ({ }: BoundaryValidationResult) => `${L2_NETWORK_ID}:${bucket}:${height}:${expectedHash}:${observedDbHash ?? "missing"}`; -const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { +const recordBoundaryMismatch = async ( + executor: Executor, + mismatch: BoundaryValidationResult, + rollupVersion: number | null, +) => { const values = { id: mismatchId(mismatch), l2NetworkId: L2_NETWORK_ID, @@ -167,9 +217,10 @@ const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { reason: mismatch.reason, lastSeenAt: new Date(), resolvedAt: null, + rollupVersion, }; - await db() + await executor .insert(l2TipBoundaryMismatchTable) .values(values) .onConflictDoUpdate({ @@ -179,55 +230,124 @@ const recordBoundaryMismatch = async (mismatch: BoundaryValidationResult) => { lastSeenAt: values.lastSeenAt, occurrenceCount: sql`${l2TipBoundaryMismatchTable.occurrenceCount} + 1`, resolvedAt: null, + rollupVersion, }, }); }; -const resolveBoundaryMismatches = async () => { - const database = db(); - if (typeof database.update !== "function") { - return; - } - await database - .update(l2TipBoundaryMismatchTable) +const MISMATCH_EXPIRY_MS = 24 * 60 * 60 * 1000; + +/** + * Resolves the open mismatches whose cause is gone: the canonical block at + * the height has the hash the tips named, a reorg record lists that hash, or + * the mismatch was last seen a day ago. Tips that validate at other heights + * resolve nothing. + */ +const resolveBoundaryMismatches = async (executor: Executor) => { + const mismatch = l2TipBoundaryMismatchTable; + await executor + .update(mismatch) .set({ resolvedAt: new Date() }) .where( and( - eq(l2TipBoundaryMismatchTable.l2NetworkId, L2_NETWORK_ID), - isNull(l2TipBoundaryMismatchTable.resolvedAt), + eq(mismatch.l2NetworkId, L2_NETWORK_ID), + isNull(mismatch.resolvedAt), + or( + lt(mismatch.lastSeenAt, new Date(Date.now() - MISMATCH_EXPIRY_MS)), + exists( + executor + .select({ one: sql`1` }) + .from(l2Block) + .where( + and( + eq(l2Block.hash, mismatch.expectedHash), + eq(l2Block.height, mismatch.height), + isNull(l2Block.orphan_timestamp), + ), + ), + ), + exists( + executor + .select({ one: sql`1` }) + .from(l2ReorgBlockTable) + .where(eq(l2ReorgBlockTable.hash, mismatch.expectedHash)), + ), + ), ), ); }; +const recordValidation = async ( + executor: Executor, + mismatch: BoundaryValidationResult | null, + rollupVersion: number | null, +) => { + if (mismatch) { + await recordBoundaryMismatch(executor, mismatch, rollupVersion); + } + await resolveBoundaryMismatches(executor); +}; + +/** + * Validates and stores tips under the network's chain lock: tips validated + * before a chain change and written after it would describe a chain that no + * longer exists. + */ export const upsertTips = async (event: L2TipsEvent) => { const tips = chicmozL2TipsSchema.parse(event.tips); const rollupVersion = await getCurrentRollupVersionNumber(); - let degradedReason: string | null = null; - let degradedMismatch: BoundaryValidationResult | null = null; - for (const bucket of ["finalized", "proven", "checkpointed", "proposed"] as const) { - const mismatch = await validateBoundary(bucket, tips, rollupVersion); + await withChainLock(async (dbTx) => { + const mismatch = await findBoundaryMismatch(dbTx, tips, rollupVersion); if (mismatch) { - degradedReason = mismatch.reason; - degradedMismatch = mismatch; - logger.warn(`L2 tips degraded: ${degradedReason}`); - break; + logger.warn(`L2 tips degraded: ${mismatch.reason}`); } - } - - const values = flattenTips({ ...event, tips }, degradedReason); - await db() - .insert(l2TipsTable) - .values(values) - .onConflictDoUpdate({ + const values = flattenTips({ ...event, tips }, mismatch?.reason ?? null); + await dbTx.insert(l2TipsTable).values(values).onConflictDoUpdate({ target: l2TipsTable.l2NetworkId, set: values, }); + await recordValidation(dbTx, mismatch, rollupVersion); + }); +}; - if (degradedMismatch) { - await recordBoundaryMismatch(degradedMismatch); +/** + * Validates the stored tips again inside a chain change, healthy or + * degraded: the change may have stored a block they name, or demoted one. + * A result that differs from the stored one is recorded, so a mismatch's + * occurrence count counts the chain changes that found it as well as tips + * events. An unchanged result records nothing, though the change may still + * have resolved an open mismatch. + */ +export const revalidateTips = async (dbTx: DbTx) => { + const [row] = await dbTx + .select() + .from(l2TipsTable) + .where(eq(l2TipsTable.l2NetworkId, L2_NETWORK_ID)) + .limit(1); + if (!row) { + return; + } + const rollupVersion = await getCurrentRollupVersionNumber(); + const mismatch = await findBoundaryMismatch( + dbTx, + toStoredTips(row), + rollupVersion, + ); + const degradedReason = mismatch?.reason ?? null; + if (degradedReason === row.degradedReason) { + await resolveBoundaryMismatches(dbTx); + return; + } + await dbTx + .update(l2TipsTable) + .set({ degradedReason, updatedAt: new Date() }) + .where(eq(l2TipsTable.l2NetworkId, L2_NETWORK_ID)); + if (mismatch) { + logger.warn(`L2 tips degraded: ${mismatch.reason}`); } else { - await resolveBoundaryMismatches(); + logger.info(`L2 tips valid again (was: ${row.degradedReason})`); } + await recordValidation(dbTx, mismatch, rollupVersion); }; export const getRecentBoundaryMismatches = async ( @@ -252,35 +372,59 @@ export const getTips = async ( return rows[0] ? toStoredTips(rows[0]) : null; }; -export const deriveNativeStatus = ( - block: Pick, +type StatusTipHeights = Record; + +/** + * The tip heights block statuses derive from, or null while the stored tips + * cannot be trusted. A missing proposed boundary block is usually one still on + * its way, so heights up to the validated checkpointed tip keep their status + * and only those above it are unknown. + */ +export const statusTipHeights = ( storedTips: StoredL2Tips | null, -): ChicmozL2NativeBlockStatus => { +): StatusTipHeights | null => { if (!storedTips) { - return "unknown"; + return null; } - if (storedTips.degradedReason) { - return "unknown"; + const heights = { + finalized: storedTips.finalized.block.number, + proven: storedTips.proven.block.number, + checkpointed: storedTips.checkpointed.block.number, + proposed: storedTips.proposed.number, + }; + if (!storedTips.degradedReason) { + return heights; + } + if ( + storedTips.degradedReason === + missingBoundaryReason("proposed", storedTips.proposed.number) + ) { + return { ...heights, proposed: heights.checkpointed }; } - if (block.orphan) { + return null; +}; + +export const deriveNativeStatus = ( + block: Pick, + storedTips: StoredL2Tips | null, +): ChicmozL2NativeBlockStatus => { + const tips = statusTipHeights(storedTips); + if (!tips || block.orphan) { return "unknown"; } const height = Number(block.height); - if (!Number.isSafeInteger(height) || height > storedTips.proposed.number) { + if (!Number.isSafeInteger(height) || height > tips.proposed) { return "unknown"; } - if (height <= storedTips.finalized.block.number) { + if (height <= tips.finalized) { return "finalized"; } - if (height <= storedTips.proven.block.number) { + if (height <= tips.proven) { return "proven"; } - if (height <= storedTips.checkpointed.block.number) { + if (height <= tips.checkpointed) { return "checkpointed"; } - if (height <= storedTips.proposed.number) { - return "proposed"; - } - return "unknown"; + return "proposed"; }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts index 4dd250c4c..959e108f1 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.ts @@ -5,6 +5,7 @@ import { l2TxL2ToL1Msg } from "../../schema/index.js"; export const deleteL2ToL1Msgs = async ( txHash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { - await db().delete(l2TxL2ToL1Msg).where(eq(l2TxL2ToL1Msg.txHash, txHash)); + await executor.delete(l2TxL2ToL1Msg).where(eq(l2TxL2ToL1Msg.txHash, txHash)); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts index c564733e9..ced104b45 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2PendingL2ToL1Msg/store.ts @@ -7,13 +7,14 @@ import { deleteL2ToL1Msgs } from "./delete.js"; export const storeL2ToL1Msgs = async ( txHash: HexString, msgs: ChicmozL2PendingL2ToL1Msg[], + executor: ReturnType = db(), ): Promise => { if (msgs.length === 0) { return; } // Delete-then-insert for idempotency (same pattern as public call requests) - await deleteL2ToL1Msgs(txHash); + await deleteL2ToL1Msgs(txHash, executor); const values = msgs.map((msg) => ({ txHash, @@ -23,7 +24,7 @@ export const storeL2ToL1Msgs = async ( content: msg.content, })); - await db().insert(l2TxL2ToL1Msg).values(values); + await executor.insert(l2TxL2ToL1Msg).values(values); logger.info(`๐Ÿ“จ Stored ${msgs.length} L2-to-L1 messages for tx: ${txHash}`); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts index d19cc799b..303e5153c 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Public-call/delete.ts @@ -5,9 +5,9 @@ import { l2TxPublicCallRequest } from "../../schema/index.js"; export const deletePublicCall = async ( txHash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { - // Delete existing public call requests for this txHash - await db() + await executor .delete(l2TxPublicCallRequest) .where(eq(l2TxPublicCallRequest.txHash, txHash)); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts b/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts index 0cde13760..22ba0421a 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Public-call/store.ts @@ -20,8 +20,9 @@ import { deletePublicCall } from "./delete.js"; const resolveArtifactNames = async ( contractAddress: string, functionSelector: string | undefined, + executor: ReturnType, ): Promise<{ contractName: string | null; functionName: string | null }> => { - const rows = await db() + const rows = await executor .select({ artifactContractName: l2ContractClassRegistered.artifactContractName, selectorMap: l2ContractClassRegistered.selectorMap, @@ -62,18 +63,20 @@ const resolveArtifactNames = async ( export const storePublicCallRequests = async ( txHash: HexString, publicCallRequests: PublicCallRequest[], + executor: ReturnType = db(), ): Promise => { if (publicCallRequests.length === 0) { return; } - await deletePublicCall(txHash); + await deletePublicCall(txHash, executor); const values = await Promise.all( publicCallRequests.map(async (request) => { const { contractName, functionName } = await resolveArtifactNames( request.contractAddress, request.functionSelector, + executor, ); return { txHash, @@ -89,7 +92,12 @@ export const storePublicCallRequests = async ( }), ); - await db().insert(l2TxPublicCallRequest).values(values); + // Two calls with one calldata share the key, and a conflict would abort the + // caller's transaction with it. + await executor + .insert(l2TxPublicCallRequest) + .values(values) + .onConflictDoNothing(); logger.info( `๐Ÿ“‹ Stored ${publicCallRequests.length} public call requests for tx: ${txHash}`, diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts index b2920ceb7..059ae09a5 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/delete.ts @@ -5,6 +5,7 @@ import { l2Tx } from "../../schema/index.js"; export const deleteTx = async ( hash: ChicmozL2PendingTx["txHash"], + executor: ReturnType = db(), ): Promise => { - await db().delete(l2Tx).where(eq(l2Tx.txHash, hash)).execute(); + await executor.delete(l2Tx).where(eq(l2Tx.txHash, hash)).execute(); }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts index 36b70236e..33b8737f0 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/store.ts @@ -18,8 +18,9 @@ export const storeL2Tx = async (tx: ChicmozL2PendingTx): Promise => { export const storeOrUpdateL2Tx = async ( tx: ChicmozL2PendingTx, + executor: ReturnType = db(), ): Promise => { - const res = await db() + const res = await executor .insert(l2Tx) .values(tx) .onConflictDoUpdate({ @@ -56,11 +57,11 @@ export const storeOrUpdateL2Tx = async ( // Store public call requests if they exist if (tx.publicCallRequests && tx.publicCallRequests.length > 0) { - await storePublicCallRequests(tx.txHash, tx.publicCallRequests); + await storePublicCallRequests(tx.txHash, tx.publicCallRequests, executor); } // Store L2-to-L1 messages if they exist if (tx.l2ToL1Msgs && tx.l2ToL1Msgs.length > 0) { - await storeL2ToL1Msgs(tx.txHash, tx.l2ToL1Msgs); + await storeL2ToL1Msgs(tx.txHash, tx.l2ToL1Msgs, executor); } }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts index 88b94dcce..c527af812 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2TxEffect/get-tx-effect.ts @@ -14,6 +14,7 @@ import { getTableColumns, gte, isNotNull, + isNull, lt, sql, } from "drizzle-orm"; @@ -105,14 +106,15 @@ export const getLatestTxEffects = async (): Promise< }); }; +// Height 0 is a bound like any other, so presence is checked, not truthiness. const generateWhereQuery = (from?: bigint, to?: bigint) => { - if (from && !to) { + if (from !== undefined && to === undefined) { return gte(l2Block.height, from); - } else if (!from && to) { + } else if (from === undefined && to !== undefined) { return lt(l2Block.height, to); } assert( - from && to, + from !== undefined && to !== undefined, "FATAL: cannot have both from and to undefined when generating where query", ); return and(gte(l2Block.height, from), lt(l2Block.height, to)); @@ -146,14 +148,18 @@ const _getTxEffects = async ( const rollupVersion = await getCurrentRollupVersionNumber(); const versionFilter = rollupVersion !== null ? eq(l2Block.version, rollupVersion) : undefined; + // A block off the chain keeps the effects no canonical block took: they + // are its history, not what its height holds. The latest list keeps them, + // flagged `isOrphaned`. + const heightFilter = and(isNull(l2Block.orphan_timestamp), versionFilter); let whereQuery; switch (args.getType) { case GetTypes.BlockHeightRange: - if (args.from ?? args.to) { + if (args.from !== undefined || args.to !== undefined) { whereQuery = joinQuery - .where(and(generateWhereQuery(args.from, args.to), versionFilter)) + .where(and(generateWhereQuery(args.from, args.to), heightFilter)) .orderBy(desc(l2Block.height), desc(txEffect.index)) .limit(DB_MAX_TX_EFFECTS); } else { @@ -169,7 +175,7 @@ const _getTxEffects = async ( and( eq(l2Block.height, args.blockHeight), eq(txEffect.index, args.txEffectIndex), - versionFilter, + heightFilter, ), ) .limit(1); @@ -304,13 +310,19 @@ export const getTxEffectDynamicWhere = async ( return chicmozL2TxEffectDeluxeSchema.parse(toParse); }; -export const txEffectExists = async (hash: HexString): Promise => { - const res = await db() +/** Whether a canonical block holds the tx: an effect a dead block keeps is not mined. */ +export const txEffectExists = async ( + hash: HexString, + executor: ReturnType = db(), +): Promise => { + const res = await executor .select({ txHash: txEffect.txHash, }) .from(txEffect) - .where(eq(txEffect.txHash, hash)) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where(and(eq(txEffect.txHash, hash), isNull(l2Block.orphan_timestamp))) .limit(1) .execute(); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts index 90ba720bf..15a0b0561 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -1,5 +1,5 @@ import { type Heartbeat } from "@chicmoz-pkg/message-bus"; -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; +import { CHAIN_WALK_BOUND } from "@chicmoz-pkg/message-registry"; import { type ChicmozL2Block, type HexString } from "@chicmoz-pkg/types"; import { and, asc, eq, gt, inArray, isNotNull, isNull, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; @@ -19,6 +19,8 @@ import { lastArchive, txEffect, } from "../../schema/l2block/index.js"; +import { withChainLock } from "../chain-lock.js"; +import { revalidateTips } from "../l2/tips.js"; import { storeBlockContracts, type BlockContracts, @@ -49,26 +51,10 @@ import { store, writeTxEffect } from "./store.js"; // descends from carries that chain's authority over the heights below it. /** Walks stop after this many steps; more canonical blocks than this above a tip is corrupted state. */ -export const WALK_BOUND = 10_000; +export const WALK_BOUND = CHAIN_WALK_BOUND; const HEARTBEAT_EVERY = 500; -const LOCK_NAMESPACE = 1_815_307_112; const ROWS_PER_STATEMENT = 1_000; -/** - * Runs `fn` in one transaction that first takes the network's chain lock, - * which every chain change takes; the dropped- and pending-tx handlers write - * without it. `lock_timeout` bounds every lock wait in the transaction, this - * one included: a wait over 10 s throws, so the message is redelivered. - */ -export const withChainLock = (fn: (dbTx: DbTx) => Promise): Promise => - db().transaction(async (dbTx) => { - await dbTx.execute(sql`SET LOCAL lock_timeout = '10s'`); - await dbTx.execute( - sql`SELECT pg_advisory_xact_lock(${LOCK_NAMESPACE}::int4, hashtext(${L2_NETWORK_ID}))`, - ); - return fn(dbTx); - }); - export type IncomingBlock = { block: ChicmozL2Block; contracts: BlockContracts; @@ -749,6 +735,9 @@ const settle = async ( [...new Set([...change.walked.values(), ...change.repairs])], (part) => recordRepairHeights(change.dbTx, part), ); + if (change.demoted.size > 0 || change.promoted.size > 0) { + await revalidateTips(change.dbTx); + } if (canonical) { await fulfilRepairHeight(change.dbTx, block.height); } diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts b/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts index e9409c19d..37d0ec6d7 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/get-block.ts @@ -17,7 +17,7 @@ import { import { DB_MAX_BLOCKS, L2_NETWORK_ID } from "../../../../environment.js"; import { l2ReorgBlockTable, l2ReorgTable } from "../../schema/l2/reorg.js"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { deriveNativeStatus, getTips } from "../l2/tips.js"; +import { deriveNativeStatus, getTips, statusTipHeights } from "../l2/tips.js"; import { getLatestBlockRollupVersion } from "./get-latest.js"; import { archive, @@ -127,17 +127,17 @@ export const getBlock = async ( export const getBlocksByNativeStatus = async ( options: BlockQueryOptions = {}, ): Promise => { - const tips = await getTips(); - if (!tips || tips.degradedReason) { + const tips = statusTipHeights(await getTips()); + if (!tips) { const latest = await getBlock(-1n, options); return latest ? [latest] : []; } const heights = [ - tips.finalized.block.number, - tips.proven.block.number, - tips.checkpointed.block.number, - tips.proposed.number, + tips.finalized, + tips.proven, + tips.checkpointed, + tips.proposed, ]; const blocks: ChicmozL2BlockLight[] = []; const seen = new Set(); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts index 392a31019..8c78d7fe2 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/missing-ranges.ts @@ -13,6 +13,7 @@ import { lte, ne, not, + notExists, or, sql, } from "drizzle-orm"; @@ -27,9 +28,9 @@ import { } from "../../../../environment.js"; import { logger } from "../../../../logger.js"; import { l2OpenGapTable } from "../../schema/l2/open-gap.js"; +import { l2TipBoundaryMismatchTable } from "../../schema/l2/tips.js"; import { l2Block } from "../../schema/l2block/index.js"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { getTips } from "../l2/tips.js"; import { getLatestBlockRollupVersion, getLatestHeight } from "./get-latest.js"; type GapRange = { from: number; to: number; statusHint: "proposed" }; @@ -517,11 +518,11 @@ const findPresentHeights = async (ranges: Array<{ from: number; to: number }>) = return new Set(rows.map((row) => Number(row.height))); }; +// Heights above the latest canonical block are still on their way in the +// ordered stream: asking for them would race it. const getReconciliationUpperBound = async () => { - const tips = await getTips(); const latestHeight = await getLatestHeight(); - const upperBound = tips?.proposed.number ?? (latestHeight ? Number(latestHeight) : 0); - return { tips, upperBound }; + return latestHeight === null ? 0 : Number(latestHeight); }; export const buildMissingBlockRangeRequest = async ({ @@ -533,7 +534,7 @@ export const buildMissingBlockRangeRequest = async ({ scanWindow?: number; maxBlocks?: number; }): Promise => { - const { upperBound } = await getReconciliationUpperBound(); + const upperBound = await getReconciliationUpperBound(); if (!Number.isSafeInteger(upperBound) || upperBound < 1) { logger.info(`Skipping ${reason} L2 block reconciliation: no upper bound`); return null; @@ -581,40 +582,75 @@ export const buildMissingBlockRangeRequest = async ({ }; }; -const parseTipBoundaryHeight = (degradedReason: string | undefined) => { - if (!degradedReason) { - return null; - } - const match = /boundary block (\d+) (?:is missing|hash mismatch)/u.exec(degradedReason); - if (!match?.[1]) { - return null; - } - const height = Number(match[1]); - return Number.isSafeInteger(height) && height > 0 ? height : null; -}; - +/** + * Asks for the window around an open tip-boundary mismatch: the least + * recently seen one whose window is not backing off. While the block + * consumer lags, a newer mismatch can appear on every tick; oldest first, it + * cannot keep an older one waiting. The request names the mismatch height + * first, then the rest of its window, and is sent again while the mismatch + * stays open (its heights may be present but wrong), with the same backoff + * as other gaps, whatever the window row's status: blocks landing in the + * window fulfil the row without resolving the mismatch. + */ export const buildTipBoundaryRepairRequest = async (): Promise => { - const tips = await getTips(); - const height = parseTipBoundaryHeight(tips?.degradedReason); - if (!height) { + // A window fits one request's block budget: wider, it would name heights + // no request could carry. + const repairWindow = Math.min( + L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW, + Math.floor((L2_BLOCK_RECONCILIATION_MAX_BLOCKS - 1) / 2), + ); + const rollupVersion = await getCurrentRollupVersionNumber(); + const mismatch = l2TipBoundaryMismatchTable; + // Every filter, the backoff included, applies before the limit: rows a + // tick would pass over must not hide one it would send. + const [candidate] = await db() + .select({ height: mismatch.height }) + .from(mismatch) + .where( + and( + eq(mismatch.l2NetworkId, L2_NETWORK_ID), + isNull(mismatch.resolvedAt), + // This version's, and those recorded before mismatches carried one. + rollupVersion === null + ? undefined + : or( + isNull(mismatch.rollupVersion), + eq(mismatch.rollupVersion, rollupVersion), + ), + // The listener fetches no height below 1. + gte(mismatch.height, 1), + notExists( + db() + .select({ one: sql`1` }) + .from(l2OpenGapTable) + .where( + and( + eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), + eq(l2OpenGapTable.reason, TIP_BOUNDARY_REASON), + eq( + l2OpenGapTable.fromHeight, + sql`greatest(1, ${mismatch.height} - ${repairWindow})`, + ), + eq( + l2OpenGapTable.toHeight, + sql`${mismatch.height} + ${repairWindow}`, + ), + not(gapDueSql(Date.now())), + ), + ), + ), + ), + ) + .orderBy(asc(mismatch.lastSeenAt)) + .limit(1); + if (!candidate) { return null; } - const repairWindow = L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW; + const { height } = candidate; const from = Math.max(1, height - repairWindow); const to = height + repairWindow; const id = gapId({ from, to, reason: TIP_BOUNDARY_REASON }); - // The window is re-sent whole while the tips stay degraded (its heights - // may be present but wrong), with the same backoff as other gaps, - // whatever the row's status: blocks landing in the window fulfil it - // without fixing a mismatch. - const [existing] = await db() - .select({ due: sql`${gapDueSql(Date.now())}` }) - .from(l2OpenGapTable) - .where(eq(l2OpenGapTable.id, id)); - if (existing && !existing.due) { - return null; - } const range = { from, to, statusHint: "proposed" as const }; // Reopening must not reset the backoff here: the row is "fulfilled" as // soon as its heights are present, mismatch or not. @@ -624,14 +660,24 @@ export const buildTipBoundaryRepairRequest = resetOnReopen: false, }); logger.warn( - `Requesting L2 tip-boundary repair around block ${height}: ${from}-${to}; reason=${tips?.degradedReason}`, + `Requesting L2 tip-boundary repair around block ${height}: ${from}-${to}`, ); + // The listener sends ranges in order, each from its lowest height, and + // its own width and block limits can be lower than the API's: the + // mismatch goes first, so a truncated request still carries it. + const ranges = [ + { from: height, to: height }, + { from, to: height - 1 }, + { from: height + 1, to }, + ] + .filter((part) => part.from <= part.to) + .map((part) => ({ ...part, statusHint: "proposed" as const })); return { request: { requestId: randomUUID(), requestedAt: Date.now(), reason: TIP_BOUNDARY_REASON, - ranges: [range], + ranges, maxBlocks: Math.min(L2_BLOCK_RECONCILIATION_MAX_BLOCKS, to - from + 1), }, markRequested: () => markGapsRequested([id]), diff --git a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts index 348f452c4..dc7b65d74 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -8,8 +8,20 @@ import { type ChicmozL2ContractInstanceVerifiedDeploymentArgumnetsSchema, type ChicmozL2PrivateFunctionBroadcastedEvent, type ChicmozL2UtilityFunctionBroadcastedEvent, + type HexString, } from "@chicmoz-pkg/types"; -import { and, eq, inArray, isNull, or } from "drizzle-orm"; +import { + and, + eq, + exists, + inArray, + isNotNull, + isNull, + or, + sql, + type SQL, +} from "drizzle-orm"; +import { type PgColumn } from "drizzle-orm/pg-core"; import { l2ContractClassRegistered, l2ContractInstanceDeployed, @@ -19,6 +31,7 @@ import { l2UtilityFunction, } from "../../../database/schema/l2contract/index.js"; import { l2TxPublicCallRequest } from "../../../database/schema/l2public-call/index.js"; +import { l2Block } from "../../schema/index.js"; import { buildSelectorMap, selectorMapValueToFunctionName, @@ -26,21 +39,82 @@ import { import { logger } from "../../../../logger.js"; import { type DbTx } from "../utils.js"; +/** + * A contract row's rule on a key conflict: it moves to `incoming` from a + * block off the chain, and its own block writes it again; another canonical + * block keeps it. + */ +const movesTo = ( + executor: ReturnType, + owner: PgColumn, + incoming: HexString, +): SQL => + sql`${eq(owner, incoming)} OR ${exists( + executor + .select({ one: sql`1` }) + .from(l2Block) + .where(and(eq(l2Block.hash, owner), isNotNull(l2Block.orphan_timestamp))), + )}`; + +/** + * Stores a deployment, or moves it as `movesTo` allows. Only its block + * changes: the arguments verified for the address, and its deployer metadata, + * stay. False when another canonical block keeps it. + */ export const storeContractInstanceDeployed = async ( instance: ChicmozL2ContractInstanceDeployedEvent, executor: ReturnType = db(), -): Promise => { +): Promise => { const { publicKeys, ...rest } = instance; - await executor + const stored = await executor .insert(l2ContractInstanceDeployed) - .values({ ...publicKeys, ...rest }); + .values({ ...publicKeys, ...rest }) + .onConflictDoUpdate({ + target: l2ContractInstanceDeployed.address, + set: { blockHash: rest.blockHash }, + setWhere: movesTo( + executor, + l2ContractInstanceDeployed.blockHash, + rest.blockHash, + ), + }) + .returning({ address: l2ContractInstanceDeployed.address }); + return stored.length > 0; }; +/** + * Stores an update, or moves it with its new block's values as `movesTo` + * allows. False when another canonical block keeps it. + */ export const storeContractInstanceUpdated = async ( instance: ChicmozL2ContractInstanceUpdatedEvent, executor: ReturnType = db(), -): Promise => { - await executor.insert(l2ContractInstanceUpdate).values({ ...instance }); +): Promise => { + const { + blockHash, + prevContractClassId, + newContractClassId, + timestampOfChange, + } = instance; + const stored = await executor + .insert(l2ContractInstanceUpdate) + .values({ ...instance }) + .onConflictDoUpdate({ + target: l2ContractInstanceUpdate.address, + set: { + blockHash, + prevContractClassId, + newContractClassId, + timestampOfChange, + }, + setWhere: movesTo( + executor, + l2ContractInstanceUpdate.blockHash, + blockHash, + ), + }) + .returning({ address: l2ContractInstanceUpdate.address }); + return stored.length > 0; }; export const storeContractInstanceVerifiedDeploymentArguments = async ( @@ -60,13 +134,32 @@ export const storeContractInstanceVerifiedDeploymentArguments = async ( }); }; +/** + * Stores a class, or moves it as `movesTo` allows. Only its block changes: + * the artifact and source verified for the class stay. False when another + * canonical block keeps it. + */ export const storeContractClass = async ( contractClass: ChicmozL2ContractClassRegisteredEvent, executor: ReturnType = db(), -): Promise => { - await executor.insert(l2ContractClassRegistered).values({ - ...contractClass, - }); +): Promise => { + const stored = await executor + .insert(l2ContractClassRegistered) + .values({ ...contractClass }) + .onConflictDoUpdate({ + target: [ + l2ContractClassRegistered.contractClassId, + l2ContractClassRegistered.version, + ], + set: { blockHash: contractClass.blockHash }, + setWhere: movesTo( + executor, + l2ContractClassRegistered.blockHash, + contractClass.blockHash, + ), + }) + .returning({ contractClassId: l2ContractClassRegistered.contractClassId }); + return stored.length > 0; }; export type BlockContracts = { @@ -75,11 +168,31 @@ export type BlockContracts = { instancesUpdated: ChicmozL2ContractInstanceUpdatedEvent[]; }; +const RETRYABLE_CLASSES = new Set(["08", "40", "53", "57", "58"]); + +/** + * Whether a rerun of the block can clear `e`: SQLSTATE classes 08 + * (connection), 40 (serialization failure, deadlock), 53 (insufficient + * resources), 57 (operator intervention) and 58 (system error, such as I/O), + * and 55P03 (lock timeout). + */ +const retryable = (e: unknown): boolean => { + // drizzle-orm 0.44 and later wrap pg's error, keeping it as `cause`. + const { code, cause } = (e ?? {}) as { + code?: unknown; + cause?: { code?: unknown }; + }; + const state = code ?? cause?.code; + return ( + typeof state === "string" && + (RETRYABLE_CLASSES.has(state.slice(0, 2)) || state === "55P03") + ); +}; + /** - * Stores a block's contract rows inside its transaction, each in a savepoint: - * a row that fails (a duplicate, or an instance whose class was never - * stored) is logged and skipped without aborting the block; a failed - * heartbeat, taken before each row, aborts it. + * Stores a canonical block's contract rows, each in a savepoint: a row that + * fails on its own data is logged and skipped, while a failed heartbeat or an + * error a retry can cure aborts the block. */ export const storeBlockContracts = async ( dbTx: DbTx, @@ -89,20 +202,23 @@ export const storeBlockContracts = async ( const each = async ( rows: T[], label: (row: T) => string, - write: (row: T, executor: DbTx) => Promise, + write: (row: T, executor: DbTx) => Promise, ) => { for (const row of rows) { await heartbeat(); try { - await dbTx.transaction((savepoint) => write(row, savepoint)); - } catch (e) { - if ((e as { code?: string }).code === "23505") { - logger.warn(`DB Duplicate: ${label(row)}`); - } else { - logger.error( - `Failed to store ${label(row)}: ${(e as Error).stack ?? String(e)}`, + if (!(await dbTx.transaction((savepoint) => write(row, savepoint)))) { + logger.warn( + `${label(row)} stays with the canonical block that holds it`, ); } + } catch (e) { + if (retryable(e)) { + throw e; + } + logger.error( + `Failed to store ${label(row)}: ${(e as Error).stack ?? String(e)}`, + ); } } }; diff --git a/services/explorer-api/src/svcs/database/controllers/ui/tables.ts b/services/explorer-api/src/svcs/database/controllers/ui/tables.ts index 023b5b911..dda084729 100644 --- a/services/explorer-api/src/svcs/database/controllers/ui/tables.ts +++ b/services/explorer-api/src/svcs/database/controllers/ui/tables.ts @@ -29,7 +29,7 @@ import { uiTxEffectTableSchema, } from "@chicmoz-pkg/types"; import { getCurrentRollupVersionNumber } from "../l2/chain-info/rollup-version-cache.js"; -import { deriveNativeStatus, getTips } from "../l2/tips.js"; +import { deriveNativeStatus, getTips, statusTipHeights } from "../l2/tips.js"; type GetBlocksByRange = { from: bigint | undefined; @@ -41,14 +41,15 @@ const statusFilterWhere = ( status: Exclude, l2Tips: Awaited>, ) => { - if (!l2Tips || l2Tips.degradedReason) { + const tips = statusTipHeights(l2Tips); + if (!tips) { return status === "unknown" ? isNull(l2Block.orphan_timestamp) : sql`false`; } - const finalizedHeight = BigInt(l2Tips.finalized.block.number); - const provenHeight = BigInt(l2Tips.proven.block.number); - const checkpointedHeight = BigInt(l2Tips.checkpointed.block.number); - const proposedHeight = BigInt(l2Tips.proposed.number); + const finalizedHeight = BigInt(tips.finalized); + const provenHeight = BigInt(tips.proven); + const checkpointedHeight = BigInt(tips.checkpointed); + const proposedHeight = BigInt(tips.proposed); switch (status) { case "proposed": diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts index f99df5a1a..a6dec8df1 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/blocks.ts @@ -89,8 +89,9 @@ export const openapi_GET_BLOCK: OpenAPIObject["paths"] = { export const GET_BLOCK = asyncHandler(async (req, res) => { const { heightOrHash } = getBlockByHeightOrHashSchema.parse(req).params; - const blockData = await dbWrapper.get(["l2", "blocks", heightOrHash], () => - db.l2Block.getBlock(heightOrHash), + const blockData = await dbWrapper.getOnChain( + ["l2", "blocks", heightOrHash], + () => db.l2Block.getBlock(heightOrHash), ); res.status(200).json(await parseWithFreshNativeStatuses(blockData)); }); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts index 00784e43a..72d4b3fb4 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/contract-instances.ts @@ -156,11 +156,13 @@ export const GET_L2_CONTRACT_INSTANCE = asyncHandler(async (req, res) => { }); return; } - const instanceData = await dbWrapper.get(contractInstanceKeys(address), () => - db.l2Contract.getL2DeployedContractInstanceByAddress( - address, - includeArtifactJson, - ), + const instanceData = await dbWrapper.getOnChain( + contractInstanceKeys(address), + () => + db.l2Contract.getL2DeployedContractInstanceByAddress( + address, + includeArtifactJson, + ), ); res.status(200).json(JSON.parse(instanceData)); }); @@ -276,7 +278,7 @@ export const GET_L2_CONTRACT_INSTANCES_BY_BLOCK_HASH = asyncHandler( getContractInstancesByBlockHashSchema.parse(req).params; const { includeArtifactJson } = getContractInstancesByBlockHashSchema.parse(req).query; - const instances = await dbWrapper.get( + const instances = await dbWrapper.getOnChain( ["l2", "contract-instances", "block", blockHash], () => db.l2Contract.getL2DeployedContractInstancesByBlockHash( @@ -348,7 +350,7 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( }, }, } = postVerifiedContractInstanceSchema.parse(req); - const instanceData = await dbWrapper.get( + const instanceData = await dbWrapper.getOnChain( ["l2", "contract-instances", address], () => db.l2Contract.getL2DeployedContractInstanceByAddress(address), ); @@ -508,11 +510,14 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( constructorArgs, }); + const instanceKeys = await dbWrapper.onChainKeys( + contractInstanceKeys(address), + ); if (!deployerMetadata) { const freshInstance = await l2Contract.getL2DeployedContractInstanceByAddress(address, true); await setEntry( - contractInstanceKeys(address), + instanceKeys, JSON.stringify(freshInstance), CACHE_TTL_SECONDS, ).catch((err) => { @@ -547,7 +552,7 @@ export const POST_L2_VERIFY_CONTRACT_INSTANCE_DEPLOYMENT = asyncHandler( await l2Contract.getL2DeployedContractInstanceByAddress(address, true); await setEntry( - contractInstanceKeys(address), + instanceKeys, JSON.stringify(newContractInstance), CACHE_TTL_SECONDS, ).catch((err) => { diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts index cb36470ef..a15b91c59 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/tx-effects.ts @@ -54,7 +54,7 @@ export const openapi_GET_L2_TX_EFFECTS_BY_BLOCK_HEIGHT: OpenAPIObject["paths"] = export const GET_L2_TX_EFFECTS_BY_BLOCK_HEIGHT = asyncHandler( async (req, res) => { const { blockHeight } = getTxEffectsByBlockHeightSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects"], () => db.l2TxEffect.getTxEffectsByBlockHeight(blockHeight), ); @@ -95,7 +95,7 @@ export const GET_L2_TX_EFFECT_BY_BLOCK_HEIGHT_AND_INDEX = asyncHandler( async (req, res) => { const { blockHeight, txEffectIndex } = getTxEffectByBlockHeightAndIndexSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects", txEffectIndex], () => db.l2TxEffect.getTxEffectByBlockHeightAndIndex( @@ -132,7 +132,7 @@ export const openapi_GET_L2_TX_EFFECT_BY_TX_EFFECT_HASH: OpenAPIObject["paths"] export const GET_L2_TX_EFFECT_BY_TX_EFFECT_HASH = asyncHandler( async (req, res) => { const { txEffectHash } = getTxEffectsByTxHashSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "txEffects", txEffectHash], () => db.l2TxEffect.getTxEffectByHash(txEffectHash), ); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts index bb0d99db6..996dde0b7 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/ui.ts @@ -122,7 +122,7 @@ export const openapi_GET_TX_EFFECTS_BY_BLOCK_HEIGHT_UI_TABLE: OpenAPIObject["pat export const GET_TX_EFFECTS_BY_BLOCK_HEIGHT_UI_TABLE = asyncHandler( async (req, res) => { const { blockHeight } = getTxEffectsByBlockHeightSchema.parse(req).params; - const txEffectsData = await dbWrapper.get( + const txEffectsData = await dbWrapper.getOnChain( ["l2", "blocks", blockHeight, "txEffects"], () => db.ui.getTxEffectForUiTable({ blockHeight, getType: 1 }), ); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts index 9b3f529e8..024c161d6 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/db-wrapper.ts @@ -5,13 +5,25 @@ import { CACHE_TTL_SECONDS, } from "../../../../../environment.js"; import { logger } from "../../../../../logger.js"; +import { getChainRevision } from "../../../../cache/chain-revision.js"; import { dbParseErrorCallback } from "../../../../database/controllers/utils.js"; import { controllers as db } from "../../../../database/index.js"; const LATEST_HEIGHT = "latestHeight"; -export const getLatestHeight = async () => { - const cacheRes = await getEntry([LATEST_HEIGHT]); +/** + * Keys for a read whose answer depends on which blocks are canonical. Take + * them before reading the data: a read that sees a bumped revision then sees + * the commit the bump follows. + */ +export const onChainKeys = async (keys: CacheKeys): Promise => [ + ...keys, + await getChainRevision(), +]; + +const latestHeightAt = async (revision: string) => { + const keys = [LATEST_HEIGHT, revision]; + const cacheRes = await getEntry(keys); const cachedVal = cacheRes.value; const isCached = cachedVal !== null && cachedVal !== undefined; if (isCached) { @@ -20,22 +32,30 @@ export const getLatestHeight = async () => { const dbVal = await db.l2Block.getLatestHeight().catch(dbParseErrorCallback); if (dbVal) { - await setEntry([LATEST_HEIGHT], dbVal.toString(), CACHE_LATEST_TTL_SECONDS); + await setEntry(keys, dbVal.toString(), CACHE_LATEST_TTL_SECONDS); return dbVal; } throw new Error("CACHE_ERROR: latest height not found"); }; +export const getLatestHeight = async () => + latestHeightAt(await getChainRevision()); + export const getLatest = async ( keys: CacheKeys, dbFn: () => Promise, ): Promise => { - const latestHeight = await getLatestHeight(); + const revision = await getChainRevision(); + const latestHeight = await latestHeightAt(revision); if (!latestHeight) { throw new Error("CACHE_ERROR: latest height not found"); } // NOTE: we add one second to the TTL to ensure that stale cache is not stored - return get([...keys, latestHeight], dbFn, CACHE_LATEST_TTL_SECONDS + 1); + return get( + [...keys, latestHeight, revision], + dbFn, + CACHE_LATEST_TTL_SECONDS + 1, + ); }; export const get = async ( @@ -61,3 +81,9 @@ export const get = async ( } throw new Error(`CACHE_ERROR: ${keys.toString()} not found`); }; + +/** `get` for a read whose answer depends on which blocks are canonical. */ +export const getOnChain = async ( + keys: CacheKeys, + dbFn: () => Promise, +): Promise => get(await onChainKeys(keys), dbFn); diff --git a/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap b/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap index cacc015df..6e5a2adaf 100644 --- a/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap +++ b/services/explorer-api/tests/characterization/__snapshots__/consumer-replay.corpus.test.ts.snap @@ -555,6 +555,14 @@ exports[`committed frames replayed into the explorer-api consumers > recorded lo { "args": [ "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", + "chain-locked transaction", + ], + "seam": "txEffectExists", + }, + { + "args": [ + "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", + "chain-locked transaction", ], "seam": "removeDroppedTxByHash", }, @@ -581,6 +589,7 @@ exports[`committed frames replayed into the explorer-api consumers > recorded lo "teardownGasLimitL2": 0, "txHash": "0x12bac4f40aa7b6d3b7f9a960ec18d12646d9e0ff390352033e2f69b80b47b38a", }, + "chain-locked transaction", ], "seam": "storeOrUpdateL2Tx", }, diff --git a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts index 5a8b2e5e8..4da8f7429 100644 --- a/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts +++ b/services/explorer-api/tests/characterization/consumer-replay.corpus.test.ts @@ -87,6 +87,20 @@ vi.mock("../../src/svcs/database/controllers/l2Tx/index.js", () => ({ vi.mock("../../src/svcs/database/controllers/dropped-tx/index.js", () => ({ removeDroppedTxByHash: seam.record("removeDroppedTxByHash", 0), })); +vi.mock( + "../../src/svcs/database/controllers/l2TxEffect/get-tx-effect.js", + () => ({ txEffectExists: seam.record("txEffectExists", false) }), +); +// Its transaction shows in the snapshot as the writes' last argument. +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (fn: (dbTx: unknown) => Promise) => + fn("chain-locked transaction"), +})); +// The block consumers bump it; its real module reads the Redis environment on +// import. +vi.mock("../../src/svcs/cache/chain-revision.js", () => ({ + bumpChainRevision: seam.record("bumpChainRevision"), +})); // Only the compile-result consumer uses it; its real module reads the Redis // environment on import. vi.mock( diff --git a/services/explorer-api/tests/integration/block-ingest.integration.test.ts b/services/explorer-api/tests/integration/block-ingest.integration.test.ts index 82dae0d91..c8260109b 100644 --- a/services/explorer-api/tests/integration/block-ingest.integration.test.ts +++ b/services/explorer-api/tests/integration/block-ingest.integration.test.ts @@ -55,6 +55,12 @@ describe("recorded blocks through the block handler", () => { }, ); + it("serves no tx effects at height 0", async () => { + const res = await api.request.get("/l2/blocks/0/tx-effects"); + expect(res.status).toBe(200); + expect(JSON.parse(res.text)).toEqual([]); + }); + it("links each published class and deployed instance to the block that carries it", async () => { const classes = recorded.flatMap(({ expected }) => expected.contractClassIds.map((id) => ({ id, blockHash: expected.hash })), diff --git a/services/explorer-api/tests/integration/block-reorg.integration.test.ts b/services/explorer-api/tests/integration/block-reorg.integration.test.ts index 5e5bd9bc4..2a374455b 100644 --- a/services/explorer-api/tests/integration/block-reorg.integration.test.ts +++ b/services/explorer-api/tests/integration/block-reorg.integration.test.ts @@ -1,3 +1,4 @@ +import { type HexString } from "@chicmoz-pkg/types"; import { deliver } from "@chicmoz/test-harness"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { @@ -7,6 +8,12 @@ import { orderedEvent, } from "./support/blocks.js"; import { loadChainReads } from "./support/chain.js"; +import { + rawArtifact, + readClassRow, + readDeploymentArguments, + seedStoredArtifact, +} from "./support/contracts.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -97,4 +104,94 @@ describe("block conflicts on a real database", () => { await store(new301); await settled(); }); + + it("moves the contract class and instance a replacing chain registers again to it, keeping what was verified for them, but never from a canonical block", async () => { + const { controllers } = await import("../../src/svcs/database/index.js"); + const chainAt400 = async ( + [classTx, deployTx]: HexString[], + version?: number, + ) => { + const publishing = await buildBlock(400n, [classTx], { + version, + effect: "publishesClass", + }); + const deploying = await buildBlock(401n, [deployTx], { + version, + parent: publishing, + effect: "deploysInstance", + }); + return { publishing, deploying }; + }; + const txs = [freshTxHash(), freshTxHash()]; + const replaced = await chainAt400(txs); + await store(replaced.publishing); + await store(replaced.deploying); + const [contractClassId] = await reads.classesOf(replaced.publishing.hash); + const [address] = await reads.instancesOf(replaced.deploying.hash); + expect([contractClassId, address]).not.toContain(undefined); + await seedStoredArtifact( + { contractClassId, version: 1 }, + rawArtifact("escrow_contract-Escrow"), + ); + const salt = freshTxHash(); + await controllers.l2Contract.storeContractInstanceVerifiedDeploymentArguments( + { + address, + salt, + deployer: `0x${"00".repeat(32)}`, + publicKeysString: "0x00", + constructorArgs: [], + }, + ); + + const replacing = await chainAt400(txs); + await store(replacing.publishing); + await store(replacing.deploying); + const owned = async () => [ + await reads.classesOf(replacing.publishing.hash), + await reads.instancesOf(replacing.deploying.hash), + ]; + expect(await owned()).toEqual([[contractClassId], [address]]); + expect(await readClassRow({ contractClassId, version: 1 })).toMatchObject({ + artifactContractName: "Escrow", + }); + expect(await readDeploymentArguments(address)).toMatchObject({ salt }); + + const other = await chainAt400([freshTxHash(), freshTxHash()], 2); + await store(other.publishing); + await store(other.deploying); + expect(await reads.stateOf(other.deploying.hash)).toBe("canonical"); + expect(await owned()).toEqual([[contractClassId], [address]]); + }); + + it("moves a contract update emitted again from a block off the chain with the new block's values, but never from another canonical block", async () => { + const { controllers } = await import("../../src/svcs/database/index.js"); + const address = `0x${"0a".repeat(32)}` as const; + const updateIn = (block: BuiltBlock, timestampOfChange: number) => + controllers.l2Contract.storeContractInstanceUpdated({ + address, + prevContractClassId: `0x${"01".repeat(32)}`, + newContractClassId: `0x${"02".repeat(32)}`, + timestampOfChange, + blockHash: block.hash, + }); + const replaced = await buildBlock(500n, [freshTxHash()]); + const replacing = await buildBlock(500n, [freshTxHash()]); + const child = await buildBlock(501n, [freshTxHash()], { + parent: replacing, + }); + await store(replaced); + await updateIn(replaced, 1_000); + await store(replacing); + + expect(await updateIn(replacing, 2_000)).toBe(true); + // Its own block, delivered again, writes it again. + expect(await updateIn(replacing, 2_000)).toBe(true); + await store(child); + expect(await updateIn(child, 3_000)).toBe(false); + expect(await reads.updateOf(address)).toEqual({ + blockHash: replacing.hash, + timestampOfChange: 2_000, + }); + }); }); diff --git a/services/explorer-api/tests/integration/chain-cache.integration.test.ts b/services/explorer-api/tests/integration/chain-cache.integration.test.ts new file mode 100644 index 000000000..d2aa7a7ce --- /dev/null +++ b/services/explorer-api/tests/integration/chain-cache.integration.test.ts @@ -0,0 +1,104 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +type Holder = { blockHash: HexString; isOrphaned: boolean }; +type Effect = Holder & { txHash: HexString }; + +describe("cached chain reads on a real database and Redis", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + let reads: Awaited>; + + const body = async (path: string): Promise => { + const res = await api.request.get(path); + expect(res.status, `GET ${path}: ${res.text.slice(0, 300)}`).toBe(200); + return res.body as T; + }; + const holder = ({ blockHash, isOrphaned }: Holder) => [blockHash, isOrphaned]; + const held = ({ txHash, ...rest }: Effect) => [txHash, ...holder(rest)]; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + reads = await loadChainReads(); + store = (b) => deliver(blockHandler, orderedEvent(b)); + }); + + afterAll(async () => { + await api?.close(); + }); + + // The prune leaves the tip's height, and so the latest height in the + // latest-block keys, as it was. + it("serves the block that replaced the tip, the tx and instance it took, and none of the replaced block's own txs, from a warm cache", async () => { + const parent = await buildBlock(1n, [freshTxHash()], { + effect: "publishesClass", + }); + const deployTx = freshTxHash(); + // Both blocks include the deploy tx, which moves; each has a tx of its own. + const atTip = () => + buildBlock(2n, [deployTx, freshTxHash()], { + parent, + effect: "deploysInstance", + }); + const replaced = await atTip(); + const replacing = await atTip(); + await store(parent); + await store(replaced); + const [address] = await reads.instancesOf(replaced.hash); + const served = async () => ({ + latest: (await body<{ hash: HexString }>("/l2/blocks/latest")).hash, + atHeight: (await body<{ hash: HexString }>("/l2/blocks/2")).hash, + replacedOnChain: !( + await body<{ orphan?: unknown }>(`/l2/blocks/${replaced.hash}`) + ).orphan, + txEffectsAtHeight: (await body("/l2/blocks/2/tx-effects")).map( + held, + ), + txEffectAtIndex: held(await body("/l2/blocks/2/tx-effects/1")), + txEffect: holder(await body(`/l2/tx-effects/${deployTx}`)), + instance: holder(await body(`/l2/contract-instances/${address}`)), + instancesOfReplaced: ( + await body<{ address: HexString }[]>( + `/l2/blocks/${replaced.hash}/contract-instances`, + ) + ).map((i) => i.address), + }); + const servedWith = (tip: BuiltBlock) => { + const [shared, own] = tip.txHashes; + return { + latest: tip.hash, + atHeight: tip.hash, + replacedOnChain: tip === replaced, + txEffectsAtHeight: [ + [own, tip.hash, false], + [shared, tip.hash, false], + ], + txEffectAtIndex: [own, tip.hash, false], + txEffect: [tip.hash, false], + instance: [tip.hash, false], + instancesOfReplaced: tip === replaced ? [address] : [], + }; + }; + expect(await served()).toEqual(servedWith(replaced)); + + await store(replacing); + + // The bump retired every warm entry: these reads come from the database. + expect(await served()).toEqual(servedWith(replacing)); + }); +}); diff --git a/services/explorer-api/tests/integration/chain-head.integration.test.ts b/services/explorer-api/tests/integration/chain-head.integration.test.ts index 912905fc9..718d4495a 100644 --- a/services/explorer-api/tests/integration/chain-head.integration.test.ts +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -17,6 +17,7 @@ import { orderedEvent, } from "./support/blocks.js"; import { heads, loadChainReads } from "./support/chain.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -54,7 +55,7 @@ describe("the canonical chain on a real database", () => { event: NewBlockEvent, ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; let holdChainLock: () => Promise<() => Promise>; - let lockWaiters: () => Promise; + let untilLockWaiters: (count: number, what: string) => Promise; let fulfilByHeight: (height: bigint) => Promise; let walkBound: number; @@ -63,7 +64,7 @@ describe("the canonical chain on a real database", () => { const { blockHandler, catchupHandler } = await import( "../../src/events/received/on-block/index.js" ); - const { WALK_BOUND, withChainLock } = await import( + const { WALK_BOUND } = await import( "../../src/svcs/database/controllers/l2block/canonical.js" ); const { markOpenGapsFulfilledByHeight } = await import( @@ -268,30 +269,7 @@ describe("the canonical chain on a real database", () => { await admin.disconnect(); } }; - holdChainLock = async () => { - let release: () => void = () => undefined; - let held: Promise = Promise.resolve(); - await new Promise((locked) => { - held = withChainLock(() => { - locked(); - return new Promise((resolve) => { - release = resolve; - }); - }); - }); - return async () => { - release(); - await held; - }; - }; - // Lock requests waiting in this file's database, where the chain lock is - // the only advisory lock taken. - lockWaiters = async () => { - const { rows } = await db.execute<{ waiting: number }>( - sql`SELECT count(*)::int AS waiting FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, - ); - return rows[0]?.waiting ?? 0; - }; + ({ holdChainLock, untilLockWaiters } = await loadChainLockProbes()); fulfilByHeight = markOpenGapsFulfilledByHeight; }); @@ -928,13 +906,7 @@ describe("the canonical chain on a real database", () => { catchup(fromCatchup).then(() => finished.push("catch-up")), ]); try { - const deadline = Date.now() + 5_000; - while ((await lockWaiters()) < 2) { - if (Date.now() > deadline) { - throw new Error("the consumers never waited on the chain lock"); - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } + await untilLockWaiters(2, "the consumers"); expect(finished).toEqual([]); } finally { await release(); @@ -985,7 +957,7 @@ describe("the canonical chain on a real database", () => { const tx = freshTxHash(); const block = await buildBlock(28_000n, [tx], { version: freshVersion(), - publishesClass: true, + effect: "publishesClass", }); let beats = 0; // The beats before its effect and before its class row pass; the next, diff --git a/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts b/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts new file mode 100644 index 000000000..cbae7aae5 --- /dev/null +++ b/services/explorer-api/tests/integration/l2-tips-block-race.integration.test.ts @@ -0,0 +1,193 @@ +import { type L2TipsEvent } from "@chicmoz-pkg/message-registry"; +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + buildChain, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +const word = (n: number): HexString => `0x${n.toString(16).padStart(64, "0")}`; + +// Tips and blocks arrive on separate topics, so tips can name a proposed +// block before it is stored, or one a later change demotes. Finalized 1, +// proven 2, checkpointed 3. +describe("native block statuses when the tips and the chain disagree", () => { + let api: ExplorerApiForTest; + let chain: BuiltBlock[]; + let deliverBlock: (block: BuiltBlock) => Promise; + let deliverTips: (proposed: BuiltBlock) => Promise; + let statusesOf: (heights: number[]) => Promise; + let degradedReason: () => Promise; + let openMismatches: (height: number) => Promise; + let unknownInUiTable: () => Promise; + let holdChainLock: () => Promise<() => Promise>; + let untilLockWaiters: (count: number, what: string) => Promise; + let takeOffChain: (block: BuiltBlock) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { l2TipsHandler } = await import( + "../../src/events/received/on-l2-tips.js" + ); + const { getBlock } = await import( + "../../src/svcs/database/controllers/l2block/get-block.js" + ); + const { getBlocksForUiTable } = await import( + "../../src/svcs/database/controllers/ui/tables.js" + ); + const tips = await import("../../src/svcs/database/controllers/l2/tips.js"); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { eq } = await import("drizzle-orm"); + + chain = await buildChain(1n, 5); + deliverBlock = (block) => deliver(blockHandler, orderedEvent(block)); + const at = (block: BuiltBlock, checkpoint: number) => ({ + block: { number: Number(block.height), hash: block.hash }, + checkpoint: { number: checkpoint, hash: word(0x500 + checkpoint) }, + }); + deliverTips = (proposed) => + deliver(l2TipsHandler, { + tips: { + proposed: { number: Number(proposed.height), hash: proposed.hash }, + checkpointed: at(chain[2], 3), + proven: at(chain[1], 2), + finalized: at(chain[0], 1), + }, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + statusesOf = (heights) => + Promise.all( + heights.map( + async (height) => + (await getBlock(BigInt(height)))?.nativeStatus ?? "absent", + ), + ); + degradedReason = async () => (await tips.getTips())?.degradedReason; + openMismatches = async (height) => + (await tips.getRecentBoundaryMismatches()) + .filter( + (mismatch) => !mismatch.resolvedAt && mismatch.height === height, + ) + .map(({ bucket, observedDbHash, occurrenceCount }) => ({ + bucket, + observedDbHash, + occurrenceCount, + })); + unknownInUiTable = async () => + ( + await getBlocksForUiTable({ + from: undefined, + to: undefined, + status: "unknown", + }) + ).map((block) => Number(block.height)); + ({ holdChainLock, untilLockWaiters } = await loadChainLockProbes()); + takeOffChain = async (block) => { + await (await import("@chicmoz-pkg/postgres-helper")) + .getDb() + .update(l2Block) + .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) + .where(eq(l2Block.hash, block.hash)); + }; + + for (const block of chain.slice(0, 3)) { + await deliverBlock(block); + } + }); + + afterAll(async () => { + await api?.close(); + }); + + // The cases build on each other, in order. + it("keeps the statuses up to the checkpointed tip while the proposed block is on its way", async () => { + await deliverTips(chain[4]); + await deliverBlock(chain[3]); + + expect(await degradedReason()).toBe("proposed boundary block 5 is missing"); + expect(await statusesOf([1, 2, 3, 4])).toEqual([ + "finalized", + "proven", + "checkpointed", + "unknown", + ]); + expect(await unknownInUiTable()).toEqual([4]); + // Storing block 4 validated again without counting another occurrence. + expect(await openMismatches(5)).toEqual([ + { bucket: "proposed", observedDbHash: null, occurrenceCount: 1 }, + ]); + }); + + it("counts the tips as valid once the block they name is stored", async () => { + await deliverBlock(chain[4]); + + expect(await degradedReason()).toBeUndefined(); + expect(await statusesOf([1, 4, 5])).toEqual([ + "finalized", + "proposed", + "proposed", + ]); + expect(await unknownInUiTable()).toEqual([]); + expect(await openMismatches(5)).toEqual([]); + }); + + it("keeps the tips degraded when the block stored at the proposed height has another hash", async () => { + const named = await buildBlock(6n, [freshTxHash()], { parent: chain[4] }); + const stored = await buildBlock(6n, [freshTxHash()], { parent: chain[4] }); + await deliverTips(named); + await deliverBlock(stored); + + expect(await degradedReason()).toBe( + `proposed boundary block 6 hash mismatch: db=${stored.hash} tip=${named.hash}`, + ); + expect(await statusesOf([1, 6])).toEqual(["unknown", "unknown"]); + chain.push(stored); + }); + + it("degrades healthy tips when a change demotes the block they name, and closes the mismatch the reorg explains", async () => { + const named = await buildBlock(7n, [freshTxHash()], { parent: chain[5] }); + await deliverBlock(named); + await deliverTips(named); + expect(await degradedReason()).toBeUndefined(); + + const replacing = await buildBlock(7n, [freshTxHash()], { + parent: chain[5], + }); + await deliverBlock(replacing); + + expect(await degradedReason()).toBe( + `proposed boundary block 7 hash mismatch: db=${replacing.hash} tip=${named.hash}`, + ); + expect(await statusesOf([1, 7])).toEqual(["unknown", "unknown"]); + expect(await openMismatches(7)).toEqual([]); + chain.push(replacing); + }); + + it("validates tips on the chain they are written against, so a demotion while they wait leaves them degraded", async () => { + const named = await buildBlock(8n, [freshTxHash()], { parent: chain[6] }); + await deliverBlock(named); + const release = await holdChainLock(); + const stored = deliverTips(named); + await untilLockWaiters(1, "the tips handler"); + await takeOffChain(named); + await release(); + await stored; + + expect(await degradedReason()).toBe("proposed boundary block 8 is missing"); + }); +}); diff --git a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts index efc26f211..0c293f669 100644 --- a/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -5,10 +5,12 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { type BuiltBlock, buildBlock, + buildChain, catchupEvent, freshTxHash, orderedEvent, } from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -37,9 +39,13 @@ describe("a replaced block that stays stored on a real database", () => { }, ) => Promise; let repairRequestCovers: (height: number) => Promise; + let lastSeenAgo: (height: number, ms: number) => Promise; + let mismatchOpenAt: (height: number) => Promise; + let reads: Awaited>; beforeAll(async () => { api = await startExplorerApiForTest(); + reads = await loadChainReads(); const { blockHandler, catchupHandler } = await import( "../../src/events/received/on-block/index.js" ); @@ -94,6 +100,24 @@ describe("a replaced block that stays stored on a real database", () => { ) ?? false ); }; + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { and, eq, isNull } = await import("drizzle-orm"); + const { l2TipBoundaryMismatchTable: mismatch } = await import( + "../../src/svcs/database/schema/l2/tips.js" + ); + lastSeenAgo = async (height, ms) => { + await getDb() + .update(mismatch) + .set({ lastSeenAt: new Date(Date.now() - ms) }) + .where(eq(mismatch.height, height)); + }; + mismatchOpenAt = async (height) => + ( + await getDb() + .select({ id: mismatch.id }) + .from(mismatch) + .where(and(eq(mismatch.height, height), isNull(mismatch.resolvedAt))) + ).length > 0; }); afterAll(async () => { @@ -135,41 +159,74 @@ describe("a replaced block that stays stored on a real database", () => { expect(await isDropped(t)).toBe(false); }); - it.fails( - "still requests a replaced height after the next tips validate at other heights", - async () => { - const chain: BuiltBlock[] = []; - for (let height = 400n; height <= 403n; height++) { - chain.push( - await buildBlock(height, [freshTxHash()], { parent: chain.at(-1) }), - ); - } - const [finalized, proven, checkpointed, replaced] = chain; - for (const block of chain) { - await store(block); - } - const replacing = await buildBlock(403n, [freshTxHash()], { - parent: checkpointed, + it("requests a replaced height while the tips validate at other heights, until the block they named arrives", async () => { + const chain: BuiltBlock[] = []; + for (let height = 400n; height <= 403n; height++) { + chain.push( + await buildBlock(height, [freshTxHash()], { parent: chain.at(-1) }), + ); + } + const [finalized, proven, checkpointed] = chain; + for (const block of chain) { + await store(block); + } + const replacing = await buildBlock(403n, [freshTxHash()], { + parent: checkpointed, + }); + const next = await buildBlock(404n, [freshTxHash()], { + parent: replacing, + }); + const tipsAt = (proposed: BuiltBlock) => + storeTips({ + proposed: { number: Number(proposed.height), hash: proposed.hash }, + finalized, + proven, + checkpointed, }); - const next = await buildBlock(404n, [freshTxHash()], { - parent: replacing, + + await tipsAt(replacing); + expect(await repairRequestCovers(403)).toBe(true); + + await store(next); + await tipsAt(next); + + // The next ordered block names a parent that is not stored, so the + // stored block at 403 leaves the chain and its height is asked for. + expect(await canonicalHash(403n)).toBeUndefined(); + expect(await reads.repairOpen(403)).toBe(true); + expect(await repairRequestCovers(403)).toBe(true); + + // The stored tips stay valid, and the block they named fills the height. + await storeLate(replacing); + + expect(await canonicalHash(403n)).toBe(replacing.hash); + expect(await mismatchOpenAt(403)).toBe(false); + expect(await repairRequestCovers(403)).toBe(false); + }); + + it("resolves a tip mismatch nothing fixed only a day after it was last seen", async () => { + const chain = await buildChain(500n, 4); + const [finalized, proven, checkpointed, stored] = chain; + for (const block of chain) { + await store(block); + } + const named = await buildBlock(503n, [freshTxHash()], { + parent: checkpointed, + }); + const tipsAt = (proposed: BuiltBlock) => + storeTips({ + proposed: { number: Number(proposed.height), hash: proposed.hash }, + finalized, + proven, + checkpointed, }); - const tipsAt = (proposed: BuiltBlock) => - storeTips({ - proposed: { number: Number(proposed.height), hash: proposed.hash }, - finalized, - proven, - checkpointed, - }); - - await tipsAt(replacing); - expect(await repairRequestCovers(403)).toBe(true); - - await store(next); - await tipsAt(next); - - expect(await canonicalHash(403n)).toBe(replaced.hash); - expect(await repairRequestCovers(403)).toBe(true); - }, - ); + await tipsAt(named); + await tipsAt(stored); + expect(await mismatchOpenAt(503)).toBe(true); + + await lastSeenAgo(503, 25 * 60 * 60 * 1000); + await tipsAt(stored); + + expect(await mismatchOpenAt(503)).toBe(false); + }); }); diff --git a/services/explorer-api/tests/integration/open-gap.integration.test.ts b/services/explorer-api/tests/integration/open-gap.integration.test.ts index 1bd7abdba..bd16ec1cd 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -32,6 +32,10 @@ const byFrom = (ranges: Range[] | null) => describe("open gap scheduling on a real database", () => { let api: ExplorerApiForTest; let tick: () => Promise; + let repairTick: () => Promise; + let mismatches: ( + rows: Array<{ height: number; seenAgoMs: number; version?: number }>, + ) => Promise; let blocks: (heights: number[], version?: number) => Promise; let arrive: (height: number) => Promise; let orphan: (height: number) => Promise; @@ -49,6 +53,7 @@ describe("open gap scheduling on a real database", () => { L2_BLOCK_RECONCILIATION_MAX_BLOCKS: "200", L2_BLOCK_RECONCILIATION_MAX_RANGES: "10", L2_BLOCK_RECONCILIATION_SCAN_WINDOW: "10000", + L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW: "5", }); api = await startExplorerApiForTest(); const { getDb } = await import("@chicmoz-pkg/postgres-helper"); @@ -56,11 +61,15 @@ describe("open gap scheduling on a real database", () => { const { l2OpenGapTable } = await import( "../../src/svcs/database/schema/l2/open-gap.js" ); + const { l2TipBoundaryMismatchTable } = await import( + "../../src/svcs/database/schema/l2/tips.js" + ); const { l2Block } = await import( "../../src/svcs/database/schema/l2block/index.js" ); const { buildMissingBlockRangeRequest, + buildTipBoundaryRepairRequest, fulfilRepairHeight, markOpenGapsFulfilledByHeight, recordRepairHeights, @@ -79,15 +88,36 @@ describe("open gap scheduling on a real database", () => { const db = getDb(); const hashOf = (height: number, version: number): HexString => `0x${version.toString(16).padStart(2, "0")}${height.toString(16).padStart(62, "0")}`; - // A cadence tick whose publish succeeds: what it would send, then the - // marking that follows the send. - tick = async () => { - const planned = await buildMissingBlockRangeRequest({ reason: "cadence" }); + // A tick whose publish succeeds: what it would send, then the marking + // that follows the send. + const sent = async ( + planned: Awaited>, + ) => { await planned?.markRequested(); return planned ? planned.request.ranges.map(({ from, to }): Range => [from, to]) : null; }; + tick = async () => + sent(await buildMissingBlockRangeRequest({ reason: "cadence" })); + repairTick = async () => sent(await buildTipBoundaryRepairRequest()); + mismatches = async (rows) => { + const now = Date.now(); + await db.insert(l2TipBoundaryMismatchTable).values( + rows.map(({ height, seenAgoMs, version = CURRENT }) => ({ + id: `SANDBOX:proposed:${height}`, + l2NetworkId: "SANDBOX" as const, + bucket: "proposed" as const, + height, + expectedHash: hashOf(height, version), + observedDbHash: null, + reason: `proposed boundary block ${height} is missing`, + firstSeenAt: new Date(now - seenAgoMs), + lastSeenAt: new Date(now - seenAgoMs), + rollupVersion: version, + })), + ); + }; blocks = async (heights, version = CURRENT) => { await db.insert(l2Block).values( heights.map((height) => ({ @@ -145,6 +175,7 @@ describe("open gap scheduling on a real database", () => { ).map(({ from, to }): Range => [from, to]); reset = async () => { await db.delete(l2OpenGapTable); + await db.delete(l2TipBoundaryMismatchTable); await db.delete(l2Block); }; }); @@ -235,6 +266,53 @@ describe("open gap scheduling on a real database", () => { expect(await tick()).toEqual([[170, 170], [180, 180]]); }); + it("sends the least recently seen of two due tip repairs first", async () => { + await mismatches([ + { height: 700, seenAgoMs: 10 * MINUTE }, + { height: 600, seenAgoMs: 20 * MINUTE }, + ]); + + expect((await repairTick())?.[0]).toEqual([600, 600]); + expect((await repairTick())?.[0]).toEqual([700, 700]); + }); + + it("sends a tip repair again once its window's backoff has passed, and not before", async () => { + await mismatches([{ height: 500, seenAgoMs: MINUTE }]); + expect((await repairTick())?.[0]).toEqual([500, 500]); + + // One request: the window waits two cadences. + expect(await repairTick()).toBeNull(); + await elapse(2 * CADENCE_MS); + expect((await repairTick())?.[0]).toEqual([500, 500]); + }); + + it("sends a due tip repair past more backed-off windows than the scheduler's candidates", async () => { + // Each seen before the due mismatch at 900, and more of them than the + // scheduler's 50 candidates. The first ticks request, and so back off, + // these windows; the one at 3 starts at height 1. + const backedOff = [3, ...span(1_001, 1_050)]; + await mismatches([ + // Never fetched: the listener starts at height 1. + { height: 0, seenAgoMs: 180 * MINUTE }, + ...backedOff.map((height, i) => ({ + height, + seenAgoMs: 120 * MINUTE - i * 1_000, + })), + { height: 950, seenAgoMs: 90 * MINUTE, version: OLD }, + { height: 900, seenAgoMs: 60 * MINUTE }, + ]); + + for (const height of backedOff) { + expect((await repairTick())?.[0]).toEqual([height, height]); + } + expect(await repairTick()).toEqual([ + [900, 900], + [895, 899], + [901, 905], + ]); + expect(await repairTick()).toBeNull(); + }); + it("does not let old-version blocks or old-chain gap rows hide a current-version gap", async () => { // The old chain is ahead of the current one, as right after an upgrade. await blocks(span(1, 120), OLD); diff --git a/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts b/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts new file mode 100644 index 000000000..d3e87047a --- /dev/null +++ b/services/explorer-api/tests/integration/pending-and-dropped.integration.test.ts @@ -0,0 +1,196 @@ +import { + type DroppedTxsEvent, + type PendingTxsEvent, +} from "@chicmoz-pkg/message-registry"; +import { + type ChicmozL2DroppedTx, + type HexString, + type PublicCallRequest, +} from "@chicmoz-pkg/types"; +import { deliver, frameBytes, loadFixture } from "@chicmoz/test-harness"; +import { BSON } from "bson"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { loadChainReads } from "./support/chain.js"; +import { loadChainLockProbes } from "./support/chain-lock.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +let lastVersion = 1_000; +const freshVersion = () => ++lastVersion; + +const droppedRow = (txHash: HexString): ChicmozL2DroppedTx => ({ + txHash, + createdAsPendingAt: Date.now(), + droppedAt: Date.now(), + dropReason: "dropped", +}); + +// Whether a tx counts as mined decides every write here, so each one runs on +// the chain lock that canonical changes take. +describe("pending and dropped txs on a real database", () => { + let api: ExplorerApiForTest; + let reads: Awaited>; + let probes: Awaited>; + let ordered: (b: BuiltBlock) => Promise; + let dropped: (txHash: HexString) => Promise; + let pending: ( + txHash: HexString, + publicCallRequests?: PublicCallRequest[], + ) => Promise; + let takeOffChain: (b: BuiltBlock) => Promise; + let isPending: (txHash: HexString) => Promise; + let storeDropped: (txHash: HexString) => Promise; + let sweep: () => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { droppedTxHandler } = await import( + "../../src/events/received/on-dropped-txs.js" + ); + const { pendingTxHandler } = await import( + "../../src/events/received/on-pending-txs.js" + ); + const { removeMinedDroppedTxs } = await import( + "../../src/svcs/database/controllers/dropped-tx/remove.js" + ); + const { storeDroppedTx } = await import( + "../../src/svcs/database/controllers/dropped-tx/store.js" + ); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { l2Tx } = await import( + "../../src/svcs/database/schema/l2tx/index.js" + ); + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { eq } = await import("drizzle-orm"); + const db = getDb(); + reads = await loadChainReads(); + probes = await loadChainLockProbes(); + + const { + txs: [recorded], + } = ( + BSON.deserialize( + frameBytes( + loadFixture("local-network", "frame", "pending-txs-event-1"), + ), + ) as { data: PendingTxsEvent } + ).data; + if (!recorded) { + throw new Error("the recorded pending-txs frame holds no tx"); + } + ordered = (b) => deliver(blockHandler, orderedEvent(b)); + dropped = (txHash) => + deliver(droppedTxHandler, { + txs: [droppedRow(txHash)], + } satisfies DroppedTxsEvent); + pending = (txHash, publicCallRequests) => + deliver(pendingTxHandler, { + txs: [{ ...recorded, txHash, publicCallRequests }], + } satisfies PendingTxsEvent); + takeOffChain = async (b) => { + await db + .update(l2Block) + .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) + .where(eq(l2Block.hash, b.hash)); + }; + isPending = async (txHash) => + ( + await db + .select({ txHash: l2Tx.txHash }) + .from(l2Tx) + .where(eq(l2Tx.txHash, txHash)) + ).length > 0; + storeDropped = (txHash) => storeDroppedTx(droppedRow(txHash)); + sweep = removeMinedDroppedTxs; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("serializes a dropped tx's write with the block that includes it on the chain lock, so the tx ends mined", async () => { + const tx = freshTxHash(); + const block = await buildBlock(1_000n, [tx], { version: freshVersion() }); + const deliveries: Promise[] = []; + + const release = await probes.holdChainLock(); + try { + deliveries.push(ordered(block)); + await probes.untilLockWaiters(1, "the block"); + deliveries.push(dropped(tx)); + await probes.untilLockWaiters(2, "the dropped-tx handler"); + } finally { + await release(); + await Promise.all(deliveries); + } + + expect(await reads.ownerOf(tx)).toBe(block.hash); + expect(await reads.isDropped(tx)).toBe(false); + }); + + it("counts a tx as mined only while a canonical block holds it: a dropped tx an off-chain block holds is stored, a pending tx a canonical block holds is not", async () => { + const version = freshVersion(); + const [mined, kept] = [freshTxHash(), freshTxHash()]; + const live = await buildBlock(2_000n, [mined], { version }); + const dead = await buildBlock(2_001n, [kept], { version, parent: live }); + await ordered(live); + await ordered(dead); + await takeOffChain(dead); + + await dropped(kept); + await pending(mined); + + expect(await reads.isDropped(kept)).toBe(true); + expect(await isPending(mined)).toBe(false); + }); + + it("stores a pending tx whose two public calls share their calldata", async () => { + const tx = freshTxHash(); + const call: PublicCallRequest = { + msgSender: `0x${"00".repeat(31)}0a`, + contractAddress: `0x${"00".repeat(31)}0b`, + isStaticCall: false, + calldataHash: `0x${"00".repeat(31)}0c`, + callType: "revertible", + functionSelector: "0x0000000d", + }; + + await pending(tx, [call, call]); + + expect(await isPending(tx)).toBe(true); + }); + + it("keeps a genuinely dropped tx through the start-up sweep, and removes the dropped row of a mined one", async () => { + const version = freshVersion(); + const [mined, kept, lost] = [freshTxHash(), freshTxHash(), freshTxHash()]; + const live = await buildBlock(3_000n, [mined], { version }); + const dead = await buildBlock(3_001n, [kept], { version, parent: live }); + await ordered(live); + await ordered(dead); + await takeOffChain(dead); + for (const tx of [mined, kept, lost]) { + await storeDropped(tx); + } + + await sweep(); + + expect([ + await reads.isDropped(mined), + await reads.isDropped(kept), + await reads.isDropped(lost), + ]).toEqual([false, true, true]); + }); +}); diff --git a/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts b/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts index fb04551d3..4a681b417 100644 --- a/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts +++ b/services/explorer-api/tests/integration/recorded-blocks.integration.test.ts @@ -11,6 +11,7 @@ import { type L1L2ValidatorEvent, type PendingTxsEvent, } from "@chicmoz-pkg/message-registry"; +import { type CacheKeys } from "@chicmoz-pkg/redis-helper"; import { BSON } from "bson"; import { existsSync, readFileSync } from "node:fs"; import { @@ -132,6 +133,14 @@ describe("recorded chain data read back through Postgres and Redis", () => { return body; }; + /** A chain read's keys at the current chain revision, which every stored block moves. */ + const chainKeys = async (keys: CacheKeys) => { + const { onChainKeys } = await import( + "../../src/svcs/http-server/routes/controllers/utils/db-wrapper.js" + ); + return onChainKeys(keys); + }; + beforeAll(async () => { api = await startExplorerApiForTest(); }); @@ -284,8 +293,12 @@ describe("recorded chain data read back through Postgres and Redis", () => { describe("contract instance verification", () => { const [address] = INSTANCES; const artifact = rawArtifact("auth_registry_contract-AuthRegistry"); - const instanceEntry = () => - cacheAt(api.stack, api.namespace, ["l2", "contract-instances", address]); + const instanceEntry = async () => + cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "contract-instances", address]), + ); let deploymentArguments: { publicKeysString: string; salt: string; @@ -315,7 +328,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // The POST reads the instance through the cache; a 200 while the row's // salt disagrees proves the answer came from the committed string. it("POST verifies the recorded deployment from the committed string of its cache entry", async () => { - const entry = instanceEntry(); + const entry = await instanceEntry(); await entry.remove(); const first = await verify({ verifiedDeploymentArguments: { @@ -416,7 +429,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // The entry now carries the notes and metadata, which the POST's reader // parses too; the salt control proves the committed string answered. it("POST verifies from the committed cache string that carries the notes and metadata", async () => { - const entry = instanceEntry(); + const entry = await instanceEntry(); await entry.remove(); const miss = await verify({ verifiedDeploymentArguments: { @@ -460,7 +473,7 @@ describe("recorded chain data read back through Postgres and Redis", () => { // Their cache entries are removed, as when they expire, so the routes // read the rows the verification left. it("class and instance read back with the stored artifact, deployment arguments and notes", async () => { - await instanceEntry().remove(); + await (await instanceEntry()).remove(); expect( snapshotOf( await get( @@ -513,11 +526,11 @@ describe("recorded chain data read back through Postgres and Redis", () => { it("GET /l2/rpc-nodes answers from the committed string of its cache entry", async () => { const path = "/l2/rpc-nodes"; await deliverRpcNode(); - const entry = cacheAt(api.stack, api.namespace, [ - "l2", - "rpc-nodes", - LOCAL_TIP, - ]); + const entry = cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "rpc-nodes", LOCAL_TIP]), + ); await entry.remove(); expect(await get(path, path)).toHaveLength(1); const committed = await pinCacheString(entry, "rpc-nodes"); @@ -533,12 +546,11 @@ describe("recorded chain data read back through Postgres and Redis", () => { await deliverRpcNode(); const { rpcNodeName } = RPC_NODE.rpcNode; const path = `/l2/rpc-nodes/${rpcNodeName}`; - const entry = cacheAt(api.stack, api.namespace, [ - "l2", - "rpc-nodes", - rpcNodeName, - LOCAL_TIP, - ]); + const entry = cacheAt( + api.stack, + api.namespace, + await chainKeys(["l2", "rpc-nodes", rpcNodeName, LOCAL_TIP]), + ); await entry.remove(); await get(path, "/l2/rpc-nodes/:rpcNodeName"); // The node's own times come from its payload and the frozen clock; only diff --git a/services/explorer-api/tests/integration/start-up.integration.test.ts b/services/explorer-api/tests/integration/start-up.integration.test.ts new file mode 100644 index 000000000..878bfb2eb --- /dev/null +++ b/services/explorer-api/tests/integration/start-up.integration.test.ts @@ -0,0 +1,74 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +type ChainRevision = typeof import("../../src/svcs/cache/chain-revision.js"); + +const crash = vi.hoisted(() => ({ beforeBump: false })); + +// A crash right after a block's commit: the block is stored, and nothing +// after the commit runs. +vi.mock("../../src/svcs/cache/chain-revision.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + bumpChainRevision: () => + crash.beforeBump + ? Promise.reject(new Error("crashed before the bump")) + : actual.bumpChainRevision(), + }; +}); + +describe("explorer-api start-up on a real database and Redis", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + + beforeAll(async () => { + // Archive mode starts without consuming or reconciling. + vi.stubEnv("ARCHIVE_MODE", "true"); + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + store = (b) => deliver(blockHandler, orderedEvent(b)); + }); + + afterAll(async () => { + await api?.close(); + vi.unstubAllEnvs(); + }); + + it("serves the block that replaced a cached one once it starts, after a crash cut off that block's bump", async () => { + const atHeight = async () => { + const res = await api.request.get("/l2/blocks/2"); + expect(res.status, res.text.slice(0, 300)).toBe(200); + return (res.body as { hash: HexString }).hash; + }; + const parent = await buildBlock(1n, [freshTxHash()]); + const replaced = await buildBlock(2n, [freshTxHash()], { parent }); + const replacing = await buildBlock(2n, [freshTxHash()], { parent }); + await store(parent); + await store(replaced); + expect(await atHeight()).toBe(replaced.hash); + + crash.beforeBump = true; + await expect(store(replacing)).rejects.toThrow("crashed before the bump"); + crash.beforeBump = false; + expect(await atHeight()).toBe(replaced.hash); + + const { start } = await import("../../src/start.js"); + await start(); + + expect(await atHeight()).toBe(replacing.hash); + }); +}); diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index 121ea0236..0ae58aee7 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -41,25 +41,38 @@ const recorded = ( return L2Block.fromBuffer(Buffer.from(fixture.data.hex, "hex")); }; -// A recorded effect with public logs and no contract-class logs, so storing a -// clone adds no contract rows that would collide across blocks. -let plain: L2Block | undefined; -// A recorded effect that publishes a contract class. Its clones share the -// class row, so only the first one stored in a database adds it. -let publishing: L2Block | undefined; -const baseBlock = (publishesClass: boolean): L2Block => - publishesClass - ? (publishing ??= recorded( - "a contract class log", - (e) => e.counts.contractClassLogs > 0, - )) - : (plain ??= recorded( - "public logs and no contract logs", - (e) => - e.counts.publicLogs > 0 && - e.counts.contractClassLogs === 0 && - e.contractInstanceAddresses.length === 0, - )); +type Effect = "plain" | "publishesClass" | "deploysInstance"; + +// Recorded effects to clone. A plain one has public logs and no contract +// logs, so its clones add no contract rows. The others publish the recorded +// contract class and deploy the recorded instance of it: their clones share +// one row each. +const EFFECTS: Record< + Effect, + [string, (expected: FixtureData["l2-block"]["expected"]) => boolean] +> = { + plain: [ + "public logs and no contract logs", + (e) => + e.counts.publicLogs > 0 && + e.counts.contractClassLogs === 0 && + e.contractInstanceAddresses.length === 0, + ], + publishesClass: [ + "a contract class log", + (e) => e.counts.contractClassLogs > 0, + ], + deploysInstance: [ + "a contract instance deployment", + (e) => e.contractInstanceAddresses.length > 0, + ], +}; +const bases = new Map(); +const baseBlock = (effect: Effect): L2Block => { + const base = bases.get(effect) ?? recorded(...EFFECTS[effect]); + bases.set(effect, base); + return base; +}; /** * The coinbase is salted to tell headers at one height apart. The handler @@ -67,7 +80,7 @@ const baseBlock = (publishesClass: boolean): L2Block => * `version` replaces the recorded rollup version. Each block gets an archive * of its own, unless `archive` names one; `parent` makes the block's last * archive the parent's archive, the link a chain's consecutive blocks have. - * `publishesClass` clones an effect that publishes a contract class. + * `effect` names the recorded effect the txs clone. */ export const buildBlock = async ( height: bigint, @@ -76,15 +89,15 @@ export const buildBlock = async ( version, parent, archive: sharedArchive, - publishesClass, + effect: cloned = "plain", }: { version?: number; parent?: Pick; archive?: AppendOnlyTreeSnapshot; - publishesClass?: true; + effect?: Effect; } = {}, ): Promise => { - const base = baseBlock(publishesClass === true); + const base = baseBlock(cloned); const [effect] = base.body.txEffects; if (!effect) { throw new Error("base block has no tx effect"); diff --git a/services/explorer-api/tests/integration/support/chain-lock.ts b/services/explorer-api/tests/integration/support/chain-lock.ts new file mode 100644 index 000000000..a922271a3 --- /dev/null +++ b/services/explorer-api/tests/integration/support/chain-lock.ts @@ -0,0 +1,52 @@ +/** + * Probes of the network's chain lock on a test file's database. Call after + * startExplorerApiForTest, like any explorer-api import. + */ +export const loadChainLockProbes = async () => { + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { sql } = await import("drizzle-orm"); + const { withChainLock } = await import( + "../../../src/svcs/database/controllers/chain-lock.js" + ); + const db = getDb(); + + /** Takes the chain lock and holds it until the returned release is awaited. */ + const holdChainLock = async () => { + let release: () => void = () => undefined; + let held: Promise = Promise.resolve(); + await new Promise((locked) => { + held = withChainLock(() => { + locked(); + return new Promise((resolve) => { + release = resolve; + }); + }); + }); + return async () => { + release(); + await held; + }; + }; + + // Lock requests waiting in this file's database, where the chain lock is + // the only advisory lock taken. + const lockWaiters = async () => { + const { rows } = await db.execute<{ waiting: number }>( + sql`SELECT count(*)::int AS waiting FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND database = (SELECT oid FROM pg_database WHERE datname = current_database())`, + ); + return rows[0]?.waiting ?? 0; + }; + + /** Resolves once `count` requests wait on the lock; throws after 5 s. */ + const untilLockWaiters = async (count: number, what: string) => { + const deadline = Date.now() + 5_000; + while ((await lockWaiters()) < count) { + if (Date.now() > deadline) { + throw new Error(`${what} never waited on the chain lock`); + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } + }; + + return { holdChainLock, untilLockWaiters }; +}; diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts index b60dd9995..2eecc53c2 100644 --- a/services/explorer-api/tests/integration/support/chain.ts +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -39,9 +39,11 @@ export const loadChainReads = async () => { const { l2OpenGapTable } = await import( "../../../src/svcs/database/schema/l2/open-gap.js" ); - const { l2ContractClassRegistered } = await import( - "../../../src/svcs/database/schema/l2contract/index.js" - ); + const { + l2ContractClassRegistered, + l2ContractInstanceDeployed, + l2ContractInstanceUpdate, + } = await import("../../../src/svcs/database/schema/l2contract/index.js"); const { getReorgs } = await import( "../../../src/svcs/database/controllers/l2block/get-block.js" ); @@ -92,6 +94,26 @@ export const loadChainReads = async () => { .where(eq(l2ContractClassRegistered.blockHash, blockHash)) ).map(({ id }) => id); + /** The addresses of the contract instances deployed with a block. */ + const instancesOf = async (blockHash: HexString) => + ( + await db + .select({ address: l2ContractInstanceDeployed.address }) + .from(l2ContractInstanceDeployed) + .where(eq(l2ContractInstanceDeployed.blockHash, blockHash)) + ).map(({ address }) => address); + + const updateOf = async (address: string) => { + const [row] = await db + .select({ + blockHash: l2ContractInstanceUpdate.blockHash, + timestampOfChange: l2ContractInstanceUpdate.timestampOfChange, + }) + .from(l2ContractInstanceUpdate) + .where(eq(l2ContractInstanceUpdate.address, address)); + return row; + }; + const isDropped = async (txHash: HexString) => ( await db @@ -169,6 +191,8 @@ export const loadChainReads = async () => { stateOf, ownerOf, classesOf, + instancesOf, + updateOf, isDropped, recordsOf, listed, diff --git a/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts b/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts new file mode 100644 index 000000000..2c8b9f254 --- /dev/null +++ b/services/explorer-api/tests/integration/young-chain-tips.integration.test.ts @@ -0,0 +1,84 @@ +import { type L2TipsEvent } from "@chicmoz-pkg/message-registry"; +import { type HexString } from "@chicmoz-pkg/types"; +import { deliver } from "@chicmoz/test-harness"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { type BuiltBlock, buildChain, orderedEvent } from "./support/blocks.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +const word = (n: number): HexString => `0x${n.toString(16).padStart(64, "0")}`; + +// Until a tier moves past block 0 it names the genesis block, which the +// chain never stores. +describe("the tips of a young chain on a real database", () => { + let api: ExplorerApiForTest; + let store: (block: BuiltBlock) => Promise; + let storeTips: (tips: L2TipsEvent["tips"]) => Promise; + let degradedReason: () => Promise; + let openMismatchHeights: () => Promise; + let statusesOf: (heights: number[]) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { l2TipsHandler } = await import( + "../../src/events/received/on-l2-tips.js" + ); + const { getBlock } = await import( + "../../src/svcs/database/controllers/l2block/get-block.js" + ); + const tips = await import("../../src/svcs/database/controllers/l2/tips.js"); + store = (block) => deliver(blockHandler, orderedEvent(block)); + storeTips = (tipsOf) => + deliver(l2TipsHandler, { + tips: tipsOf, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + degradedReason = async () => (await tips.getTips())?.degradedReason; + openMismatchHeights = async () => + (await tips.getRecentBoundaryMismatches()) + .filter((mismatch) => !mismatch.resolvedAt) + .map((mismatch) => mismatch.height); + statusesOf = (heights) => + Promise.all( + heights.map( + async (height) => + (await getBlock(BigInt(height)))?.nativeStatus ?? "absent", + ), + ); + }); + + afterAll(async () => { + await api?.close(); + }); + + it("keeps the tips healthy while the proven and finalized tiers are at block 0", async () => { + const [first, second, third] = await buildChain(1n, 3); + await store(first); + await store(second); + const genesis = { + block: { number: 0, hash: word(0x10) }, + checkpoint: { number: 0, hash: word(0x500) }, + }; + await storeTips({ + proposed: { number: 2, hash: second.hash }, + checkpointed: { + block: { number: 1, hash: first.hash }, + checkpoint: { number: 1, hash: word(0x501) }, + }, + proven: genesis, + finalized: genesis, + }); + // A chain change validates the stored tips again. + await store(third); + + expect(await degradedReason()).toBeUndefined(); + expect(await openMismatchHeights()).toEqual([]); + expect(await statusesOf([1, 2])).toEqual(["checkpointed", "proposed"]); + }); +}); diff --git a/services/explorer-api/tests/unit/block-contract-row-errors.test.ts b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts new file mode 100644 index 000000000..98f6686ed --- /dev/null +++ b/services/explorer-api/tests/unit/block-contract-row-errors.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@chicmoz-pkg/postgres-helper", () => ({ getDb: vi.fn() })); +vi.mock("../../src/logger.js", () => ({ + logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, +})); +vi.mock("../../src/utils/resolve-artifact-names.js", () => ({ + buildSelectorMap: vi.fn(), + selectorMapValueToFunctionName: vi.fn(), +})); + +const { storeBlockContracts } = await import( + "../../src/svcs/database/controllers/l2contract/store.js" +); + +type DbTx = Parameters[0]; + +const contracts = { + classes: [{ contractClassId: "0x0a" }, { contractClassId: "0x0b" }], + instancesDeployed: [], + instancesUpdated: [], +} as unknown as Parameters[1]; + +// pg's error for a failed statement carries its SQLSTATE as `code`. +const pgError = (code: string, message: string) => + Object.assign(new Error(message), { code }); + +// The first row's savepoint rejects with `error`; every later one stores. +const failFirstSavepoint = (error: Error) => { + const transaction = vi + .fn() + .mockRejectedValueOnce(error) + .mockResolvedValue(true); + return { transaction, dbTx: { transaction } as unknown as DbTx }; +}; + +const lockTimeout = () => + pgError("55P03", "canceling statement due to lock timeout"); + +describe("a contract row whose savepoint fails", () => { + it.each([ + { fault: "a lock timeout as pg throws it", error: lockTimeout() }, + { + fault: "a lock timeout wrapped as a query error's cause", + error: Object.assign(new Error("Failed query"), { cause: lockTimeout() }), + }, + { + fault: "an I/O error", + error: pgError("58030", "could not read block 0 in file: I/O error"), + }, + ])( + "aborts the block on $fault, so the bus redelivers it", + async ({ error }) => { + const { transaction, dbTx } = failFirstSavepoint(error); + + await expect( + storeBlockContracts(dbTx, contracts, () => Promise.resolve()), + ).rejects.toBe(error); + expect(transaction).toHaveBeenCalledTimes(1); + }, + ); + + it("skips a row that fails on its own data and stores the next", async () => { + const { transaction, dbTx } = failFirstSavepoint( + pgError("23505", "duplicate key value violates unique constraint"), + ); + + await storeBlockContracts(dbTx, contracts, () => Promise.resolve()); + expect(transaction).toHaveBeenCalledTimes(2); + }); +}); diff --git a/services/explorer-api/tests/unit/l2-tips-native-status.test.ts b/services/explorer-api/tests/unit/l2-tips-native-status.test.ts index ee8132321..37243e082 100644 --- a/services/explorer-api/tests/unit/l2-tips-native-status.test.ts +++ b/services/explorer-api/tests/unit/l2-tips-native-status.test.ts @@ -26,9 +26,12 @@ const mocks = vi.hoisted(() => { return { onConflictDoUpdate }; }); const insert = vi.fn(() => ({ values })); + const update = vi.fn(() => ({ + set: () => ({ where: () => Promise.resolve() }), + })); return { - db: { insert, select }, + db: { insert, select, update }, from, limit, onConflictDoUpdate, @@ -49,6 +52,10 @@ vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX", })); +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (fn: (dbTx: unknown) => Promise) => fn(mocks.db), +})); + vi.mock("../../src/logger.js", () => ({ logger: { debug: vi.fn(), @@ -162,7 +169,7 @@ describe("deriveNativeStatus", () => { expect( deriveNativeStatus( { hash: hash(1), height: 1n }, - { ...storedTips, degradedReason: "proposed boundary block 100 is missing" }, + { ...storedTips, degradedReason: "checkpointed boundary block 80 is missing" }, ), ).toBe("unknown"); expect( @@ -243,7 +250,7 @@ describe("upsertTips", () => { await upsertTips(tipsEvent); expect(mocks.getCurrentRollupVersionNumber).toHaveBeenCalledOnce(); - expect(mocks.where).toHaveBeenCalledTimes(4); + expect(mocks.limit).toHaveBeenCalledTimes(4); expect(mocks.state.insertValues[0]).toMatchObject({ degradedReason: null }); }); }); diff --git a/services/explorer-api/tests/unit/mempool-heartbeats.test.ts b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts new file mode 100644 index 000000000..d6878e12f --- /dev/null +++ b/services/explorer-api/tests/unit/mempool-heartbeats.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from "vitest"; + +const order = vi.hoisted(() => [] as string[]); + +vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX" })); +vi.mock("../../src/logger.js", () => ({ + logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, +})); +vi.mock("../../src/svcs/database/controllers/chain-lock.js", () => ({ + withChainLock: (write: (dbTx: unknown) => Promise) => { + order.push("lock"); + return write({}); + }, +})); +vi.mock( + "../../src/svcs/database/controllers/l2TxEffect/get-tx-effect.js", + () => ({ txEffectExists: () => Promise.resolve(false) }), +); +vi.mock("../../src/svcs/database/controllers/l2Tx/index.js", () => ({ + deleteTx: vi.fn(), + storeOrUpdateL2Tx: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/index.js", () => ({ + removeDroppedTxByHash: () => Promise.resolve(0), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/store.js", () => ({ + storeDroppedTx: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/l2Public-call/delete.js", () => ({ + deletePublicCall: vi.fn(), +})); +vi.mock( + "../../src/svcs/database/controllers/l2PendingL2ToL1Msg/delete.js", + () => ({ deleteL2ToL1Msgs: vi.fn() }), +); +// The loop under test starts after parsing; any tx object passes here. +vi.mock("@chicmoz-pkg/types", async (importOriginal) => ({ + ...(await importOriginal()), + chicmozL2PendingTxSchema: { + safeParse: (data: unknown) => ({ success: true, data }), + }, +})); + +const { pendingTxHandler } = await import( + "../../src/events/received/on-pending-txs.js" +); +const { droppedTxHandler } = await import( + "../../src/events/received/on-dropped-txs.js" +); + +// Each tx's lock wait can be long, so each starts after a heartbeat. +describe("the pending and dropped tx handlers", () => { + it.each([ + ["pending", pendingTxHandler], + ["dropped", droppedTxHandler], + ])( + "wait for a heartbeat before each %s tx's chain lock, and stop when one fails", + async (_kind, handler) => { + order.length = 0; + const beats: Array<{ pass: () => void; fail: (e: Error) => void }> = []; + const frame = { txs: [{ txHash: "0x01" }, { txHash: "0x02" }] }; + + const handled = handler.cb( + frame as never, + () => + new Promise((pass, fail) => { + order.push("beat"); + beats.push({ pass, fail }); + }), + ); + // Let anything not waiting for the heartbeat run. + await new Promise((settle) => setTimeout(settle, 20)); + expect(order).toEqual(["beat"]); + + beats[0].pass(); + await vi.waitFor(() => expect(order).toEqual(["beat", "lock", "beat"])); + + beats[1].fail(new Error("rebalancing")); + await expect(handled).rejects.toThrow("rebalancing"); + expect(order).toEqual(["beat", "lock", "beat"]); + }, + ); +}); diff --git a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts index 379ecdbce..d27423d49 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -4,7 +4,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const INTERVAL_MS = 120_000; const TIP = 104_595; -const PROVEN_TIP = 104_539; const dialect = new PgDialect(); const render = (condition: unknown) => dialect.sqlToQuery(condition as SQL); @@ -37,7 +36,8 @@ const mocks = vi.hoisted(() => { deleted: [] as unknown[], updates: [] as Array>, updateTargets: [] as unknown[][], - tips: {} as { degradedReason?: string; provenTip?: number }, + candidateHeights: [] as number[], + tipRepairWindow: 5, publishFails: false, order: [] as string[], }; @@ -82,6 +82,20 @@ const mocks = vi.hoisted(() => { select: (fields?: Record) => ({ from: (table: object) => ({ where: (condition: unknown) => { + // The tip repair's candidate query filters and orders in SQL, which + // the integration tests run; here it yields the heights given. + if (tableName(table) === "l2_tip_boundary_mismatch") { + return { + orderBy: () => ({ + limit: (limit: number) => + Promise.resolve( + state.candidateHeights + .slice(0, limit) + .map((height) => ({ height })), + ), + }), + }; + } if (tableName(table) !== "l2_open_gap") { return Object.assign(Promise.resolve(heightRows()), { orderBy: () => Promise.resolve(heightRows()), @@ -149,7 +163,9 @@ vi.mock("../../src/environment.js", () => ({ L2_BLOCK_RECONCILIATION_MAX_BLOCKS: 200, L2_BLOCK_RECONCILIATION_MAX_RANGES: 10, L2_BLOCK_RECONCILIATION_SCAN_WINDOW: 10_000, - L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW: 5, + get L2_BLOCK_RECONCILIATION_TIP_REPAIR_WINDOW() { + return mocks.state.tipRepairWindow; + }, })); vi.mock("../../src/logger.js", () => ({ logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, @@ -158,14 +174,6 @@ vi.mock( "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", () => ({ getCurrentRollupVersionNumber: () => Promise.resolve(1) }), ); -vi.mock("../../src/svcs/database/controllers/l2/tips.js", () => ({ - getTips: () => - Promise.resolve({ - proposed: { number: TIP }, - proven: { block: { number: mocks.state.tips.provenTip ?? PROVEN_TIP } }, - degradedReason: mocks.state.tips.degradedReason, - }), -})); vi.mock("../../src/svcs/database/controllers/l2block/get-latest.js", () => ({ getLatestHeight: () => Promise.resolve(BigInt(TIP)), getLatestBlockRollupVersion: () => Promise.resolve(1), @@ -239,7 +247,8 @@ beforeEach(() => { deleted: [], updates: [], updateTargets: [], - tips: {}, + candidateHeights: [], + tipRepairWindow: 5, publishFails: false, order: [], }); @@ -613,44 +622,51 @@ describe("selection", () => { }); describe("buildTipBoundaryRepairRequest", () => { - it("sends the window for a hash mismatch above the proven tip too", async () => { - mocks.state.tips = { - degradedReason: `proposed boundary block ${TIP - 2} hash mismatch: db=0x1 tip=0x2`, - }; - - const planned = await buildTipBoundaryRepairRequest(); - - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); - }); - - it("sends the window for a missing block", async () => { - mocks.state.tips = { - degradedReason: `proposed boundary block ${TIP - 2} is missing`, - }; + // The mismatch, then the heights below it, then those above it. + const windowAround = (height: number, radius: number) => [ + range(height, height), + range(height - radius, height - 1), + range(height + 1, height + radius), + ]; + // What a listener with a lower limit than the API's sends for a request: the + // ranges in order, each from its lowest height and at most `limit` wide, + // until `limit` heights in all. + const listenerSends = ( + request: + | { ranges: Array<{ from: number; to: number }>; maxBlocks?: number } + | undefined, + limit: number, + ) => + (request?.ranges ?? []) + .flatMap(({ from, to }) => { + const first = Math.max(1, from); + return heights(first, Math.min(to, first + limit - 1)); + }) + .slice(0, Math.min(request?.maxBlocks ?? limit, limit)); + + it("sends the window around the picked mismatch, keeping its row's backoff", async () => { + mocks.state.candidateHeights = [TIP - 2]; const planned = await buildTipBoundaryRepairRequest(); - expect(planned?.request.ranges).toEqual([range(TIP - 7, TIP + 3)]); + expect(planned?.request.ranges).toEqual(windowAround(TIP - 2, 5)); // Reopening a tip row keeps its backoff: it is fulfilled as soon as its // heights are present, mismatch or not. expect(mocks.state.upserts[0].set).not.toHaveProperty("requestCount"); }); - it("backs off while its row is not due", async () => { - mocks.state.tips = { - degradedReason: "finalized boundary block 98106 is missing", - }; - mocks.state.gaps = [ - gap({ - id: "MAINNET:tip_boundary_mismatch:98101:98111", - fromHeight: 98101, - toHeight: 98111, - reason: "tip_boundary_mismatch", - due: false, - }), - ]; + it("asks for the mismatch before its neighbors, so a listener sending fewer heights than the window still sends it", async () => { + mocks.state.tipRepairWindow = 300; + mocks.state.candidateHeights = [TIP - 2]; + + const planned = await buildTipBoundaryRepairRequest(); - await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); + expect(listenerSends(planned?.request, 50)).toContain(TIP - 2); + // The window still fits the API's own block budget. + expect(planned?.request).toMatchObject({ + ranges: windowAround(TIP - 2, 99), + maxBlocks: 199, + }); }); }); diff --git a/services/explorer-api/tests/unit/start-up.test.ts b/services/explorer-api/tests/unit/start-up.test.ts new file mode 100644 index 000000000..f8aa828de --- /dev/null +++ b/services/explorer-api/tests/unit/start-up.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from "vitest"; +import { start } from "../../src/start.js"; + +const steps = vi.hoisted(() => { + const order: string[] = []; + const step = (name: string) => () => { + order.push(name); + return Promise.resolve(); + }; + return { order, step }; +}); + +vi.mock("../../src/environment.js", () => ({ + ARCHIVE_MODE: false, + L1_GOVERNANCE_URI_RECONCILIATION_ENABLED: false, + L2_BLOCK_RECONCILIATION_ENABLED: false, + L2_NETWORK_ID: "SANDBOX", +})); +vi.mock("../../src/constants.js", () => ({ AZTEC_SCAN_NOTES: {} })); +vi.mock("../../src/logger.js", () => ({ logger: { info: vi.fn() } })); +vi.mock("../../src/svcs/database/controllers/l2Tx/delete-all-txs.js", () => ({ + deleteAllTxs: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/dropped-tx/remove.js", () => ({ + removeMinedDroppedTxs: steps.step("sweep"), +})); +vi.mock( + "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", + () => ({ initializeRollupVersionCache: vi.fn() }), +); +vi.mock("../../src/utils/protocol-contracts.js", () => ({ + initializeProtocolContracts: vi.fn(), +})); +vi.mock("../../src/svcs/database/controllers/l2/aztec-scan-notes.js", () => ({ + updateContractInstanceAztecScanNotes: vi.fn(), +})); +vi.mock("../../src/svcs/cache/chain-revision.js", () => ({ + bumpChainRevision: steps.step("bump"), +})); +vi.mock("../../src/events/received/index.js", () => ({ + subscribeHandlers: steps.step("subscribe"), +})); +vi.mock("../../src/svcs/reconciliation/l2-block-reconciliation.js", () => ({ + runL2BlockReconciliationOnce: vi.fn(), + startL2BlockReconciliation: vi.fn(), +})); +vi.mock( + "../../src/svcs/reconciliation/governance-uri-reconciliation.js", + () => ({ + runGovernanceUriReconciliationOnce: vi.fn(), + startGovernanceUriReconciliation: vi.fn(), + }), +); + +describe("explorer-api start-up", () => { + // A crash between a block's commit and its bump leaves cached chain reads + // from before that commit; the sweep's deletions change them too. + it("bumps the chain revision after the dropped-tx sweep, before it consumes", async () => { + await start(); + + expect(steps.order).toEqual(["sweep", "bump", "subscribe"]); + }); +}); diff --git a/services/explorer-ui-v2/src/api/by-hash-lookups.test.ts b/services/explorer-ui-v2/src/api/by-hash-lookups.test.ts new file mode 100644 index 000000000..39f6da185 --- /dev/null +++ b/services/explorer-ui-v2/src/api/by-hash-lookups.test.ts @@ -0,0 +1,80 @@ +import { QueryClient } from "@tanstack/react-query"; +import { AxiosError, type AxiosAdapter, type AxiosResponse } from "axios"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import client from "./client"; +import { DroppedTxAPI } from "./dropped-tx"; +import { TxAPI } from "./tx"; + +vi.mock("~/service/constants", () => ({ + API_URL: "https://api.test/key", + aztecExplorer: { + getL2DroppedTxByHash: (hash: string) => `/l2/dropped-txs/${hash}`, + getL2PendingTxsByHash: (hash: string) => `/l2/txs/${hash}`, + }, +})); + +const TX = `0x${"cd".repeat(32)}`; + +// A custom adapter must reject on its own: axios applies validateStatus only in its built-in adapters. +const answer = + (status: number, data: unknown): AxiosAdapter => + (config) => { + const response: AxiosResponse = { + data, + status, + statusText: "", + headers: {}, + config, + }; + return status < 400 + ? Promise.resolve(response) + : Promise.reject( + new AxiosError( + `Request failed with status code ${status}`, + AxiosError.ERR_BAD_REQUEST, + config, + {}, + response, + ), + ); + }; + +const { adapter } = client.defaults; +afterEach(() => { + client.defaults.adapter = adapter; +}); + +describe.each([ + { + name: "DroppedTxAPI.getDroppedTxByHash", + lookup: DroppedTxAPI.getDroppedTxByHash, + row: { txHash: TX, createdAsPendingAt: 1, droppedAt: 2 }, + }, + { + name: "TxAPI.getPendingTxsByHash", + lookup: TxAPI.getPendingTxsByHash, + row: { txHash: TX, feePayer: `0x${"0e".repeat(32)}`, birthTimestamp: 1 }, + }, +])("$name", ({ name, lookup, row }) => { + it("answers null once the tx has no row, so a refetch clears the row it found before", async () => { + const queryClient = new QueryClient(); + const query = { + queryKey: [name, TX], + queryFn: (): Promise => lookup(TX), + retry: false, + }; + client.defaults.adapter = answer(200, row); + await queryClient.fetchQuery(query); + + client.defaults.adapter = answer(404, "not found"); + await queryClient.refetchQueries({ queryKey: query.queryKey }); + + expect(queryClient.getQueryData(query.queryKey)).toBeNull(); + }); + + it("still fails on any other error", async () => { + client.defaults.adapter = answer(500, "boom"); + + await expect(lookup(TX)).rejects.toMatchObject({ status: 500 }); + }); +}); diff --git a/services/explorer-ui-v2/src/api/dropped-tx.ts b/services/explorer-ui-v2/src/api/dropped-tx.ts index 202d87ab2..653145008 100644 --- a/services/explorer-ui-v2/src/api/dropped-tx.ts +++ b/services/explorer-ui-v2/src/api/dropped-tx.ts @@ -3,13 +3,23 @@ import { chicmozL2DroppedTxSchema, } from "@chicmoz-pkg/types"; import { aztecExplorer } from "~/service/constants"; -import client, { validateResponse } from "./client"; +import client, { isNotFoundError, validateResponse } from "./client"; export const DroppedTxAPI = { - getDroppedTxByHash: async (hash: string): Promise => { - const response = await client.get( - aztecExplorer.getL2DroppedTxByHash(hash), - ); - return validateResponse(chicmozL2DroppedTxSchema, response.data); + /** `null` for a tx with no dropped row: a failed refetch would keep the drop it last found. */ + getDroppedTxByHash: async ( + hash: string, + ): Promise => { + try { + const response = await client.get( + aztecExplorer.getL2DroppedTxByHash(hash), + ); + return validateResponse(chicmozL2DroppedTxSchema, response.data); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } }, }; diff --git a/services/explorer-ui-v2/src/api/tx.ts b/services/explorer-ui-v2/src/api/tx.ts index ab1441ee3..81bfbc228 100644 --- a/services/explorer-ui-v2/src/api/tx.ts +++ b/services/explorer-ui-v2/src/api/tx.ts @@ -8,18 +8,28 @@ import { } from "@chicmoz-pkg/types"; import { z } from "zod"; import { aztecExplorer } from "~/service/constants"; -import client, { validateResponse } from "./client"; +import client, { isNotFoundError, validateResponse } from "./client"; export const TxAPI = { getPendingTxs: async (): Promise => { const response = await client.get(aztecExplorer.getL2PendingTxs); return validateResponse(z.array(chicmozL2PendingTxSchema), response.data); }, - getPendingTxsByHash: async (hash: string): Promise => { - const response = await client.get( - aztecExplorer.getL2PendingTxsByHash(hash), - ); - return validateResponse(chicmozL2PendingTxSchema, response.data); + /** `null` for a tx with no pending row: a failed refetch would keep the row it last found. */ + getPendingTxsByHash: async ( + hash: string, + ): Promise => { + try { + const response = await client.get( + aztecExplorer.getL2PendingTxsByHash(hash), + ); + return validateResponse(chicmozL2PendingTxSchema, response.data); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } }, getPublicCallRequestsByTxHash: async ( diff --git a/services/explorer-ui-v2/src/hooks/api/block.ts b/services/explorer-ui-v2/src/hooks/api/block.ts index 72f468483..eb881fc43 100644 --- a/services/explorer-ui-v2/src/hooks/api/block.ts +++ b/services/explorer-ui-v2/src/hooks/api/block.ts @@ -36,8 +36,9 @@ export const useGetBlockByIdentifier = ( ? BlockAPI.getBlockByHash(heightOrHash) : BlockAPI.getBlockByHeight(heightOrHash), enabled: !!heightOrHash, - // Historical blocks don't mutate; cache them for a while so walking - // next/prev on the detail page is instant. + // Cached so walking next/prev is instant; frames refresh it, but none + // announces a catch-up block, which can orphan it or fill its txs. + refetchInterval: SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; diff --git a/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts b/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts index 987380aa1..04ba85e39 100644 --- a/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts +++ b/services/explorer-ui-v2/src/hooks/api/dropped-tx.ts @@ -5,8 +5,8 @@ import { queryKeyGenerator } from "./utils"; export const useDroppedTxByHash = ( hash: string, -): UseQueryResult => { - return useQuery({ +): UseQueryResult => { + return useQuery({ queryKey: queryKeyGenerator.droppedTxByHash(hash), queryFn: () => DroppedTxAPI.getDroppedTxByHash(hash), enabled: !!hash, diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx new file mode 100644 index 000000000..7d1651ad7 --- /dev/null +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.test.tsx @@ -0,0 +1,64 @@ +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; +import { REFETCH_INTERVAL, SLOW_REFETCH_INTERVAL } from "./utils"; + +type RefetchInterval = (query: { + state: { data?: { isOrphaned: boolean } }; +}) => number | false; + +const passed = vi.hoisted(() => ({ options: [] as unknown[] })); + +vi.mock("@tanstack/react-query", () => ({ + useQuery: (options: unknown) => { + passed.options.push(options); + return {}; + }, +})); +vi.mock("~/api", () => ({ BlockAPI: {}, TxEffectsAPI: {} })); + +const { useGetBlockByIdentifier } = await import("./block"); +const { useGetTableTxEffectsByBlockHeight, useGetTxEffectByHash } = + await import("./tx-effect"); + +// The refetchInterval of each query `Page` renders, in call order. +const intervalsOf = (Page: () => null) => { + passed.options = []; + renderToStaticMarkup(); + return passed.options.map( + (options) => (options as { refetchInterval: unknown }).refetchInterval, + ); +}; + +// react-query asks for the interval again after each fetch, with its data. +const intervalAfterFetching = (data?: { isOrphaned: boolean }) => { + const TxPage = () => { + useGetTxEffectByHash(`0x${"cd".repeat(32)}`); + return null; + }; + const [refetchInterval] = intervalsOf(TxPage) as [RefetchInterval]; + return refetchInterval({ state: { data } }); +}; + +describe("useGetTxEffectByHash", () => { + it("refetches an orphaned effect every 10 s, and a canonical or missing one every minute", () => { + expect(intervalAfterFetching({ isOrphaned: true })).toBe(REFETCH_INTERVAL); + expect(intervalAfterFetching({ isOrphaned: false })).toBe( + SLOW_REFETCH_INTERVAL, + ); + expect(intervalAfterFetching()).toBe(SLOW_REFETCH_INTERVAL); + }); +}); + +describe("the block page's queries", () => { + it("refetch every minute", () => { + const BlockPage = () => { + useGetBlockByIdentifier("7"); + useGetTableTxEffectsByBlockHeight(7n); + return null; + }; + expect(intervalsOf(BlockPage)).toEqual([ + SLOW_REFETCH_INTERVAL, + SLOW_REFETCH_INTERVAL, + ]); + }); +}); diff --git a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts index 4a3f68f1a..0d4982022 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx-effect.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx-effect.ts @@ -7,6 +7,7 @@ import { TxEffectsAPI } from "~/api"; import { LIVE_REFETCH_INTERVAL, REFETCH_INTERVAL, + SLOW_REFETCH_INTERVAL, queryKeyGenerator, } from "./utils"; @@ -18,9 +19,16 @@ export const useGetTxEffectByHash = ( queryKey: queryKeyGenerator.txEffectByHash(hash), queryFn: () => TxEffectsAPI.getTxEffectByHash(hash), enabled: !!hash, + // Detail queries poll, since catch-up blocks index and move effects and + // fill blocks' txs with no websocket frame. refetchInterval: ({ state }) => - refetchUntilFound && !state.data ? LIVE_REFETCH_INTERVAL : false, - // Mined tx effects are immutable โ€” cache for 5min. + !state.data + ? refetchUntilFound + ? LIVE_REFETCH_INTERVAL + : SLOW_REFETCH_INTERVAL + : state.data.isOrphaned + ? REFETCH_INTERVAL + : SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; @@ -49,6 +57,7 @@ export const useGetTableTxEffectsByBlockHeight = ( ? Promise.resolve([]) : TxEffectsAPI.getTableTxEffectsByBlockHeight(BigInt(height)), enabled: height !== undefined, + refetchInterval: SLOW_REFETCH_INTERVAL, staleTime: 5 * 60_000, }); }; diff --git a/services/explorer-ui-v2/src/hooks/api/tx.ts b/services/explorer-ui-v2/src/hooks/api/tx.ts index 8853db903..51b754a44 100644 --- a/services/explorer-ui-v2/src/hooks/api/tx.ts +++ b/services/explorer-ui-v2/src/hooks/api/tx.ts @@ -24,8 +24,8 @@ export const usePendingTxs = (): UseQueryResult< export const usePendingTxsByHash = ( hash: string, -): UseQueryResult => { - return useQuery({ +): UseQueryResult => { + return useQuery({ queryKey: queryKeyGenerator.pendingTxsByHash(hash), queryFn: () => TxAPI.getPendingTxsByHash(hash), enabled: !!hash, diff --git a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts index 981d63168..f0f3083ae 100644 --- a/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts +++ b/services/explorer-ui-v2/src/hooks/websocket/message-callbacks.ts @@ -1,6 +1,29 @@ import type { QueryClient } from "@tanstack/react-query"; import { queryKeyGenerator } from "~/hooks/api"; +const prefixOf = (queryKey: readonly unknown[]) => queryKey.slice(0, 1); + +// Refreshed on a block or tips frame. Either can follow a prune, which changes +// the reorg lists and any block, tx or contract instance already shown: the +// detail and page queries go by prefix, whatever they name. +const CHAIN_QUERIES = [ + queryKeyGenerator.latestBlock, + queryKeyGenerator.latestTableBlocks, + queryKeyGenerator.blocksByNativeStatus, + queryKeyGenerator.l2TipsHealth, + queryKeyGenerator.reorgs, + queryKeyGenerator.orphanedBlocks, + prefixOf(queryKeyGenerator.paginatedTableBlocks(0, 0, undefined)), + prefixOf(queryKeyGenerator.blockByHeight("")), + prefixOf(queryKeyGenerator.txEffectsByBlockHeight(undefined)), + prefixOf(queryKeyGenerator.txEffectByHash("")), + prefixOf(queryKeyGenerator.pendingTxsByHash("")), + prefixOf(queryKeyGenerator.droppedTxByHash("")), + prefixOf(queryKeyGenerator.contractInstance("")), + prefixOf(queryKeyGenerator.deployedContractInstances("")), + queryKeyGenerator.latestContractInstances, +]; + /** * The websocket publisher sends compact payloads such as `{ block }` and * `{ txs }`. Older/alternate publishers may send a `{ topic }` envelope, so we @@ -37,18 +60,9 @@ export const handleWebSocketMessage = async ( const hasStatsUpdate = topic?.includes("stats") ?? false; if (hasBlockUpdate || hasTipsUpdate) { - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.latestBlock, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.latestTableBlocks, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.blocksByNativeStatus, - }); - await queryClient.invalidateQueries({ - queryKey: queryKeyGenerator.l2TipsHealth, - }); + for (const queryKey of CHAIN_QUERIES) { + await queryClient.invalidateQueries({ queryKey }); + } } if (hasTxUpdate) { diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx new file mode 100644 index 000000000..803c47d9e --- /dev/null +++ b/services/explorer-ui-v2/src/pages/block-detail/index.test.tsx @@ -0,0 +1,147 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const BLOCK = `0x${"ab".repeat(32)}`; +const tx = (byte: string) => `0x${byte.repeat(32)}`; +const [TX_A, TX_B, TX_C] = [tx("0a"), tx("0b"), tx("0c")]; +const ONE = (10n ** 18n).toString(); +const TWO = (2n * 10n ** 18n).toString(); +const shown = vi.hoisted(() => ({ + block: undefined as unknown, + heightRead: undefined as unknown, +})); + +vi.mock("@tanstack/react-router", async () => { + const { createElement } = await import("react"); + return { + Link: ({ + to, + params, + children, + }: { + to: string; + params?: Record; + children: ReactNode; + }) => + createElement( + "a", + { + href: to.replace( + /\$(\w+)/g, + (_, name: string) => params?.[name] ?? "", + ), + }, + children, + ), + useParams: () => ({ blockNumber: BLOCK }), + }; +}); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/hooks/api", () => ({ + useGetBlockByIdentifier: () => ({ data: shown.block }), + useGetTableTxEffectsByBlockHeight: () => ({ data: shown.heightRead }), + useChainInfo: () => ({ data: undefined }), +})); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { BlockDetailPage } = await import("./index"); +const { formatFees } = await import("~/lib/utils"); + +// The tx rows, as [tx hash, index, fee], and whether the page notes where a +// tx mined again is listed. +const render = ({ + body, + orphaned, + heightRead, +}: { + body: string[]; + orphaned: boolean; + heightRead: Array<[txHash: string, fee: string]>; +}) => { + shown.block = { + hash: BLOCK, + height: 7n, + nativeStatus: "proposed", + orphan: orphaned + ? { timestamp: 1_700_000_000_000, hasOrphanedParent: false } + : undefined, + archive: { root: BLOCK }, + header: { + lastArchive: { root: BLOCK }, + totalFees: "0", + totalManaUsed: 0n, + globalVariables: { + timestamp: 1_700_000_000n, + version: 1, + slotNumber: 1, + coinbase: BLOCK, + feeRecipient: BLOCK, + gasFees: { feePerDaGas: 0, feePerL2Gas: 0 }, + }, + }, + body: { txEffects: body.map((txHash) => ({ txHash })) }, + }; + shown.heightRead = heightRead.map(([txHash, transactionFee]) => ({ + blockNumber: 7n, + txHash, + transactionFee, + timestamp: 1_700_000_000_000, + })); + const html = renderToStaticMarkup(); + return { + rows: [ + ...html.matchAll( + /href="\/tx-effects\/([^"]+)">.*?(.*?)<\/span>(.*?) [txHash, index, fee]), + note: html.includes("a later block also mined"), + }; +}; + +describe("BlockDetailPage", () => { + it("lists an orphaned block's own txs with no index or fee, and notes where a tx mined again is listed", () => { + expect( + render({ + body: [TX_A, TX_B], + orphaned: true, + heightRead: [ + [TX_B, ONE], + [TX_C, TWO], + ], + }), + ).toEqual({ + rows: [ + [TX_A, "โ€”", "โ€”"], + [TX_B, "โ€”", "โ€”"], + ], + note: true, + }); + }); + + it("lists a block's txs in its order, each with its index and its own fee", () => { + expect( + render({ + body: [TX_B, TX_C], + orphaned: false, + heightRead: [ + [TX_C, TWO], + [TX_B, ONE], + ], + }), + ).toEqual({ + rows: [ + [TX_B, "0", formatFees(ONE)], + [TX_C, "1", formatFees(TWO)], + ], + note: false, + }); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/block-detail/index.tsx b/services/explorer-ui-v2/src/pages/block-detail/index.tsx index 313eb8216..7da789b1b 100644 --- a/services/explorer-ui-v2/src/pages/block-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/block-detail/index.tsx @@ -91,6 +91,12 @@ export const BlockDetailPage: FC = () => { const totalFees = formatFees(block.header.totalFees, feeJuiceDecimals); const totalManaUsed = block.header.totalManaUsed?.toString?.() ?? "0"; const txCount = block.body.txEffects.length; + // The body says which txs this block holds; the height read, the canonical + // block's, only adds their fees. A tx's effect moves to the block that + // mines it again, so an orphaned body keeps only the rest: its positions + // are not their indexes, and a fee by hash can be the later block's. + const orphaned = !!block.orphan; + const feeByTxHash = new Map(txs?.map((t) => [t.txHash, t.transactionFee])); const l1Anchor = block.proposedOnL1 ?? block.proofVerifiedOnL1; const blockRollupVersion = BigInt(block.header.globalVariables.version); const isOldRollup = @@ -388,30 +394,38 @@ export const BlockDetailPage: FC = () => {
Idx
Fee ({feeJuiceSymbol})
- {(txs ?? []).map((t, i) => ( - - - {i} - - {formatFees(t.transactionFee, feeJuiceDecimals)} - - - - ))} - {(!txs || txs.length === 0) && ( -
- {txs ? "no tx-effects in this block" : "loading tx-effectsโ€ฆ"} + {orphaned && ( +
+ a tx that a later block also mined is listed under that block
)} + {block.body.txEffects.map(({ txHash }, i) => { + const fee = orphaned ? undefined : feeByTxHash.get(txHash); + return ( + + + {orphaned ? "โ€”" : i} + + {fee === undefined + ? "โ€”" + : formatFees(fee, feeJuiceDecimals)} + + + + ); + })} + {txCount === 0 && ( +
no tx-effects in this block
+ )}
)} {tab === "roots" && ( diff --git a/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx b/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx new file mode 100644 index 000000000..ee86798a4 --- /dev/null +++ b/services/explorer-ui-v2/src/pages/contract-instance/index.test.tsx @@ -0,0 +1,72 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const ADDRESS = `0x${"ef".repeat(32)}`; +const found = vi.hoisted(() => ({ instance: undefined as unknown })); + +vi.mock("@tanstack/react-router", () => ({ + Link: ({ children }: { children: ReactNode }) => children, + useParams: () => ({ address: ADDRESS }), +})); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/components/ui/tooltip", () => ({ + Tooltip: ({ children }: { children: ReactNode }) => children, + TooltipContent: () => null, + TooltipTrigger: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("~/hooks/api", () => { + const none = () => ({ data: undefined }); + return { + useContractInstance: () => ({ + data: found.instance, + isLoading: false, + isError: false, + error: null, + isFetching: false, + refetch: () => Promise.resolve(), + }), + useContractInstanceBalance: none, + useContractInstanceBalanceHistory: none, + useContractInstanceFpcRelationships: none, + useContractInstanceFpcTransactions: none, + useChainInfo: none, + useL2ToL1MsgsByContract: none, + usePublicCallRequestsByContract: none, + useL1FeeJuicePortalDepositsByAddress: none, + }; +}); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { ContractInstancePage } = await import("./index"); + +const statusOf = (isOrphaned: boolean) => { + found.instance = { + address: ADDRESS, + blockHash: `0x${"ab".repeat(32)}`, + contractClassId: `0x${"12".repeat(32)}`, + version: 1, + deployer: `0x${"34".repeat(32)}`, + salt: `0x${"56".repeat(32)}`, + initializationHash: `0x${"78".repeat(32)}`, + immutablesHash: `0x${"9a".repeat(32)}`, + isOrphaned, + }; + const html = renderToStaticMarkup(); + return /Status<\/span>([^<]*)<\/span>/.exec( + html, + )?.[1]; +}; + +describe("ContractInstancePage", () => { + it("shows whether the instance's deployment is orphaned, as the instance lists do", () => { + expect([statusOf(true), statusOf(false)]).toEqual(["orphaned", "active"]); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/contract-instance/index.tsx b/services/explorer-ui-v2/src/pages/contract-instance/index.tsx index af162aa57..826b74e76 100644 --- a/services/explorer-ui-v2/src/pages/contract-instance/index.tsx +++ b/services/explorer-ui-v2/src/pages/contract-instance/index.tsx @@ -325,6 +325,9 @@ export const ContractInstancePage: FC = () => { + + {instance.isOrphaned ? "orphaned" : "active"} + {instance.artifactHash} diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx new file mode 100644 index 000000000..3a499bae4 --- /dev/null +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.test.tsx @@ -0,0 +1,162 @@ +import { type ReactNode } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it, vi } from "vitest"; + +const TX = `0x${"cd".repeat(32)}`; +const BLOCK = `0x${"ab".repeat(32)}`; +const found = vi.hoisted(() => ({ + effect: undefined as unknown, + pending: null as unknown, + dropped: null as unknown, +})); + +vi.mock("@tanstack/react-router", async () => { + const { createElement } = await import("react"); + return { + Link: ({ + to, + params, + children, + }: { + to: string; + params?: Record; + children: ReactNode; + }) => + createElement( + "a", + { + href: to.replace( + /\$(\w+)/g, + (_, name: string) => params?.[name] ?? "", + ), + }, + children, + ), + useParams: () => ({ hash: TX }), + }; +}); +vi.mock("~/components/layout", () => ({ + Shell: ({ children }: { children: ReactNode }) => children, + ConsoleHead: () => null, +})); +vi.mock("~/hooks/api", () => ({ + usePendingTxsByHash: () => ({ data: found.pending }), + useGetTxEffectByHash: () => ({ data: found.effect }), + useDroppedTxByHash: () => ({ data: found.dropped }), + usePublicCallRequestsByTxHash: () => ({ data: [] }), + useChainInfo: () => ({ data: undefined }), +})); + +// The components read these from the env at import. +vi.stubEnv("VITE_L2_NETWORK_ID", "SANDBOX"); +vi.stubEnv("VITE_API_URL", "https://api.test"); +vi.stubEnv("VITE_API_KEY", "dev-api-key"); + +const { TxDetailPage } = await import("./index"); + +// Each panel by the API path its head names. +const PANELS = { pending: "/api/l2/txs/", dropped: "/api/l2/dropped-txs/" }; + +// What the lookups hold for the tx: its effect (in a block on the chain, or +// only in an orphaned one), and whether it has a pending and a dropped row. +const render = ({ + effect, + pending = false, + dropped = false, +}: { + effect?: "mined" | "orphaned"; + pending?: boolean; + dropped?: boolean; +}) => { + found.effect = effect && { + txHash: TX, + blockHash: BLOCK, + blockHeight: 7n, + timestamp: 1_700_000_000_000, + isOrphaned: effect === "orphaned", + transactionFee: "1000", + revertCode: { code: 0 }, + noteHashes: [], + nullifiers: [], + publicDataWrites: [], + l2ToL1Msgs: [], + privateLogs: [], + publicLogs: [], + contractClassLogs: [], + }; + found.pending = pending + ? { txHash: TX, feePayer: BLOCK, birthTimestamp: 1_700_000_000_000 } + : null; + found.dropped = dropped + ? { + txHash: TX, + createdAsPendingAt: 1_700_000_000_000, + droppedAt: 1_700_000_100_000, + dropReason: "expired", + } + : null; + const html = renderToStaticMarkup(); + return { + status: /class="status-pill (\w+)"/.exec(html)?.[1], + blockLinks: [...html.matchAll(/href="\/blocks\/([^"]+)"/g)].map( + ([, block]) => block, + ), + droppedAt: html.includes("dropped at "), + panels: Object.entries(PANELS) + .filter(([, path]) => html.includes(path)) + .map(([panel]) => panel), + notFound: html.includes("tx not found"), + }; +}; + +describe("TxDetailPage", () => { + it("shows a tx whose effect only an orphaned block keeps as not mined, and links that block by hash", () => { + expect(render({ effect: "orphaned" })).toEqual({ + status: "orphaned", + blockLinks: [BLOCK, BLOCK, BLOCK], + droppedAt: false, + panels: [], + notFound: false, + }); + }); + + it("shows a mined tx as mined, links its block by hash, and shows no drop it once had", () => { + expect(render({ effect: "mined", dropped: true })).toEqual({ + status: "mined", + blockLinks: [BLOCK, BLOCK, BLOCK], + droppedAt: false, + panels: [], + notFound: false, + }); + }); + + it("shows a dropped tx's drop, not the pending row it still has", () => { + expect(render({ pending: true, dropped: true })).toEqual({ + status: "dropped", + blockLinks: [], + droppedAt: true, + panels: ["dropped"], + notFound: false, + }); + }); + + it("shows no status for a tx no lookup found", () => { + expect(render({})).toEqual({ + status: undefined, + blockLinks: [], + droppedAt: false, + panels: [], + notFound: true, + }); + }); + + it("shows a pending tx's pending row", () => { + expect(render({ pending: true })).toEqual({ + status: "pending", + blockLinks: [], + droppedAt: false, + panels: ["pending"], + notFound: false, + }); + }); +}); diff --git a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx index e219ba3f0..b96b98538 100644 --- a/services/explorer-ui-v2/src/pages/tx-detail/index.tsx +++ b/services/explorer-ui-v2/src/pages/tx-detail/index.tsx @@ -1,3 +1,4 @@ +import { type ChicmozL2TxEffectDeluxe } from "@chicmoz-pkg/types"; import { Link, useParams } from "@tanstack/react-router"; import { type FC, useState } from "react"; import { @@ -31,6 +32,16 @@ import { type Tab = "notes" | "nulls" | "public" | "l1" | "logs" | "calls"; +// By hash: a height names whichever block is canonical there when the link +// is followed, which can be another block by then. +const EffectBlockLink: FC<{ effect: ChicmozL2TxEffectDeluxe }> = ({ + effect, +}) => ( + + #{fmtNum(Number(effect.blockHeight))} + +); + export const TxDetailPage: FC = () => { const { hash = "" } = useParams({ strict: false }); const [tab, setTab] = useState("notes"); @@ -46,14 +57,19 @@ export const TxDetailPage: FC = () => { const feeJuiceSymbol = getFeeJuiceSymbol(chainInfo?.feeJuiceSymbol); const feeJuiceAddress = chainInfo?.l1ContractAddresses?.feeJuiceAddress; - const mined = !!effect; + // Only a block on the chain mines a tx: an orphaned block's effect is history. + const historical = effect?.isOrphaned === true; + const mined = !!effect && !historical; + // No status while no lookup has found the tx. const status = mined ? "mined" : dropped ? "dropped" : pending ? "pending" - : "pending"; + : historical + ? "orphaned" + : undefined; const ts = effect?.timestamp ? effect.timestamp @@ -88,19 +104,13 @@ export const TxDetailPage: FC = () => {
Tx effect ยท {ts ? ageStr(ts) : "โ€”"}

{hash}

- - {mined && effect?.blockHeight !== undefined && ( + {status && } + {effect?.blockHeight !== undefined && ( - in{" "} - - #{fmtNum(Number(effect.blockHeight))} - + {historical ? "was in" : "in"} )} - {dropped && ( + {status === "dropped" && dropped && ( dropped at {toIsoUtc(dropped.droppedAt)} @@ -108,7 +118,7 @@ export const TxDetailPage: FC = () => {
- {mined && effect && ( + {effect && ( <>
@@ -132,12 +142,7 @@ export const TxDetailPage: FC = () => {
Block
- - #{fmtNum(Number(effect.blockHeight))} - +
@@ -153,7 +158,10 @@ export const TxDetailPage: FC = () => {

- Transactionmined transaction + Transaction + + {historical ? "in an orphaned block" : "mined transaction"} +

@@ -161,15 +169,14 @@ export const TxDetailPage: FC = () => { {effect.txHash} - mined + {historical ? ( + orphaned + ) : ( + mined + )} - - #{fmtNum(Number(effect.blockHeight))} - + {effect.blockHash} @@ -305,7 +312,7 @@ export const TxDetailPage: FC = () => { )} - {!mined && pending && ( + {status === "pending" && pending && ( <>
@@ -369,7 +376,7 @@ export const TxDetailPage: FC = () => { )} - {!mined && !pending && dropped && ( + {status === "dropped" && dropped && (

@@ -398,7 +405,7 @@ export const TxDetailPage: FC = () => {

)} - {!mined && !pending && !dropped && ( + {!effect && !pending && !dropped && (
tx not found
diff --git a/services/explorer-ui-v2/src/styles/pages.css b/services/explorer-ui-v2/src/styles/pages.css index b037f7a6a..00c17e23c 100644 --- a/services/explorer-ui-v2/src/styles/pages.css +++ b/services/explorer-ui-v2/src/styles/pages.css @@ -809,6 +809,13 @@ color: var(--ink-3); text-align: right; } +.block-tx-note { + padding: 10px 18px; + border-bottom: 1px solid var(--line-soft); + font-family: var(--mono); + font-size: 11px; + color: var(--ink-3); +} /* ==================================================================== * CONTRACTS diff --git a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts index f5168c38c..e2f105a49 100644 --- a/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts +++ b/services/explorer-ui-v2/tests/characterization/ws-frame.test.ts @@ -19,27 +19,60 @@ const PUBLISHED_BLOCK_FRAME = new URL( import.meta.url, ); +const TX = `0x${"cd".repeat(32)}`; +const ADDRESS = `0x${"ef".repeat(32)}`; +// Views a prune can change: the reorg lists, the block pages, block and tx +// details by height and by hash, and the contract instances and their lists. +const CHAIN_VIEWS = [ + queryKeyGenerator.reorgs, + queryKeyGenerator.orphanedBlocks, + queryKeyGenerator.paginatedTableBlocks(2, 20, undefined), + queryKeyGenerator.blockByHeight("7"), + queryKeyGenerator.blockByHeight(`0x${"ab".repeat(32)}`), + queryKeyGenerator.txEffectsByBlockHeight(7), + queryKeyGenerator.txEffectByHash(TX), + queryKeyGenerator.pendingTxsByHash(TX), + queryKeyGenerator.droppedTxByHash(TX), + queryKeyGenerator.contractInstance(ADDRESS), + queryKeyGenerator.deployedContractInstances(`0x${"12".repeat(32)}`), + queryKeyGenerator.paginatedContractInstances(20, 20, "all"), +]; +// A block frame says nothing about it. +const UNRELATED = queryKeyGenerator.averageFees; + +const staleAfter = async (frame: string, views: unknown[][]) => { + const queryClient = new QueryClient(); + for (const key of [...views, UNRELATED]) { + queryClient.setQueryData(key, []); + } + await handleWebSocketMessage(queryClient, frame); + return { + views: views.map((key) => queryClient.getQueryState(key)?.isInvalidated), + unrelated: queryClient.getQueryState(UNRELATED)?.isInvalidated, + }; +}; + // The handler drops a frame it cannot parse or whose keys it does not know, // without a word, so a change to the publisher's frame would silently stop // live updates. A hand-written frame here would not follow the publisher. describe("websocket frames from the publisher", () => { - it("a published block frame marks the latest-block and block-table queries stale", async () => { - const queryClient = new QueryClient(); + it("a published block frame marks the latest-block, block-table and chain detail queries stale", async () => { const views = [ queryKeyGenerator.latestBlock, queryKeyGenerator.latestTableBlocks, + ...CHAIN_VIEWS, ]; - for (const key of views) { - queryClient.setQueryData(key, []); - } - await handleWebSocketMessage( - queryClient, - readFileSync(PUBLISHED_BLOCK_FRAME, "utf8"), - ); + expect( + await staleAfter(readFileSync(PUBLISHED_BLOCK_FRAME, "utf8"), views), + ).toEqual({ views: views.map(() => true), unrelated: false }); + }); + // No publisher test records a tips frame. The publisher sends `{ l2Tips }` + // (`sendL2TipsToClients`), and the handler reads only that key. + it("a tips frame marks the reorg lists and the chain detail queries stale", async () => { expect( - views.map((key) => queryClient.getQueryState(key)?.isInvalidated), - ).toEqual([true, true]); + await staleAfter(JSON.stringify({ l2Tips: {} }), CHAIN_VIEWS), + ).toEqual({ views: CHAIN_VIEWS.map(() => true), unrelated: false }); }); });