diff --git a/packages/types/src/aztec/reorg.ts b/packages/types/src/aztec/reorg.ts index 57cda62b9..7fab567e1 100644 --- a/packages/types/src/aztec/reorg.ts +++ b/packages/types/src/aztec/reorg.ts @@ -1,11 +1,21 @@ import { z } from "zod"; import { hexStringSchema } from "../general.js"; -export const chicmozReorgSchema = z.object({ - orphanedBlockHash: hexStringSchema, - height: z.coerce.bigint().nonnegative(), - timestamp: z.coerce.date(), - nbrOfOrphanedBlocks: z.number().int().nonnegative(), -}); +export const chicmozReorgSchema = z + .object({ + orphanedBlockHash: hexStringSchema.describe( + "The lowest of the record's blocks that are still orphaned.", + ), + height: z.coerce.bigint().nonnegative(), + timestamp: z.coerce.date(), + nbrOfOrphanedBlocks: z + .number() + .int() + .nonnegative() + .describe("How many of the record's blocks are still orphaned."), + }) + .describe( + "One chain change that orphaned canonical blocks. Its count and lowest block cover only the blocks still orphaned, and the record disappears once all its blocks are back on the chain.", + ); export type ChicmozReorg = z.infer; diff --git a/services/explorer-api/migrations/0038_block_link_indexes.sql b/services/explorer-api/migrations/0038_block_link_indexes.sql new file mode 100644 index 000000000..fb647c883 --- /dev/null +++ b/services/explorer-api/migrations/0038_block_link_indexes.sql @@ -0,0 +1,4 @@ +CREATE INDEX IF NOT EXISTS "archive_root_idx" ON "archive" USING btree ("root");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "last_archive_root_idx" ON "last_archive" USING btree ("root");--> statement-breakpoint +ALTER TABLE "l2_tip_boundary_mismatch" ADD COLUMN IF NOT EXISTS "rollup_version" bigint;--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_tip_boundary_mismatch_unresolved_idx" ON "l2_tip_boundary_mismatch" USING btree ("l2_network_id","height") WHERE "resolved_at" IS NULL; diff --git a/services/explorer-api/migrations/0039_l2_reorg.sql b/services/explorer-api/migrations/0039_l2_reorg.sql new file mode 100644 index 000000000..ccc91bf60 --- /dev/null +++ b/services/explorer-api/migrations/0039_l2_reorg.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS "l2_reorg" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + "l2_network_id" varchar NOT NULL, + "rollup_version" bigint NOT NULL, + "cause_hash" varchar NOT NULL, + "cause_kind" varchar NOT NULL, + "observed_at" timestamp NOT NULL, + "revived_at" timestamp +);--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_reorg_network_observed_idx" ON "l2_reorg" USING btree ("l2_network_id","observed_at" DESC);--> statement-breakpoint +CREATE TABLE IF NOT EXISTS "l2_reorg_block" ( + "reorg_id" bigint NOT NULL REFERENCES "l2_reorg"("id") ON DELETE CASCADE, + "height" bigint NOT NULL, + "hash" varchar NOT NULL, + CONSTRAINT "l2_reorg_block_pkey" PRIMARY KEY ("reorg_id","hash") +);--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "l2_reorg_block_hash_idx" ON "l2_reorg_block" USING btree ("hash"); diff --git a/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql new file mode 100644 index 000000000..87c04a3ed --- /dev/null +++ b/services/explorer-api/migrations/0040_one_canonical_block_per_height.sql @@ -0,0 +1 @@ +CREATE UNIQUE INDEX "l2block_one_canonical_per_height_idx" ON "l2Block" USING btree ("version","height") WHERE "l2Block"."orphan_timestamp" IS NULL; diff --git a/services/explorer-api/migrations/meta/_journal.json b/services/explorer-api/migrations/meta/_journal.json index d145c6b7c..9b3a583c4 100644 --- a/services/explorer-api/migrations/meta/_journal.json +++ b/services/explorer-api/migrations/meta/_journal.json @@ -267,6 +267,27 @@ "when": 1779960000010, "tag": "0037_reset_open_gap_request_history", "breakpoints": true + }, + { + "idx": 38, + "version": "7", + "when": 1779960000011, + "tag": "0038_block_link_indexes", + "breakpoints": true + }, + { + "idx": 39, + "version": "7", + "when": 1779960000012, + "tag": "0039_l2_reorg", + "breakpoints": true + }, + { + "idx": 40, + "version": "7", + "when": 1779960000013, + "tag": "0040_one_canonical_block_per_height", + "breakpoints": true } ] } diff --git a/services/explorer-api/src/events/received/on-block/contracts.ts b/services/explorer-api/src/events/received/on-block/contracts.ts index 5498b5340..6a487db5b 100644 --- a/services/explorer-api/src/events/received/on-block/contracts.ts +++ b/services/explorer-api/src/events/received/on-block/contracts.ts @@ -11,13 +11,10 @@ import { chicmozL2ContractInstanceUpdatedEventSchema, type ChicmozL2ContractClassRegisteredEvent, type ChicmozL2ContractInstanceDeployedEvent, - type ChicmozL2PrivateFunctionBroadcastedEvent, - type ChicmozL2UtilityFunctionBroadcastedEvent, } from "@chicmoz-pkg/types"; import { z } from "zod"; import { logger } from "../../../logger.js"; -import { controllers } from "../../../svcs/database/index.js"; -import { handleDuplicateError } from "../utils.js"; +import { type BlockContracts } from "../../../svcs/database/controllers/l2contract/store.js"; const AZTEC_CONTRACT_CLASS_VERSION = 1; @@ -45,22 +42,11 @@ const parseObjs = ( return parsedObjs; }; -const storeObj = async ( - objs: T[], - storeFn: (obj: T) => Promise, - objType: string, - objId: keyof T, -) => { - for (const obj of objs) { - await storeFn(obj).catch((e) => { - const duplicateErrorId = obj[objId] as string; - handleDuplicateError(e as Error, `${objType} ${duplicateErrorId}`); - }); - } -}; - // NOTE: reference for parsing in aztec-packages: yarn-project/archiver/src/archiver/archiver.ts -export const storeContracts = async (b: L2Block, blockHash: string) => { +export const parseBlockContracts = async ( + b: L2Block, + blockHash: string, +): Promise => { const privateLogs = b.body.txEffects.flatMap( (txEffect) => txEffect.privateLogs, ); @@ -99,9 +85,6 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { contractClassRegisteredEvents.map((e) => e.toContractClassPublic()), ); - const privateFnEvents: unknown[] = []; - const utilityFnEvents: unknown[] = []; - if (contractClasses.length > 0) { logger.info( `๐Ÿ“œ Parsing and storing ${contractClasses.length} contract classes`, @@ -117,16 +100,6 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { `โฌ†๏ธ Parsing and storing ${contractInstanceUpdated.length} contract instances updated`, ); } - if (privateFnEvents.length > 0) { - logger.info( - `๐Ÿ”’ Parsing and storing ${privateFnEvents.length} private function events`, - ); - } - if (utilityFnEvents.length > 0) { - logger.info( - `๐Ÿ’ช Parsing and storing ${utilityFnEvents.length} utility function events`, - ); - } const contractClassesWithId = contractClasses.map((contractClass) => { return { @@ -189,37 +162,9 @@ export const storeContracts = async (b: L2Block, blockHash: string) => { newContractClassId: contractInstance.newContractClassId.toString(), } as ChicmozL2ContractInstanceUpdatedEvent), ); - const parsedPrivateFnEvents: ChicmozL2PrivateFunctionBroadcastedEvent[] = []; - const parsedUtilityFnEvents: ChicmozL2UtilityFunctionBroadcastedEvent[] = []; - - await storeObj( - parsedContractClasses, - controllers.l2Contract.storeContractClass, - "contractClass", - "contractClassId", - ); - await storeObj( - parsedContractInstancesDeployed, - controllers.l2Contract.storeContractInstanceDeployed, - "contractInstanceDeployed", - "address", - ); - await storeObj( - parsedContractInstanceUpdate, - controllers.l2Contract.storeContractInstanceUpdated, - "contractInstanceUpdated", - "address", - ); - await storeObj( - parsedPrivateFnEvents, - controllers.l2Contract.storePrivateFunction, - "privateFunction", - "artifactMetadataHash", - ); - await storeObj( - parsedUtilityFnEvents, - controllers.l2Contract.storeUtilityFunction, - "utilityFunction", - "artifactMetadataHash", - ); + return { + classes: parsedContractClasses, + instancesDeployed: parsedContractInstancesDeployed, + instancesUpdated: parsedContractInstanceUpdate, + }; }; 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 8673b4742..7bec3f7ac 100644 --- a/services/explorer-api/src/events/received/on-block/index.ts +++ b/services/explorer-api/src/events/received/on-block/index.ts @@ -1,260 +1,107 @@ import { blockFromBuffer, parseBlock } from "@chicmoz-pkg/backend-utils"; -import { type EventHandler } from "@chicmoz-pkg/message-bus"; +import { type EventHandler, type Heartbeat } from "@chicmoz-pkg/message-bus"; import { generateL2TopicName, getConsumerGroupId, + type CatchupBlockEvent, type NewBlockEvent, } from "@chicmoz-pkg/message-registry"; -import { - chicmozChainInfoSchema, - type ChicmozL2Block, - type ChicmozL2TxEffect, -} from "@chicmoz-pkg/types"; +import { chicmozChainInfoSchema } from "@chicmoz-pkg/types"; +import { z } from "zod"; import { SERVICE_NAME } from "../../../constants.js"; import { L2_NETWORK_ID } from "../../../environment.js"; import { logger } from "../../../logger.js"; import { observeRollupVersion } from "../../../svcs/database/controllers/l2/chain-info/rollup-version-cache.js"; import { - deleteL2BlockByHash, - deleteL2BlockByHeight, - getTxEffectOwners, - type TxEffectOwner, -} from "../../../svcs/database/controllers/l2block/delete.js"; -import { unOrphanBlock } from "../../../svcs/database/controllers/l2block/orphan.js"; + applyCatchupBlock, + applyOrderedBlock, + type ChainOutcome, + type IncomingBlock, +} from "../../../svcs/database/controllers/l2block/canonical.js"; import { controllers } from "../../../svcs/database/index.js"; -import { handleDuplicateBlockError, type PartialDbError } from "../utils.js"; -import { storeContracts } from "./contracts.js"; -import { detectReorg, handleReorg } from "./reorg-handler.js"; -import { type L2Block } from "@aztec-labs/aztec.js/block"; - -const truncateString = (value: string) => { - const startHash = value.substring(0, 100); - const endHash = value.substring(value.length - 100, value.length); - return `${startHash}...${endHash}`; -}; +import { parseBlockContracts } from "./contracts.js"; -// eslint-disable-next-line @typescript-eslint/no-unused-vars -const hackyLogBlock = (b: L2Block) => { - const blockString = JSON.stringify(b, null, 2); - const logString = blockString - .split(":") - .map((v) => { - if (v.length > 200 && v.includes(",")) { - return truncateString(v); - } - - return v; - }) - .join(":"); - logger.error(`๐Ÿšซ Block: ${logString}`); - b.body.txEffects.forEach((txEffect) => { - txEffect.privateLogs.forEach((log) => { - log.toFields().forEach((field) => { - logger.error(`๐Ÿšซ TxEffect: ${field.toString()}`); - }); - }); - }); -}; +const orderedSchema = z.object({ + proposedTip: z.number().int().nonnegative(), +}); -const onBlock = async ({ +const decode = async ({ block, blockNumber, -}: NewBlockEvent) => { +}: NewBlockEvent | CatchupBlockEvent): Promise => { if (!block) { logger.error("๐Ÿšซ Block is empty"); - return; + return undefined; } logger.info(`๐Ÿ‘“ Parsing block ${blockNumber}`); const b = blockFromBuffer(block); - let parsedBlock; + let parsed; try { - parsedBlock = await parseBlock(b); + parsed = await parseBlock(b); } catch (e) { logger.error( // eslint-disable-next-line @typescript-eslint/restrict-template-expressions `Failed to parse block ${blockNumber}: ${(e as Error)?.stack ?? e}`, ); - return; + return undefined; } + return { block: parsed, contracts: await parseBlockContracts(b, parsed.hash) }; +}; - const stored = await storeBlock(parsedBlock); - if (!stored) { +const afterCommit = async ( + { block }: IncomingBlock, + { canonical }: ChainOutcome, +) => { + if (!canonical) { return; } - await controllers.l2Block.markOpenGapsFulfilledByHeight(parsedBlock.height); + await controllers.l2Block.markOpenGapsFulfilledByHeight(block.height); await observeRollupVersion({ l2NetworkId: L2_NETWORK_ID, rollupVersion: chicmozChainInfoSchema.shape.rollupVersion.parse( - parsedBlock.header.globalVariables.version, + block.header.globalVariables.version, ), source: "block", }); - await storeContracts(b, parsedBlock.hash); - await pendingTxsHook(parsedBlock.body.txEffects); }; -/** - * @returns false when the block was skipped (see - * pruneConflictingOrphanedTxOwners); true when it is stored. - */ -const storeBlock = async ( - parsedBlock: ChicmozL2Block, - haveRetried = false, -): Promise => { - logger.info( - `๐Ÿงข Storing block ${parsedBlock.height} (hash: ${parsedBlock.hash})`, - ); - - const reorgDetected = await detectReorg(parsedBlock); - - // Decided before handleReorg writes anything, so a skip changes nothing. - const blockingOwners = await findBlockingTxOwners(parsedBlock, reorgDetected); - if (blockingOwners.length > 0) { - logSkippedTxConflict(parsedBlock, blockingOwners); - return false; - } - - if (reorgDetected) { - await handleReorg(parsedBlock); +// Only the hash-following listener marks its blocks ordered. An unordered +// block carries no chain authority, and storing it could build runs of +// unlinked blocks that a later walk would have to cross. +const onBlock = async (event: NewBlockEvent, heartbeat: Heartbeat) => { + if (event.ordered === undefined) { + logger.warn(`Ignoring block ${event.blockNumber}: not from the ordered stream`); + return; } - - // Set orphan fields to null/false for the new block - parsedBlock.orphan = undefined; - - // Store the new block - try { - await controllers.l2Block.store(parsedBlock); - return true; - } catch (e) { - if (haveRetried) { - throw new Error( - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - `Failed to store block ${parsedBlock.height} after retry: ${e}`, - ); - } - // Only duplicates are resolved below. Anything else propagates, so the - // message bus redelivers the block instead of it being lost. - if ((e as PartialDbError).code !== "23505") { - throw e; - } - - // If we still get an error, we'll try the old approach as fallback - const outcome = await handleDuplicateBlockError( - e as Error, - `block ${parsedBlock.height}`, - async () => { - logger.warn( - `Deleting block ${parsedBlock.height} (hash: ${parsedBlock.hash})`, - ); - await deleteL2BlockByHeight(parsedBlock.height); - }, - async () => { - // The block hash already exists but is orphaned โ€” un-orphan it - // since the node is serving it as the canonical block. - await unOrphanBlock(parsedBlock.hash); - }, - async () => pruneConflictingOrphanedTxOwners(parsedBlock), + const ordered = orderedSchema.safeParse(event.ordered); + if (!ordered.success) { + logger.error( + `Ignoring block ${event.blockNumber}: invalid ordered field ${JSON.stringify(event.ordered)}`, ); - - if (outcome === "retry") { - return storeBlock(parsedBlock, true); - } - return outcome === "done"; + return; } -}; - -const ownerSummary = (owners: TxEffectOwner[]) => - owners - .map( - (owner) => - `${owner.txHash} in active block ${owner.blockHeight} (${owner.blockHash})`, - ) - .join(", "); - -const logSkippedTxConflict = ( - parsedBlock: ChicmozL2Block, - activeOwners: TxEffectOwner[], -) => { - logger.error( - `SKIPPED_BLOCK_TX_CONFLICT height=${parsedBlock.height} hash=${parsedBlock.hash} owners=${ownerSummary(activeOwners)}`, + const incoming = await decode(event); + if (!incoming) { + return; + } + await afterCommit( + incoming, + await applyOrderedBlock(incoming, ordered.data.proposedTip, heartbeat), ); }; -/** - * Active blocks holding the block's txs that its own reorg would leave - * active. handleReorg orphans the active block at the block's height and - * the blocks above it; an active holder elsewhere (below the height, on - * another rollup version, or anywhere when there is no reorg) means the - * block is skipped, as deciding which of the two is canonical is out of - * scope here. - */ -const findBlockingTxOwners = async ( - parsedBlock: ChicmozL2Block, - reorgDetected: boolean, +const onCatchupBlock = async ( + event: CatchupBlockEvent, + heartbeat: Heartbeat, ) => { - const owners = await getTxEffectOwners( - parsedBlock.body.txEffects.map((txEffect) => txEffect.txHash), - ); - const rollupVersion = parsedBlock.header.globalVariables.version; - return owners.filter( - (owner) => - !owner.isOrphaned && - owner.blockHash !== parsedBlock.hash && - !( - reorgDetected && - owner.rollupVersion === rollupVersion && - owner.blockHeight >= parsedBlock.height - ), - ); -}; - -/** - * Frees the block's txs from orphaned blocks still holding them, so the - * retry can store it (the multi-block reorg case). - * - * @returns false when an ACTIVE block holds one of its txs. The block is - * then skipped (the message is acked, not redelivered forever as before, - * which wedged mainnet for ~23h) and logged as SKIPPED_BLOCK_TX_CONFLICT; - * its height stays empty until something stores it. - */ -const pruneConflictingOrphanedTxOwners = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - const incomingTxHashes = parsedBlock.body.txEffects.map( - (txEffect) => txEffect.txHash, - ); - const owners = await getTxEffectOwners(incomingTxHashes); - - if (owners.length === 0) { - logger.error( - `Duplicate tx_hash while storing block ${parsedBlock.height}, but no existing tx owner was found`, - ); - throw new Error( - `Duplicate tx_hash while storing block ${parsedBlock.height}, but no existing tx owner was found`, - ); - } - - // Normally caught up front by findBlockingTxOwners; checked again in case - // a holder became active in between. - const activeOwners = owners.filter((owner) => !owner.isOrphaned); - if (activeOwners.length > 0) { - logSkippedTxConflict(parsedBlock, activeOwners); - return false; + const incoming = await decode(event); + if (!incoming) { + return; } - - const orphanedOwnerHashes = [...new Set(owners.map((owner) => owner.blockHash))]; - logger.warn( - `Pruning ${orphanedOwnerHashes.length} orphaned tx owner block(s) before retrying block ${parsedBlock.height}: ${orphanedOwnerHashes.join(", ")}`, + await afterCommit( + incoming, + await applyCatchupBlock(incoming, event.finalized === true, heartbeat), ); - - for (const blockHash of orphanedOwnerHashes) { - await deleteL2BlockByHash(blockHash); - } - return true; -}; - -const pendingTxsHook = async (txEffects: ChicmozL2TxEffect[]) => { - await controllers.l2Tx.removePendingAndDroppedTx(txEffects); }; export const blockHandler: EventHandler = { @@ -264,7 +111,7 @@ export const blockHandler: EventHandler = { handlerName: "blockHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "NEW_BLOCK_EVENT"), - cb: onBlock as (arg0: unknown) => Promise, + cb: onBlock as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; export const catchupHandler: EventHandler = { @@ -274,8 +121,5 @@ export const catchupHandler: EventHandler = { handlerName: "catchupHandler", }), topic: generateL2TopicName(L2_NETWORK_ID, "CATCHUP_BLOCK_EVENT"), - cb: ((event: NewBlockEvent) => { - logger.info(`Catchup block event`); - return onBlock(event); - }) as (arg0: unknown) => Promise, + cb: onCatchupBlock as (arg0: unknown, heartbeat: Heartbeat) => Promise, }; diff --git a/services/explorer-api/src/events/received/on-block/reorg-handler.ts b/services/explorer-api/src/events/received/on-block/reorg-handler.ts deleted file mode 100644 index 0866a7bc5..000000000 --- a/services/explorer-api/src/events/received/on-block/reorg-handler.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { ChicmozL2Block } from "@chicmoz-pkg/types"; -import { logger } from "../../../logger.js"; -import { getBlock } from "../../../svcs/database/controllers/l2block/get-block.js"; -import { handleReorgOrphaning } from "../../../svcs/database/controllers/l2block/orphan.js"; - -/** - * Detects if there's a re-org at the given block height - */ -export const detectReorg = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - // Check if a block with the same height but different hash already exists - const existingBlock = await getBlock(parsedBlock.height, { - rollupVersion: parsedBlock.header.globalVariables.version, - }); - return !!(existingBlock && existingBlock.hash !== parsedBlock.hash); -}; - -/** - * Handles a re-org by marking the existing block and higher blocks of the - * parsed block's rollup version as orphaned and storing their transactions - * as dropped - */ -export const handleReorg = async ( - parsedBlock: ChicmozL2Block, -): Promise => { - const rollupVersion = parsedBlock.header.globalVariables.version; - const existingBlock = await getBlock(parsedBlock.height, { rollupVersion }); - - if (!existingBlock) { - return; - } - - logger.warn( - `Re-org detected at height ${parsedBlock.height}. Existing hash: ${existingBlock.hash}, new hash: ${parsedBlock.hash}`, - ); - - // Handle the orphaning in a database transaction - const totalOrphaned = await handleReorgOrphaning( - existingBlock.hash, - parsedBlock.height, - rollupVersion, - ); - logger.warn( - `Completed re-org handling at height ${parsedBlock.height}. Total orphaned blocks: ${totalOrphaned}`, - ); -}; diff --git a/services/explorer-api/src/events/received/utils.ts b/services/explorer-api/src/events/received/utils.ts index b1e8f02cc..9091b45f8 100644 --- a/services/explorer-api/src/events/received/utils.ts +++ b/services/explorer-api/src/events/received/utils.ts @@ -1,76 +1,10 @@ import { logger } from "../../logger.js"; -export type PartialDbError = { +type PartialDbError = { code: string; detail: string; }; -/** - * What storing a block should do after a duplicate-key error: - * - "retry": the conflict was cleared; store the block again. - * - "done": the block is already stored (un-orphaned if needed). - * - "skip": the block is not stored; skip it and its hooks. - */ -export type DuplicateBlockOutcome = "retry" | "done" | "skip"; - -export const handleDuplicateBlockError = async ( - e: Error | PartialDbError, - additionalInfo: string, - deleteBlockCallback: () => Promise, - unOrphanCallback?: () => Promise, - // Resolves false when the conflict cannot be cleared and the block is skipped. - resolveDuplicateTxHashCallback?: () => Promise, -): Promise => { - if ((e as PartialDbError).code === "23505") { - const detail = (e as PartialDbError).detail; - if (detail.includes("(hash)")) { - // Block with exact same hash already exists. - // If the existing block is orphaned, un-orphan it instead of skipping. - if (unOrphanCallback) { - logger.info( - `DB duplicate hash for "${additionalInfo}": attempting to un-orphan existing block. [${detail}]`, - ); - await unOrphanCallback(); - } else { - logger.warn( - `DB duplicate for "${additionalInfo}" skipping... [${detail}]`, - ); - } - return "done"; - } else if (detail.includes("(tx_hash)")) { - // tx_hash duplicate: a transaction from this block already exists. Prefer - // resolving the actual owning block over deleting the incoming height. - if (resolveDuplicateTxHashCallback) { - logger.warn( - `DB duplicate tx_hash for "${additionalInfo}": resolving tx owner and retrying. [${detail}]`, - ); - return (await resolveDuplicateTxHashCallback()) ? "retry" : "skip"; - } - - logger.warn( - `DB duplicate tx_hash for "${additionalInfo}": deleting block at height and retrying. [${detail}]`, - ); - await deleteBlockCallback(); - return "retry"; - } else if (detail.includes("(height)")) { - // height duplicate: same as before. - logger.warn( - `DB duplicate for "${additionalInfo}": deleting block at height and retrying. [${detail}]`, - ); - await deleteBlockCallback(); - return "retry"; - } - // A key this handler does not know: the block was not stored, and - // counting it as stored would run its hooks and fulfil its gap. - logger.error( - `DB duplicate on an unexpected key for "${additionalInfo}": not stored, skipping. [${detail}]`, - ); - return "skip"; - } - handleOtherError(e as Error, additionalInfo); - return "skip"; -}; - export const handleDuplicateError = ( e: Error | PartialDbError, additionalInfo: string, diff --git a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts index 2f8f3a32e..c1af0ef35 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.ts @@ -1,46 +1,51 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { type ChicmozL2TxEffect } from "@chicmoz-pkg/types"; -import { eq } from "drizzle-orm"; +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; +import { type HexString } from "@chicmoz-pkg/types"; +import { eq, inArray } from "drizzle-orm"; import { logger } from "../../../../logger.js"; -import { l2Tx } from "../../../database/schema/l2tx/index.js"; +import { droppedTx } from "../../../database/schema/dropped-tx/index.js"; import { txEffect } from "../../../database/schema/l2block/body.js"; -import { removeDroppedTxByHash } from "../../controllers/dropped-tx/remove.js"; +import { l2Tx } from "../../../database/schema/l2tx/index.js"; +import { type DbTx } from "../utils.js"; +/** + * For txs now mined on the canonical chain: deletes their pending rows, + * copying each pending tx's fee and identity fields onto its tx effect, and + * their dropped rows, whether or not a pending row existed. + */ export const removePendingAndDroppedTx = async ( - txEffects: ChicmozL2TxEffect[], + dbTx: DbTx, + txHashes: HexString[], + heartbeat: Heartbeat, ): Promise => { - return await db().transaction(async (dbTx) => { - for (const txEffectRow of Object.values(txEffects)) { - const deleted = await dbTx - .delete(l2Tx) - .where(eq(l2Tx.txHash, txEffectRow.txHash)) - .returning(); - - if (!deleted || deleted.length === 0) { - continue; - } - - logger.info(`๐Ÿ•๐Ÿ”ฅ deleted pending tx ${txEffectRow.txHash}`); - - const pendingTx = deleted[0]; - - // Copy fee/identity fields from the deleted pending tx onto the mined tx effect row. - await dbTx - .update(txEffect) - .set({ - feePayer: pendingTx.feePayer ?? null, - feePaymentMethod: pendingTx.feePaymentMethod ?? null, - initiator: pendingTx.initiator ?? null, - }) - .where(eq(txEffect.txHash, txEffectRow.txHash)); - - try { - await removeDroppedTxByHash(txEffectRow.txHash); - } catch (e) { - logger.error( - `Error removing dropped tx ${txEffectRow.txHash}: ${(e as Error).stack}`, - ); - } - } - }); + if (txHashes.length === 0) { + return; + } + const pending = await dbTx + .delete(l2Tx) + .where(inArray(l2Tx.txHash, txHashes)) + .returning({ + txHash: l2Tx.txHash, + feePayer: l2Tx.feePayer, + feePaymentMethod: l2Tx.feePaymentMethod, + initiator: l2Tx.initiator, + }); + for (const pendingTx of pending) { + logger.info(`๐Ÿ•๐Ÿ”ฅ deleted pending tx ${pendingTx.txHash}`); + await heartbeat(); + await dbTx + .update(txEffect) + .set({ + feePayer: pendingTx.feePayer ?? null, + feePaymentMethod: pendingTx.feePaymentMethod ?? null, + initiator: pendingTx.initiator ?? null, + }) + .where(eq(txEffect.txHash, pendingTx.txHash)); + } + const dropped = await dbTx + .delete(droppedTx) + .where(inArray(droppedTx.txHash, txHashes)) + .returning({ txHash: droppedTx.txHash }); + for (const { txHash } of dropped) { + logger.info(`๐Ÿ—‘๏ธ๐Ÿ”ฅ removed dropped tx ${txHash}`); + } }; diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts new file mode 100644 index 000000000..90ba720bf --- /dev/null +++ b/services/explorer-api/src/svcs/database/controllers/l2block/canonical.ts @@ -0,0 +1,913 @@ +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; +import { getDb as db } from "@chicmoz-pkg/postgres-helper"; +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"; +import { L2_NETWORK_ID } from "../../../../environment.js"; +import { logger } from "../../../../logger.js"; +import { droppedTx } from "../../schema/dropped-tx/index.js"; +import { + type ReorgCauseKind, + l2ReorgBlockTable, + l2ReorgTable, +} from "../../schema/l2/reorg.js"; +import { + archive, + body, + header, + l2Block, + lastArchive, + txEffect, +} from "../../schema/l2block/index.js"; +import { + storeBlockContracts, + type BlockContracts, +} from "../l2contract/store.js"; +import { removePendingAndDroppedTx } from "../l2Tx/remove-pending-and-dropped.js"; +import { type DbTx } from "../utils.js"; +import { fulfilRepairHeight, recordRepairHeights } from "./missing-ranges.js"; +import { store, writeTxEffect } from "./store.js"; + +// Every change to which blocks are canonical goes through this module. +// +// Invariant: once a listener pass is applied, the canonical blocks of each +// rollup version (orphan_timestamp IS NULL) hold at most one block per +// height, any two at adjacent heights are linked, and none sits above the +// pass's tip. Linked: child.last_archive.root = parent.archive.root, one +// height apart, same version. The child's hash covers its last archive; the +// parent's archive root is outside the parent's hash, so two stored parents +// make a lookup ambiguous. +// +// One canonical block per height also holds after every statement: the +// unique index l2block_one_canonical_per_height_idx refuses a second. So a +// change demotes a height's canonical block before it promotes another +// there, and a violation propagates, failing the change for redelivery. +// +// Ordered blocks are the listener's chain, sent in order: each is canonical +// at its height and nothing canonical stays above its tip. Catch-up blocks +// only fill empty heights below the canonical head; one that the chain above +// 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; +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; +}; + +/** `canonical`: the block ends on the chain, its txs attached from its message. */ +export type ChainOutcome = { canonical: boolean }; + +type ChainBlock = { + hash: HexString; + height: bigint; + version: number; + canonical: boolean; + archiveRoot: string | null; + lastArchiveRoot: string | null; +}; + +type StoredBlock = ChainBlock & { bodyId: string; created: boolean }; + +type Change = { + dbTx: DbTx; + version: number; + now: number; + /** The incoming block this change applies: its reorg record names it. */ + cause: { hash: HexString; kind: ReorgCauseKind }; + heartbeat: Heartbeat; + steps: number; + demoted: Map; + promoted: Map; + // Made canonical without their own message: their moved txs need it back. + walked: Map; + repairs: Set; +}; + +type TxOwner = { + txHash: HexString; + blockHash: HexString; + height: bigint; + canonical: boolean; +}; + +class TxConflict extends Error { + constructor( + readonly block: ChicmozL2Block, + readonly owners: TxOwner[], + ) { + super(`block ${block.height} shares txs with canonical blocks`); + } +} + +/** + * Runs `write` over `items` in statements of at most ROWS_PER_STATEMENT rows, + * heartbeating before each: KafkaJS sends at most one heartbeat per interval, + * so the calls cost nothing in between. + */ +const inStatements = async ( + change: Change, + items: T[], + write: (part: T[]) => Promise, +) => { + for (let i = 0; i < items.length; i += ROWS_PER_STATEMENT) { + await change.heartbeat(); + await write(items.slice(i, i + ROWS_PER_STATEMENT)); + } +}; + +const step = async (change: Change) => { + change.steps++; + if (change.steps % HEARTBEAT_EVERY === 0) { + await change.heartbeat(); + } +}; + +const chainBlocks = (dbTx: DbTx) => + dbTx + .select({ + hash: l2Block.hash, + height: l2Block.height, + version: l2Block.version, + orphanTimestamp: l2Block.orphan_timestamp, + archiveRoot: archive.root, + lastArchiveRoot: lastArchive.root, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(header, eq(header.blockHash, l2Block.hash)) + .innerJoin(lastArchive, eq(lastArchive.fk, header.id)); + +const toChainBlock = ({ + orphanTimestamp, + ...row +}: { + hash: HexString; + height: bigint; + version: number; + orphanTimestamp: number | null; + archiveRoot: string | null; + lastArchiveRoot: string | null; +}): ChainBlock => ({ ...row, canonical: orphanTimestamp === null }); + +const canonicalAt = async (change: Change, height: bigint) => + ( + await chainBlocks(change.dbTx).where( + and( + eq(l2Block.version, change.version), + eq(l2Block.height, height), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); + +const storedParents = async (change: Change, child: ChainBlock) => + child.lastArchiveRoot === null + ? [] + : ( + await chainBlocks(change.dbTx) + .where( + and( + eq(archive.root, child.lastArchiveRoot), + eq(l2Block.height, child.height - 1n), + eq(l2Block.version, child.version), + ), + ) + .limit(2) + ).map(toChainBlock); + +const canonicalChildren = async ( + change: Change, + parents: ChainBlock[], + height: bigint, +) => { + const roots = parents.flatMap((p) => (p.archiveRoot ? [p.archiveRoot] : [])); + if (roots.length === 0) { + return []; + } + return ( + await chainBlocks(change.dbTx).where( + and( + inArray(lastArchive.root, roots), + eq(l2Block.height, height), + eq(l2Block.version, change.version), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); +}; + +const txOwners = async (dbTx: DbTx, txHashes: HexString[]) => + txHashes.length === 0 + ? [] + : ( + await dbTx + .select({ + txHash: txEffect.txHash, + blockHash: l2Block.hash, + height: l2Block.height, + orphanTimestamp: l2Block.orphan_timestamp, + }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) + .where(inArray(txEffect.txHash, txHashes)) + ).map( + ({ orphanTimestamp, ...owner }): TxOwner => ({ + ...owner, + canonical: orphanTimestamp === null, + }), + ); + +const ownedTxs = async (change: Change, blockHashes: HexString[]) => { + const owned: { txHash: HexString; birth: number }[] = []; + await inStatements(change, blockHashes, async (part) => { + owned.push( + ...(await change.dbTx + .select({ txHash: txEffect.txHash, birth: txEffect.txBirthTimestamp }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .where(inArray(body.blockHash, part))), + ); + }); + return owned; +}; + +const demote = async (change: Change, blocks: { hash: HexString }[]) => { + const hashes = blocks + .map((b) => b.hash) + .filter((hash) => !change.demoted.has(hash)); + await inStatements(change, hashes, async (part) => { + const rows = await change.dbTx + .update(l2Block) + .set({ orphan_timestamp: change.now, orphan_hasOrphanedParent: false }) + .where(and(inArray(l2Block.hash, part), isNull(l2Block.orphan_timestamp))) + .returning({ hash: l2Block.hash, height: l2Block.height }); + rows.forEach((row) => change.demoted.set(row.hash, row.height)); + }); +}; + +const promote = async ( + change: Change, + block: ChainBlock, + { walked }: { walked: boolean }, +) => { + const rows = await change.dbTx + .update(l2Block) + .set({ orphan_timestamp: null, orphan_hasOrphanedParent: false }) + .where( + and(eq(l2Block.hash, block.hash), isNotNull(l2Block.orphan_timestamp)), + ) + .returning({ hash: l2Block.hash }); + if (rows.length > 0) { + change.promoted.set(block.hash, block.height); + if (walked) { + change.walked.set(block.hash, block.height); + } + } +}; + +/** Demotes `start` and the canonical blocks linked above it, up to `ceiling`. */ +const demoteLinkedRun = async ( + change: Change, + start: ChainBlock, + ceiling: bigint, +) => { + const run = [start]; + let frontier = [start]; + for ( + let height = start.height + 1n, steps = 0; + height <= ceiling && frontier.length > 0 && steps < WALK_BOUND; + height++, steps++ + ) { + await step(change); + frontier = await canonicalChildren(change, frontier, height); + run.push(...frontier); + } + await demote(change, run); +}; + +/** + * Demotes every other canonical block of the version up to `ceiling` that + * holds one of `block`'s txs, with its linked run up to `ceiling`: a tx is + * included once per chain, so no such holder is on the chain `block` is + * canonical on. + */ +const demoteHolders = async ( + change: Change, + block: ChicmozL2Block, + ceiling: bigint, +) => { + const holders = new Set( + ( + await txOwners( + change.dbTx, + block.body.txEffects.map((e) => e.txHash), + ) + ) + .filter( + (o) => o.canonical && o.blockHash !== block.hash && o.height <= ceiling, + ) + .map((o) => o.blockHash), + ); + for (const hash of holders) { + const [holder] = ( + await chainBlocks(change.dbTx).where( + and( + eq(l2Block.hash, hash), + eq(l2Block.version, change.version), + isNull(l2Block.orphan_timestamp), + ), + ) + ).map(toChainBlock); + if (holder) { + await demoteLinkedRun(change, holder, ceiling); + } + } +}; + +/** + * Brings back the stored, off-chain ancestors of a block that just became + * canonical, demoting their competitors. Ends at a canonical parent; at a + * missing one, or after WALK_BOUND blocks, it clears that height, whose block + * cannot be the parent, and asks for the parent. + */ +const reviveAncestors = async (change: Change, start: ChainBlock) => { + let child = start; + for (let steps = 0; child.height > 1n; steps++) { + const below = child.height - 1n; + await step(change); + const parents = await storedParents(change, child); + if (parents.length > 1) { + logger.error( + `CHAIN_LINK_CONFLICT: several stored blocks at ${below} have the archive root that block ${child.height} (${child.hash}) names; height ${below} left as it is`, + ); + return; + } + const [parent] = parents; + if (parent?.canonical) { + return; + } + await demote(change, await canonicalAt(change, below)); + if (!parent || steps === WALK_BOUND) { + change.repairs.add(below); + return; + } + await promote(change, parent, { walked: true }); + child = parent; + } +}; + +/** Asks for every height below `height` that this change left without a canonical block. */ +const requestEmptied = async (change: Change, height: bigint) => { + const emptied = [ + ...new Set([...change.demoted.values()].filter((h) => h < height)), + ]; + const occupied = new Set(); + await inStatements(change, emptied, async (part) => { + const rows = await change.dbTx + .selectDistinct({ height: l2Block.height }) + .from(l2Block) + .where( + and( + eq(l2Block.version, change.version), + inArray(l2Block.height, part), + isNull(l2Block.orphan_timestamp), + ), + ); + rows.forEach((row) => occupied.add(row.height)); + }); + emptied.filter((h) => !occupied.has(h)).forEach((h) => change.repairs.add(h)); +}; + +const demoteAbove = async (change: Change, ceiling: bigint) => { + const above = await change.dbTx + .select({ hash: l2Block.hash }) + .from(l2Block) + .where( + and( + eq(l2Block.version, change.version), + gt(l2Block.height, ceiling), + isNull(l2Block.orphan_timestamp), + ), + ) + .limit(WALK_BOUND + 1); + if (above.length > WALK_BOUND) { + throw new Error( + `More than ${WALK_BOUND} canonical blocks of rollup version ${change.version} above tip ${ceiling}: refusing to demote them`, + ); + } + await demote(change, above); +}; + +// `head`: no canonical block above, so nothing to descend from. +type Link = { walked: ChainBlock[] } | "excludes" | "undecided" | "head"; + +/** + * Whether the lowest canonical block above an empty height descends from + * `block`, through the stored, off-chain blocks between them. + */ +const linkFromAbove = async ( + change: Change, + block: ChainBlock, +): Promise => { + const [lowest] = await chainBlocks(change.dbTx) + .where( + and( + eq(l2Block.version, change.version), + gt(l2Block.height, block.height), + isNull(l2Block.orphan_timestamp), + ), + ) + .orderBy(asc(l2Block.height)) + .limit(1); + if (!lowest) { + return "head"; + } + const walked: ChainBlock[] = []; + let child = toChainBlock(lowest); + for (let steps = 0; steps < WALK_BOUND; steps++) { + await step(change); + const parents = await storedParents(change, child); + if (child.height === block.height + 1n) { + if (parents.length > 1) { + return "undecided"; + } + return parents[0]?.hash === block.hash ? { walked } : "excludes"; + } + const [parent] = parents; + if (parents.length !== 1 || parent.canonical) { + return "undecided"; + } + walked.push(parent); + child = parent; + } + return "undecided"; +}; + +const storeIfAbsent = async ( + change: Change, + block: ChicmozL2Block, + { ordered }: { ordered: boolean }, +): Promise => { + const node = { + hash: block.hash, + height: block.height, + version: change.version, + archiveRoot: block.archive.root, + lastArchiveRoot: block.header.lastArchive.root, + }; + const [existing] = await change.dbTx + .select({ + orphanTimestamp: l2Block.orphan_timestamp, + archiveId: archive.id, + archiveRoot: archive.root, + bodyId: body.id, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(body, eq(body.blockHash, l2Block.hash)) + .where(eq(l2Block.hash, block.hash)) + .limit(1); + if (!existing) { + const bodyId = await store(change.dbTx, block, change.now); + return { ...node, canonical: false, bodyId, created: true }; + } + const stored = { + ...node, + canonical: existing.orphanTimestamp === null, + bodyId: existing.bodyId, + created: false, + }; + if (existing.archiveRoot === node.archiveRoot) { + return stored; + } + // The archive root is outside the block hash: the ordered stream's copy wins. + logger.warn( + `Block ${block.height} (${block.hash}) arrived with archive root ${node.archiveRoot}, stored with ${existing.archiveRoot}; keeping the ${ordered ? "ordered" : "stored"} one`, + ); + if (!ordered) { + return { ...stored, archiveRoot: existing.archiveRoot }; + } + await change.dbTx + .update(archive) + .set({ + root: block.archive.root, + nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, + }) + .where(eq(archive.id, existing.archiveId)); + return stored; +}; + +/** + * Writes the block's tx effects from its message. A canonical block takes + * every one, moving those that off-chain blocks hold; an off-chain block + * only takes those no block holds. + */ +const attachTxs = async ( + change: Change, + stored: StoredBlock, + block: ChicmozL2Block, + { canonical }: { canonical: boolean }, +) => { + const effects = block.body.txEffects; + const owners = new Map( + ( + await txOwners( + change.dbTx, + effects.map((e) => e.txHash), + ) + ).map((o) => [o.txHash, o]), + ); + if (canonical) { + const conflicts = [...owners.values()].filter( + (o) => o.canonical && o.blockHash !== block.hash, + ); + if (conflicts.length > 0) { + throw new TxConflict(block, conflicts); + } + } + for (const [index, effect] of effects.entries()) { + const owner = owners.get(effect.txHash); + if (owner?.blockHash === block.hash || (owner && !canonical)) { + continue; + } + // An effect is at most two statements plus one per public data write, + // which the protocol caps at 64 a tx. + await change.heartbeat(); + await writeTxEffect(change.dbTx, { + bodyId: stored.bodyId, + index, + effect, + held: owner !== undefined, + }); + } +}; + +const recordReorg = async (change: Change) => { + const blocks = [...change.demoted] + .map(([hash, height]) => ({ hash, height })) + .sort((a, b) => + a.height === b.height + ? a.hash.localeCompare(b.hash) + : a.height < b.height + ? -1 + : 1, + ); + const [record] = await change.dbTx + .insert(l2ReorgTable) + .values({ + l2NetworkId: L2_NETWORK_ID, + rollupVersion: change.version, + causeHash: change.cause.hash, + causeKind: change.cause.kind, + observedAt: new Date(change.now), + }) + .returning({ id: l2ReorgTable.id }); + await inStatements(change, blocks, async (part) => { + await change.dbTx + .insert(l2ReorgBlockTable) + .values(part.map((b) => ({ reorgId: record.id, ...b }))); + }); + const [lowest] = blocks; + logger.warn( + `L2 reorg at height ${lowest.height}: ${blocks.length} block(s) left the chain, the lowest ${lowest.hash}, applying ${change.cause.kind} block ${change.cause.hash}`, + ); +}; + +const markDemotedTxsDropped = async (change: Change) => { + const orphaned = await ownedTxs(change, [...change.demoted.keys()]); + await inStatements(change, orphaned, async (part) => { + await change.dbTx + .insert(droppedTx) + .values( + part.map(({ txHash, birth }) => ({ + txHash, + createdAsPendingAt: birth, + droppedAt: change.now, + dropReason: "orphaned", + })), + ) + .onConflictDoNothing(); + }); +}; + +/** A record is revived once every block it lists is stored and canonical again. */ +const reviveRecords = async (change: Change) => { + await inStatements(change, [...change.promoted.keys()], async (part) => { + await change.dbTx + .update(l2ReorgTable) + .set({ revivedAt: new Date(change.now) }) + .where( + and( + eq(l2ReorgTable.l2NetworkId, L2_NETWORK_ID), + isNull(l2ReorgTable.revivedAt), + inArray( + l2ReorgTable.id, + change.dbTx + .select({ id: l2ReorgBlockTable.reorgId }) + .from(l2ReorgBlockTable) + .where(inArray(l2ReorgBlockTable.hash, part)), + ), + sql`NOT EXISTS (SELECT 1 FROM ${l2ReorgBlockTable} LEFT JOIN ${l2Block} ON ${l2Block.hash} = ${l2ReorgBlockTable.hash} WHERE ${l2ReorgBlockTable.reorgId} = ${l2ReorgTable.id} AND (${l2Block.hash} IS NULL OR ${l2Block.orphan_timestamp} IS NOT NULL))`, + ), + ); + }); +}; + +const setHasOrphanedParent = async ( + change: Change, + hashes: HexString[], + value: boolean, +) => { + await inStatements(change, hashes, async (part) => { + await change.dbTx + .update(l2Block) + .set({ orphan_hasOrphanedParent: value }) + .where( + and(inArray(l2Block.hash, part), isNotNull(l2Block.orphan_timestamp)), + ); + }); +}; + +/** + * `orphan_hasOrphanedParent` of an off-chain block: its stored parent is off + * the chain too. Refreshed for the blocks this call demoted or stored off the + * chain, and for the off-chain children of those and of the blocks it made + * canonical. + */ +const refreshOrphanFlags = async (change: Change, storedOff: HexString[]) => { + const parent = alias(l2Block, "parent"); + const parentArchive = alias(archive, "parent_archive"); + const deadParent: HexString[] = []; + await inStatements( + change, + [...change.demoted.keys(), ...storedOff], + async (part) => { + const rows = await change.dbTx + .selectDistinct({ hash: l2Block.hash }) + .from(l2Block) + .innerJoin(header, eq(header.blockHash, l2Block.hash)) + .innerJoin(lastArchive, eq(lastArchive.fk, header.id)) + .innerJoin(parentArchive, eq(parentArchive.root, lastArchive.root)) + .innerJoin( + parent, + and( + eq(parent.hash, parentArchive.fk), + eq(parent.height, sql`${l2Block.height} - 1`), + eq(parent.version, l2Block.version), + ), + ) + .where( + and(inArray(l2Block.hash, part), isNotNull(parent.orphan_timestamp)), + ); + deadParent.push(...rows.map((r) => r.hash)); + }, + ); + + const child = alias(l2Block, "child"); + const childHeader = alias(header, "child_header"); + const childLastArchive = alias(lastArchive, "child_last_archive"); + const moved = [ + ...change.demoted.keys(), + ...change.promoted.keys(), + ...storedOff, + ]; + const liveParent: HexString[] = []; + await inStatements(change, moved, async (part) => { + const rows = await change.dbTx + .selectDistinct({ + hash: child.hash, + parentOrphanTimestamp: l2Block.orphan_timestamp, + }) + .from(l2Block) + .innerJoin(archive, eq(archive.fk, l2Block.hash)) + .innerJoin(childLastArchive, eq(childLastArchive.root, archive.root)) + .innerJoin(childHeader, eq(childHeader.id, childLastArchive.fk)) + .innerJoin( + child, + and( + eq(child.hash, childHeader.blockHash), + eq(child.height, sql`${l2Block.height} + 1`), + eq(child.version, l2Block.version), + ), + ) + .where( + and(inArray(l2Block.hash, part), isNotNull(child.orphan_timestamp)), + ); + for (const row of rows) { + (row.parentOrphanTimestamp === null ? liveParent : deadParent).push( + row.hash, + ); + } + }); + await setHasOrphanedParent(change, deadParent, true); + await setHasOrphanedParent(change, liveParent, false); +}; + +const settle = async ( + change: Change, + block: ChicmozL2Block, + { canonical, created }: { canonical: boolean; created: boolean }, +) => { + if (change.demoted.size > 0) { + await recordReorg(change); + } + await markDemotedTxsDropped(change); + const mined = new Set( + (await ownedTxs(change, [...change.promoted.keys()])).map((t) => t.txHash), + ); + if (canonical) { + block.body.txEffects.forEach((e) => mined.add(e.txHash)); + } + await inStatements(change, [...mined], (part) => + removePendingAndDroppedTx(change.dbTx, part, change.heartbeat), + ); + await reviveRecords(change); + await refreshOrphanFlags(change, created && !canonical ? [block.hash] : []); + await inStatements( + change, + [...new Set([...change.walked.values(), ...change.repairs])], + (part) => recordRepairHeights(change.dbTx, part), + ); + if (canonical) { + await fulfilRepairHeight(change.dbTx, block.height); + } +}; + +const ownerSummary = (owners: TxOwner[]) => + owners + .map((o) => `${o.txHash} in active block ${o.height} (${o.blockHash})`) + .join(", "); + +const apply = async ( + { block, contracts }: IncomingBlock, + heartbeat: Heartbeat, + { ordered }: { ordered: boolean }, + decide: (change: Change, stored: StoredBlock) => Promise, +): Promise => { + try { + return await withChainLock(async (dbTx) => { + const change: Change = { + dbTx, + version: block.header.globalVariables.version, + now: Date.now(), + cause: { hash: block.hash, kind: ordered ? "ordered" : "catchup" }, + heartbeat, + steps: 0, + demoted: new Map(), + promoted: new Map(), + walked: new Map(), + repairs: new Set(), + }; + const stored = await storeIfAbsent(change, block, { ordered }); + const canonical = await decide(change, stored); + await attachTxs(change, stored, block, { canonical }); + if (canonical) { + await storeBlockContracts(dbTx, contracts, heartbeat); + } + await settle(change, block, { canonical, created: stored.created }); + logger.info( + `๐Ÿงข Applied ${ordered ? "ordered" : "catch-up"} block ${block.height} (${block.hash}): ${canonical ? "canonical" : "off the chain"}; demoted ${change.demoted.size}, made canonical ${change.promoted.size}`, + ); + return { canonical }; + }); + } catch (e) { + if (e instanceof TxConflict) { + logger.error( + `SKIPPED_BLOCK_TX_CONFLICT height=${block.height} hash=${block.hash} owners=${ownerSummary(e.owners)}`, + ); + return { canonical: false }; + } + throw e; + } +}; + +/** + * An ordered block is canonical at its height. It replaces the block there + * with that block's linked descendants, and every other canonical holder of + * its txs with theirs; brings back its stored ancestors; asks for the heights + * below it that this leaves empty; and demotes every canonical block above + * `proposedTip`. + */ +export const applyOrderedBlock = ( + incoming: IncomingBlock, + proposedTip: number, + heartbeat: Heartbeat, +): Promise => { + const { height, hash } = incoming.block; + let ceiling = BigInt(proposedTip); + if (ceiling < height) { + logger.warn( + `Ordered block ${height} (${hash}) carries proposed tip ${proposedTip}, below its height; using ${height}`, + ); + ceiling = height; + } + return apply( + incoming, + heartbeat, + { ordered: true }, + async (change, stored) => { + if (!stored.canonical) { + for (const replaced of await canonicalAt(change, height)) { + await demoteLinkedRun(change, replaced, ceiling); + } + } + await demoteHolders(change, incoming.block, ceiling); + if (!stored.canonical) { + await promote(change, stored, { walked: false }); + await reviveAncestors(change, stored); + } + await requestEmptied(change, height); + await demoteAbove(change, ceiling); + return true; + }, + ); +}; + +/** + * A catch-up block fills an empty height below the canonical head, never a + * held one. Linked to the canonical chain above, it carries that chain's + * authority below its height, as an ordered block does: the other holders of + * its txs there go, its stored ancestors come back, and the heights left + * empty are asked for. An already-canonical block with a linked canonical + * child has the same authority. With `finalized` (at or below the serving + * node's own finalized tip), it also joins when the link is undecided and the + * canonical block below, if any, is its parent, asking for that height when + * it is empty. + */ +export const applyCatchupBlock = ( + incoming: IncomingBlock, + finalized: boolean, + heartbeat: Heartbeat, +): Promise => + apply(incoming, heartbeat, { ordered: false }, async (change, stored) => { + if (stored.canonical) { + const children = await canonicalChildren( + change, + [stored], + stored.height + 1n, + ); + if (children.length > 0) { + await demoteHolders(change, incoming.block, stored.height - 1n); + await requestEmptied(change, stored.height); + } + return true; + } + if ((await canonicalAt(change, stored.height)).length > 0) { + return false; + } + const link = await linkFromAbove(change, stored); + if (link === "head") { + return false; + } + if (link === "excludes") { + if (finalized) { + logger.warn( + `CHAIN_LINK_CONFLICT: finalized catch-up block ${stored.height} (${stored.hash}) is not the parent of the canonical chain above it; left off the chain`, + ); + } + return false; + } + if (link !== "undecided") { + await demoteHolders(change, incoming.block, stored.height - 1n); + await promote(change, stored, { walked: false }); + for (const walked of link.walked) { + await promote(change, walked, { walked: true }); + } + await reviveAncestors(change, stored); + await requestEmptied(change, stored.height); + return true; + } + if (!finalized) { + return false; + } + const below = await canonicalAt(change, stored.height - 1n); + if (below.some((b) => b.archiveRoot !== stored.lastArchiveRoot)) { + return false; + } + await promote(change, stored, { walked: false }); + if (below.length === 0 && stored.height > 1n) { + change.repairs.add(stored.height - 1n); + } + return true; + }); diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts b/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts deleted file mode 100644 index 25611428a..000000000 --- a/services/explorer-api/src/svcs/database/controllers/l2block/delete.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { type HexString } from "@chicmoz-pkg/types"; -import { eq, inArray } from "drizzle-orm"; -import { logger } from "../../../../logger.js"; -import { - body, - l2Block, - txEffect, -} from "../../../database/schema/l2block/index.js"; - -export const deleteAllBlocks = async (): Promise => { - const res = (await db().delete(l2Block).execute()).rowCount; - logger.info(`๐Ÿ—‘๏ธ Deleted ${res} blocks`); -}; - -export const deleteL2BlockByHeight = async (height: bigint): Promise => { - await db().delete(l2Block).where(eq(l2Block.height, height)).execute(); -}; - -export const deleteL2BlockByHash = async (hash: HexString): Promise => { - await db().delete(l2Block).where(eq(l2Block.hash, hash)).execute(); -}; - -export type TxEffectOwner = { - txHash: HexString; - blockHash: HexString; - blockHeight: bigint; - rollupVersion: number; - isOrphaned: boolean; -}; - -export const getTxEffectOwners = async ( - txHashes: HexString[], -): Promise => { - if (txHashes.length === 0) { - return []; - } - - const uniqueTxHashes = [...new Set(txHashes)]; - - const owners = await db() - .select({ - txHash: txEffect.txHash, - blockHash: l2Block.hash, - blockHeight: l2Block.height, - rollupVersion: l2Block.version, - orphanTimestamp: l2Block.orphan_timestamp, - }) - .from(txEffect) - .innerJoin(body, eq(txEffect.bodyId, body.id)) - .innerJoin(l2Block, eq(body.blockHash, l2Block.hash)) - .where(inArray(txEffect.txHash, uniqueTxHashes)); - - return owners.map((owner) => ({ - txHash: owner.txHash, - blockHash: owner.blockHash, - blockHeight: owner.blockHeight, - rollupVersion: owner.rollupVersion, - isOrphaned: owner.orphanTimestamp !== null, - })); -}; 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 fb876a309..e9409c19d 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 @@ -6,15 +6,16 @@ import { } from "@chicmoz-pkg/types"; import { and, - count, desc, eq, getTableColumns, isNotNull, isNull, + or, sql, } from "drizzle-orm"; -import { DB_MAX_BLOCKS } from "../../../../environment.js"; +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 { getLatestBlockRollupVersion } from "./get-latest.js"; @@ -387,62 +388,63 @@ export const getOrphanedBlocks = async ( return blocks; }; +type Reorg = { + orphanedBlockHash: HexString; + height: bigint; + timestamp: Date; + nbrOfOrphanedBlocks: number; +}; + /** - * Get information about reorgs - * @returns Array of reorg events with details about orphaned blocks + * Active reorg records, newest first, each shown by its listed blocks still + * off the chain (a block no longer stored counts as off). A block counts + * only for the newest record that lists it, so a block that died again + * shows once. */ -export const getReorgs = async (): Promise< - { - orphanedBlockHash: HexString; - height: bigint; - timestamp: Date; - nbrOfOrphanedBlocks: number; - }[] -> => { - // Get all root orphaned blocks (those with hasOrphanedParent = false) - const rootOrphanedBlocks = await db() +export const getReorgs = async (): Promise => { + const rows = await db() .select({ - hash: l2Block.hash, - height: l2Block.height, - timestamp: l2Block.orphan_timestamp, + id: l2ReorgTable.id, + observedAt: l2ReorgTable.observedAt, + hash: l2ReorgBlockTable.hash, + height: l2ReorgBlockTable.height, }) - .from(l2Block) + .from(l2ReorgTable) + .innerJoin( + l2ReorgBlockTable, + eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id), + ) + .leftJoin(l2Block, eq(l2Block.hash, l2ReorgBlockTable.hash)) .where( and( - isNotNull(l2Block.orphan_timestamp), - eq(l2Block.orphan_hasOrphanedParent, false), + eq(l2ReorgTable.l2NetworkId, L2_NETWORK_ID), + isNull(l2ReorgTable.revivedAt), + or(isNull(l2Block.hash), isNotNull(l2Block.orphan_timestamp)), + sql`NOT EXISTS (SELECT 1 FROM ${l2ReorgBlockTable} AS newer WHERE newer."hash" = ${l2ReorgBlockTable.hash} AND newer."reorg_id" > ${l2ReorgTable.id})`, ), ) - .orderBy(desc(l2Block.orphan_timestamp)) - .execute(); + .orderBy(desc(l2ReorgTable.observedAt), desc(l2ReorgTable.id)); - const result = []; - - // For each root orphaned block, count how many children it has - for (const rootBlock of rootOrphanedBlocks) { - if (!rootBlock.timestamp) { + const reorgs = new Map(); + for (const row of rows) { + const reorg = reorgs.get(row.id); + if (!reorg) { + reorgs.set(row.id, { + orphanedBlockHash: row.hash, + height: row.height, + timestamp: row.observedAt, + nbrOfOrphanedBlocks: 1, + }); continue; } - - // Count orphaned blocks with the same timestamp (these are all part of the same re-org) - const childCount = await db() - .select({ count: count() }) - .from(l2Block) - .where( - and( - eq(l2Block.orphan_timestamp, rootBlock.timestamp), - eq(l2Block.orphan_hasOrphanedParent, true), - ), - ) - .execute(); - - result.push({ - orphanedBlockHash: rootBlock.hash, - height: rootBlock.height, - timestamp: new Date(rootBlock.timestamp), - nbrOfOrphanedBlocks: (childCount[0]?.count || 0) + 1, // +1 for the root block itself - }); + reorg.nbrOfOrphanedBlocks++; + if ( + row.height < reorg.height || + (row.height === reorg.height && row.hash < reorg.orphanedBlockHash) + ) { + reorg.orphanedBlockHash = row.hash; + reorg.height = row.height; + } } - - return result; + return [...reorgs.values()]; }; 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 617992d14..392a31019 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 @@ -92,42 +92,54 @@ const upsertOpenGaps = async ({ resetOnReopen?: boolean; executor?: ReturnType; }) => { - for (const range of ranges) { - const values = { - id: gapId({ ...range, reason }), - l2NetworkId: L2_NETWORK_ID, - fromHeight: range.from, - toHeight: range.to, - reason, - statusHint: range.statusHint, - status: "open" as const, - lastSeenAt: new Date(), - fulfilledAt: null, - lastError: null, - }; - - await executor - .insert(l2OpenGapTable) - .values(values) - .onConflictDoUpdate({ - target: l2OpenGapTable.id, - set: { - status: "open", - lastSeenAt: values.lastSeenAt, - statusHint: values.statusHint, - fulfilledAt: null, - lastError: null, - // A row reopened after being fulfilled is a new gap: its earlier - // requests say nothing about it, so its backoff starts over. - ...(resetOnReopen - ? { - requestCount: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then 0 else ${l2OpenGapTable.requestCount} end`, - lastRequestedAt: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then null else ${l2OpenGapTable.lastRequestedAt} end`, - } - : {}), - }, - }); + const lastSeenAt = new Date(); + // One row per id: a statement cannot update the same row twice. + const rows = [ + ...new Map( + ranges.map((range) => { + const id = gapId({ ...range, reason }); + return [ + id, + { + id, + l2NetworkId: L2_NETWORK_ID, + fromHeight: range.from, + toHeight: range.to, + reason, + statusHint: range.statusHint, + status: "open" as const, + lastSeenAt, + fulfilledAt: null, + lastError: null, + }, + ] as const; + }), + ).values(), + ]; + if (rows.length === 0) { + return; } + await executor + .insert(l2OpenGapTable) + .values(rows) + .onConflictDoUpdate({ + target: l2OpenGapTable.id, + set: { + status: "open", + lastSeenAt, + statusHint: sql`excluded.status_hint`, + fulfilledAt: null, + lastError: null, + // A row reopened after being fulfilled is a new gap: its earlier + // requests say nothing about it, so its backoff starts over. + ...(resetOnReopen + ? { + requestCount: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then 0 else ${l2OpenGapTable.requestCount} end`, + lastRequestedAt: sql`case when ${l2OpenGapTable.status} = 'fulfilled' then null else ${l2OpenGapTable.lastRequestedAt} end`, + } + : {}), + }, + }); }; // Backoff after a gap's Nth request: interval * 2^min(N, 8), capped at 1h. @@ -141,6 +153,49 @@ const MAX_GAP_BACKOFF_MS = 60 * 60 * 1000; // requested first. const CANDIDATE_GAP_LIMIT = 50; const TIP_BOUNDARY_REASON: L2BlockRangeRequestReason = "tip_boundary_mismatch"; +// One height whose block message must come back: the canonical block there +// lacks it, or the height was cleared under a block whose parent is missing. +// Requested whole, present or not, until a block message makes the block at +// that height canonical (fulfilRepairHeight, inside that change). +const REPAIR_REASON: L2BlockRangeRequestReason = "reorg_repair"; + +export const recordRepairHeights = async ( + executor: ReturnType, + heights: Iterable, +) => { + await upsertOpenGaps({ + ranges: [...heights].map((height) => ({ + from: Number(height), + to: Number(height), + statusHint: "proposed" as const, + })), + reason: REPAIR_REASON, + executor, + }); +}; + +/** + * Closes the repair of `height`, in the transaction whose block message made + * the block there canonical. Repair rows carry no rollup version, so any + * version's block at the height closes it. + */ +export const fulfilRepairHeight = async ( + executor: ReturnType, + height: bigint, +) => { + await executor + .update(l2OpenGapTable) + .set({ status: "fulfilled", fulfilledAt: new Date(), lastError: null }) + .where( + and( + eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), + eq(l2OpenGapTable.reason, REPAIR_REASON), + eq(l2OpenGapTable.status, "open"), + eq(l2OpenGapTable.fromHeight, Number(height)), + eq(l2OpenGapTable.toHeight, Number(height)), + ), + ); +}; /** * Whether a gap may be requested again at `now` (epoch ms): never requested, @@ -364,7 +419,7 @@ const selectGapRequest = async ({ const upper = Math.min(gap.toHeight, chainTip); const missing: number[] = []; for (let height = gap.fromHeight; height <= upper; height++) { - if (!present.has(height)) { + if (gap.reason === REPAIR_REASON || !present.has(height)) { missing.push(height); } } @@ -591,6 +646,7 @@ export const markOpenGapsFulfilledByHeight = async (height: bigint) => { and( eq(l2OpenGapTable.l2NetworkId, L2_NETWORK_ID), eq(l2OpenGapTable.status, "open"), + ne(l2OpenGapTable.reason, REPAIR_REASON), lte(l2OpenGapTable.fromHeight, Number(height)), gte(l2OpenGapTable.toHeight, Number(height)), ), diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts b/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts deleted file mode 100644 index 0300889c6..000000000 --- a/services/explorer-api/src/svcs/database/controllers/l2block/orphan.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { HexString } from "@chicmoz-pkg/types"; -import { and, eq, gt, isNull } from "drizzle-orm"; -import { logger } from "../../../../logger.js"; -import { - body, - l2Block, - txEffect, -} from "../../../database/schema/l2block/index.js"; -import { storeDroppedTx } from "../../controllers/dropped-tx/store.js"; - -/** - * Mark a block as orphaned with the specified parent status - */ -export const markBlockAsOrphaned = async ( - blockHash: HexString, - timestamp: number, - hasOrphanedParent: boolean, -): Promise => { - logger.info( - `Marking block ${blockHash} as orphaned. hasOrphanedParent: ${hasOrphanedParent}`, - ); - - await db() - .update(l2Block) - .set({ - orphan_timestamp: timestamp, - orphan_hasOrphanedParent: hasOrphanedParent, - }) - .where(eq(l2Block.hash, blockHash)); -}; - -/** - * Mark all blocks with height > targetHeight and orphan_timestamp === null as orphaned - * @returns The number of blocks that were marked as orphaned - */ -export const markHigherBlocksAsOrphaned = async ( - targetHeight: bigint, - timestamp: number, -): Promise => { - logger.info( - `Marking all blocks with height > ${targetHeight} as orphaned with parent`, - ); - - // Find all blocks with higher height that aren't already orphaned - const higherBlocks = await db() - .select({ hash: l2Block.hash }) - .from(l2Block) - .where( - and(gt(l2Block.height, targetHeight), isNull(l2Block.orphan_timestamp)), - ); - - const orphanedCount = higherBlocks.length; - - // Mark them all as orphaned with hasOrphanedParent=true - for (const block of higherBlocks) { - await markBlockAsOrphaned(block.hash, timestamp, true); - } - - logger.info(`Marked ${orphanedCount} child blocks as orphaned`); - return orphanedCount; -}; - -/** - * Handle a re-org by marking the specified block and all higher blocks of its - * rollup version as orphaned - * Uses a transaction to ensure all operations are atomic - * - * @param originalBlockHash The hash of the block being replaced (original block at the height) - * @param targetHeight The height at which the re-org occurred - * @param rollupVersion The rollup version of the re-orged chain; other versions' chains are left as they are - * @returns The number of total blocks orphaned (including the original) - */ -export const handleReorgOrphaning = async ( - originalBlockHash: HexString, - targetHeight: bigint, - rollupVersion: number, -): Promise => { - const now = new Date().getTime(); - - return await db().transaction(async (dbTx) => { - logger.info( - `Starting orphan transaction for re-org at height ${targetHeight}`, - ); - - // 1. Mark the original block as orphaned (root of orphaned chain) - await dbTx - .update(l2Block) - .set({ - orphan_timestamp: now, - orphan_hasOrphanedParent: false, - }) - .where(eq(l2Block.hash, originalBlockHash)); - - // Find transaction effects in the orphaned block and store them as dropped - await storeOrphanedTxEffectsAsDropped(dbTx, originalBlockHash, now); - - // 2. Find and mark all higher blocks as orphaned with parent - const higherBlocks = await dbTx - .select({ hash: l2Block.hash }) - .from(l2Block) - .where( - and( - gt(l2Block.height, targetHeight), - eq(l2Block.version, rollupVersion), - isNull(l2Block.orphan_timestamp), - ), - ); - - const orphanedChildrenCount = higherBlocks.length; - - // Mark all children as orphaned with parent=true - for (const block of higherBlocks) { - await dbTx - .update(l2Block) - .set({ - orphan_timestamp: now, - orphan_hasOrphanedParent: true, - }) - .where(eq(l2Block.hash, block.hash)); - - // Store transaction effects from this block as dropped - await storeOrphanedTxEffectsAsDropped(dbTx, block.hash, now); - } - - const totalOrphaned = orphanedChildrenCount + 1; // +1 for the original block - logger.info( - `Completed orphan transaction. Total orphaned: ${totalOrphaned} (1 root + ${orphanedChildrenCount} children)`, - ); - - return totalOrphaned; - }); -}; - -/** - * Un-orphan a block by clearing its orphan_timestamp and orphan_hasOrphanedParent fields. - * This is used when we receive a block with the same hash as an already-orphaned block, - * meaning the orphaned block is actually the canonical one. - */ -export const unOrphanBlock = async (blockHash: HexString): Promise => { - logger.info(`Un-orphaning block ${blockHash}`); - await db() - .update(l2Block) - .set({ - orphan_timestamp: null, - orphan_hasOrphanedParent: false, - }) - .where(eq(l2Block.hash, blockHash)); -}; - -type DB = ReturnType; -type DBTransactionFunction = DB["transaction"]; -type DBTransactionFunctionCallback = Parameters[0]; -type DBTransactionFunctionCallbackParameter = - Parameters[0]; - -/** - * Find transaction effects in an orphaned block and store them as dropped transactions - */ -const storeOrphanedTxEffectsAsDropped = async ( - dbTx: DBTransactionFunctionCallbackParameter, - blockHash: HexString, - timestamp: number, -): Promise => { - // Find the body ID for this block - const blockBody = await dbTx - .select({ id: body.id }) - .from(body) - .where(eq(body.blockHash, blockHash)) - .limit(1); - - if (blockBody.length === 0) { - logger.warn(`No body found for orphaned block ${blockHash}`); - return; - } - - const bodyId = blockBody[0].id; - - // Find all transaction effects in this body - const txEffects = await dbTx - .select({ - txHash: txEffect.txHash, - txBirthTimestamp: txEffect.txBirthTimestamp, - }) - .from(txEffect) - .where(eq(txEffect.bodyId, bodyId)); - - if (txEffects.length === 0) { - logger.info(`No transaction effects found in orphaned block ${blockHash}`); - return; - } - - logger.info( - `Found ${txEffects.length} transaction effects to mark as dropped in block ${blockHash}`, - ); - - // Store each transaction effect as a dropped transaction - for (const tx of txEffects) { - try { - await storeDroppedTx({ - txHash: tx.txHash, - createdAsPendingAt: tx.txBirthTimestamp, - droppedAt: timestamp, - // Block was reorged out โ€” tx returns to dropped-state with this - // reason so the UI can show "(reorg)" rather than just a timestamp. - dropReason: "orphaned", - }); - } catch (error) { - const errorMessage = - error instanceof Error ? error.message : String(error); - logger.error( - `Failed to store dropped transaction ${tx.txHash}: ${errorMessage}`, - ); - } - } -}; diff --git a/services/explorer-api/src/svcs/database/controllers/l2block/store.ts b/services/explorer-api/src/svcs/database/controllers/l2block/store.ts index d76af4768..f1fa83e87 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2block/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2block/store.ts @@ -1,5 +1,9 @@ -import { getDb as db } from "@chicmoz-pkg/postgres-helper"; -import { HexString, type ChicmozL2Block } from "@chicmoz-pkg/types"; +import { + type ChicmozL2Block, + type ChicmozL2TxEffect, + type HexString, +} from "@chicmoz-pkg/types"; +import { eq } from "drizzle-orm"; import { randomUUID } from "node:crypto"; import { archive, @@ -18,157 +22,170 @@ import { state, txEffect, } from "../../../database/schema/l2block/index.js"; +import { type DbTx } from "../utils.js"; -export const store = async (block: ChicmozL2Block): Promise => { - return await db().transaction(async (dbTx) => { - // Insert l2Block - await dbTx.insert(l2Block).values({ - hash: block.hash, - height: BigInt(block.header.globalVariables.blockNumber), - version: block.header.globalVariables.version, - orphan_timestamp: block.orphan?.timestamp ?? null, - orphan_hasOrphanedParent: block.orphan?.hasOrphanedParent ?? false, - }); - - const headerId = randomUUID(); - // Insert header - await dbTx.insert(header).values({ - id: headerId, - blockHash: block.hash, - totalFees: block.header.totalFees.toString(), - totalManaUsed: block.header.totalManaUsed.toString(), - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - spongeBlobHash: block.header.spongeBlobHash, - }); - - // Insert archive - await dbTx.insert(archive).values({ - root: block.archive.root, - nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, - fk: block.hash, - }); +/** + * Inserts every row of a block except its tx effects, off the chain since + * `orphanTimestamp`: the caller decides its status and attaches its effects. + * Returns the body id. + */ +export const store = async ( + dbTx: DbTx, + block: ChicmozL2Block, + orphanTimestamp: number, +): Promise => { + await dbTx.insert(l2Block).values({ + hash: block.hash, + height: BigInt(block.header.globalVariables.blockNumber), + version: block.header.globalVariables.version, + orphan_timestamp: orphanTimestamp, + orphan_hasOrphanedParent: false, + }); - const lastArchiveId = randomUUID(); - // Insert last archive - await dbTx.insert(lastArchive).values({ - id: lastArchiveId, - root: block.header.lastArchive.root, - nextAvailableLeafIndex: block.header.lastArchive.nextAvailableLeafIndex, - fk: headerId, - }); + const headerId = randomUUID(); + await dbTx.insert(header).values({ + id: headerId, + blockHash: block.hash, + totalFees: block.header.totalFees.toString(), + totalManaUsed: block.header.totalManaUsed.toString(), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + spongeBlobHash: block.header.spongeBlobHash, + }); - const stateId = randomUUID(); - // Insert state - await dbTx.insert(state).values({ - id: stateId, - headerId, - }); + await dbTx.insert(archive).values({ + root: block.archive.root, + nextAvailableLeafIndex: block.archive.nextAvailableLeafIndex, + fk: block.hash, + }); - const l1ToL2MessageTreeId = randomUUID(); - // Insert l1ToL2MessageTree - await dbTx.insert(l1ToL2MessageTree).values({ - id: l1ToL2MessageTreeId, - root: block.header.state.l1ToL2MessageTree.root, - nextAvailableLeafIndex: - block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex, - fk: stateId, - }); + await dbTx.insert(lastArchive).values({ + id: randomUUID(), + root: block.header.lastArchive.root, + nextAvailableLeafIndex: block.header.lastArchive.nextAvailableLeafIndex, + fk: headerId, + }); - const partialId = randomUUID(); - // Insert partial - await dbTx.insert(partial).values({ - id: partialId, - stateId, - }); + const stateId = randomUUID(); + await dbTx.insert(state).values({ + id: stateId, + headerId, + }); - const noteHashTreeId = randomUUID(); - // Insert partial state trees - await dbTx.insert(noteHashTree).values({ - id: noteHashTreeId, - root: block.header.state.partial.noteHashTree.root, - nextAvailableLeafIndex: - block.header.state.partial.noteHashTree.nextAvailableLeafIndex, - fk: partialId, - }); + await dbTx.insert(l1ToL2MessageTree).values({ + id: randomUUID(), + root: block.header.state.l1ToL2MessageTree.root, + nextAvailableLeafIndex: + block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex, + fk: stateId, + }); - const nullifierTreeId = randomUUID(); - await dbTx.insert(nullifierTree).values({ - id: nullifierTreeId, - root: block.header.state.partial.nullifierTree.root, - nextAvailableLeafIndex: - block.header.state.partial.nullifierTree.nextAvailableLeafIndex, - fk: partialId, - }); + const partialId = randomUUID(); + await dbTx.insert(partial).values({ + id: partialId, + stateId, + }); - const publicDataTreeId = randomUUID(); - await dbTx.insert(publicDataTree).values({ - id: publicDataTreeId, - root: block.header.state.partial.publicDataTree.root, - nextAvailableLeafIndex: - block.header.state.partial.publicDataTree.nextAvailableLeafIndex, - fk: partialId, - }); + await dbTx.insert(noteHashTree).values({ + id: randomUUID(), + root: block.header.state.partial.noteHashTree.root, + nextAvailableLeafIndex: + block.header.state.partial.noteHashTree.nextAvailableLeafIndex, + fk: partialId, + }); - const globalVariablesId = randomUUID(); - // Insert global variables - await dbTx.insert(globalVariables).values({ - id: globalVariablesId, - headerId, - chainId: block.header.globalVariables.chainId, - version: block.header.globalVariables.version, - blockNumber: block.header.globalVariables.blockNumber, - slotNumber: block.header.globalVariables.slotNumber, - timestamp: block.header.globalVariables.timestamp, - coinbase: block.header.globalVariables.coinbase, - feeRecipient: block.header.globalVariables.feeRecipient, - }); + await dbTx.insert(nullifierTree).values({ + id: randomUUID(), + root: block.header.state.partial.nullifierTree.root, + nextAvailableLeafIndex: + block.header.state.partial.nullifierTree.nextAvailableLeafIndex, + fk: partialId, + }); - const gasFeesId = randomUUID(); - // Insert gas fees - await dbTx.insert(gasFees).values({ - id: gasFeesId, - globalVariablesId, - feePerDaGas: block.header.globalVariables.gasFees.feePerDaGas, - feePerL2Gas: block.header.globalVariables.gasFees.feePerL2Gas, - }); + await dbTx.insert(publicDataTree).values({ + id: randomUUID(), + root: block.header.state.partial.publicDataTree.root, + nextAvailableLeafIndex: + block.header.state.partial.publicDataTree.nextAvailableLeafIndex, + fk: partialId, + }); - const bodyId = randomUUID(); - // Insert body - await dbTx.insert(body).values({ - id: bodyId, - blockHash: block.hash, - }); + const globalVariablesId = randomUUID(); + await dbTx.insert(globalVariables).values({ + id: globalVariablesId, + headerId, + chainId: block.header.globalVariables.chainId, + version: block.header.globalVariables.version, + blockNumber: block.header.globalVariables.blockNumber, + slotNumber: block.header.globalVariables.slotNumber, + timestamp: block.header.globalVariables.timestamp, + coinbase: block.header.globalVariables.coinbase, + feeRecipient: block.header.globalVariables.feeRecipient, + }); - // Insert txEffects and create junction entries - for (const [i, txEff] of Object.entries(block.body.txEffects)) { - if (isNaN(Number(i))) { - throw new Error("Invalid txEffect index"); - } - await dbTx.insert(txEffect).values({ - txHash: txEff.txHash, - bodyId, - index: Number(i), - revertCode: txEff.revertCode.code, - transactionFee: txEff.transactionFee, - noteHashes: txEff.noteHashes as HexString[], - nullifiers: txEff.nullifiers as HexString[], - l2ToL1Msgs: txEff.l2ToL1Msgs as HexString[], - privateLogs: txEff.privateLogs, - publicLogs: txEff.publicLogs, - contractClassLogs: txEff.contractClassLogs, - }); + await dbTx.insert(gasFees).values({ + id: randomUUID(), + globalVariablesId, + feePerDaGas: block.header.globalVariables.gasFees.feePerDaGas, + feePerL2Gas: block.header.globalVariables.gasFees.feePerL2Gas, + }); - // Insert public data writes - for (const [pdwIndex, pdw] of Object.entries(txEff.publicDataWrites)) { - const publicDataWriteId = randomUUID(); - await dbTx.insert(publicDataWrite).values({ - id: publicDataWriteId, - txEffectHash: txEff.txHash, - index: Number(pdwIndex), - leafSlot: pdw.leafSlot, - value: pdw.value, - }); - } - } + const bodyId = randomUUID(); + await dbTx.insert(body).values({ + id: bodyId, + blockHash: block.hash, }); + return bodyId; +}; + +/** + * Writes a tx effect into a body: inserted when no block holds it, otherwise + * moved from its holder. A moved effect keeps its birth time and the fields + * copied from its pending tx. + */ +export const writeTxEffect = async ( + dbTx: DbTx, + { + bodyId, + index, + effect, + held, + }: { + bodyId: string; + index: number; + effect: ChicmozL2TxEffect; + held: boolean; + }, +): Promise => { + const content = { + bodyId, + index, + revertCode: effect.revertCode.code, + transactionFee: effect.transactionFee, + noteHashes: effect.noteHashes as HexString[], + nullifiers: effect.nullifiers as HexString[], + l2ToL1Msgs: effect.l2ToL1Msgs as HexString[], + privateLogs: effect.privateLogs, + publicLogs: effect.publicLogs, + contractClassLogs: effect.contractClassLogs, + }; + if (held) { + await dbTx + .update(txEffect) + .set(content) + .where(eq(txEffect.txHash, effect.txHash)); + await dbTx + .delete(publicDataWrite) + .where(eq(publicDataWrite.txEffectHash, effect.txHash)); + } else { + await dbTx.insert(txEffect).values({ txHash: effect.txHash, ...content }); + } + for (const [pdwIndex, pdw] of effect.publicDataWrites.entries()) { + await dbTx.insert(publicDataWrite).values({ + id: randomUUID(), + txEffectHash: effect.txHash, + index: pdwIndex, + leafSlot: pdw.leafSlot, + value: pdw.value, + }); + } }; 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 e74277e44..348f452c4 100644 --- a/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts +++ b/services/explorer-api/src/svcs/database/controllers/l2contract/store.ts @@ -1,3 +1,4 @@ +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; import { getDb as db } from "@chicmoz-pkg/postgres-helper"; import { ChicmozL2ContractInstanceUpdatedEvent, @@ -23,22 +24,23 @@ import { selectorMapValueToFunctionName, } from "../../../../utils/resolve-artifact-names.js"; import { logger } from "../../../../logger.js"; +import { type DbTx } from "../utils.js"; export const storeContractInstanceDeployed = async ( instance: ChicmozL2ContractInstanceDeployedEvent, + executor: ReturnType = db(), ): Promise => { const { publicKeys, ...rest } = instance; - await db() + await executor .insert(l2ContractInstanceDeployed) .values({ ...publicKeys, ...rest }); }; export const storeContractInstanceUpdated = async ( instance: ChicmozL2ContractInstanceUpdatedEvent, + executor: ReturnType = db(), ): Promise => { - await db() - .insert(l2ContractInstanceUpdate) - .values({ ...instance }); + await executor.insert(l2ContractInstanceUpdate).values({ ...instance }); }; export const storeContractInstanceVerifiedDeploymentArguments = async ( @@ -60,12 +62,65 @@ export const storeContractInstanceVerifiedDeploymentArguments = async ( export const storeContractClass = async ( contractClass: ChicmozL2ContractClassRegisteredEvent, + executor: ReturnType = db(), ): Promise => { - await db() - .insert(l2ContractClassRegistered) - .values({ - ...contractClass, - }); + await executor.insert(l2ContractClassRegistered).values({ + ...contractClass, + }); +}; + +export type BlockContracts = { + classes: ChicmozL2ContractClassRegisteredEvent[]; + instancesDeployed: ChicmozL2ContractInstanceDeployedEvent[]; + instancesUpdated: ChicmozL2ContractInstanceUpdatedEvent[]; +}; + +/** + * 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. + */ +export const storeBlockContracts = async ( + dbTx: DbTx, + { classes, instancesDeployed, instancesUpdated }: BlockContracts, + heartbeat: Heartbeat, +): Promise => { + const each = async ( + rows: T[], + label: (row: T) => string, + 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)}`, + ); + } + } + } + }; + await each( + classes, + (c) => `contractClass ${c.contractClassId}`, + storeContractClass, + ); + await each( + instancesDeployed, + (i) => `contractInstanceDeployed ${i.address}`, + storeContractInstanceDeployed, + ); + await each( + instancesUpdated, + (i) => `contractInstanceUpdated ${i.address}`, + storeContractInstanceUpdated, + ); }; export const addArtifactData = async ({ diff --git a/services/explorer-api/src/svcs/database/controllers/utils.ts b/services/explorer-api/src/svcs/database/controllers/utils.ts index b6753e788..c077a907b 100644 --- a/services/explorer-api/src/svcs/database/controllers/utils.ts +++ b/services/explorer-api/src/svcs/database/controllers/utils.ts @@ -1,10 +1,15 @@ import { BadRequestError } from "@chicmoz-pkg/error-middleware"; +import { type getDb } from "@chicmoz-pkg/postgres-helper"; import { Table, and, getTableColumns, gte, lt } from "drizzle-orm"; import { ZodError } from "zod"; import { DB_MAX_BLOCKS } from "../../../environment.js"; import { logger } from "../../../logger.js"; import { l2Block } from "../schema/index.js"; +export type DbTx = Parameters< + Parameters["transaction"]>[0] +>[0]; + export const dbParseErrorCallback = (e: unknown) => { if (e instanceof ZodError) { const newError = new Error("Internal server error (DB)"); diff --git a/services/explorer-api/src/svcs/database/schema/index.ts b/services/explorer-api/src/svcs/database/schema/index.ts index 52405039d..21369dfc6 100644 --- a/services/explorer-api/src/svcs/database/schema/index.ts +++ b/services/explorer-api/src/svcs/database/schema/index.ts @@ -5,6 +5,7 @@ export * from "./dropped-tx/index.js"; export * from "./l2/chain-info.js"; export * from "./l2/rollup-version-observation.js"; export * from "./l2/open-gap.js"; +export * from "./l2/reorg.js"; export * from "./l2/tips.js"; export * from "./l2block/index.js"; export * from "./l2contract/index.js"; diff --git a/services/explorer-api/src/svcs/database/schema/l2/reorg.ts b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts new file mode 100644 index 000000000..5d3107b01 --- /dev/null +++ b/services/explorer-api/src/svcs/database/schema/l2/reorg.ts @@ -0,0 +1,60 @@ +import { HexString, L2NetworkId } from "@chicmoz-pkg/types"; +import { + bigint, + index, + pgTable, + primaryKey, + timestamp, + varchar, +} from "drizzle-orm/pg-core"; +import { generateBoundedIntegerColumn, l2NetworkIdDbEnum } from "../utils.js"; + +/** The stream the block whose application wrote a reorg record came on. */ +export type ReorgCauseKind = "ordered" | "catchup"; + +/** + * One row per applied block, ordered or catch-up, that demoted canonical + * blocks: what the explorer had as canonical and removed, not the node's + * prune depth. `cause_hash` is that block's hash. `revived_at` is the only + * later write, set once every listed block is canonical again. + */ +export const l2ReorgTable = pgTable( + "l2_reorg", + { + id: bigint("id", { mode: "number" }) + .primaryKey() + .generatedAlwaysAsIdentity(), + l2NetworkId: l2NetworkIdDbEnum("l2_network_id") + .notNull() + .$type(), + rollupVersion: generateBoundedIntegerColumn("rollup_version").notNull(), + causeHash: varchar("cause_hash").notNull().$type(), + causeKind: varchar("cause_kind").notNull().$type(), + observedAt: timestamp("observed_at").notNull(), + revivedAt: timestamp("revived_at"), + }, + (t) => ({ + networkObservedIdx: index("l2_reorg_network_observed_idx").on( + t.l2NetworkId, + t.observedAt.desc(), + ), + }), +); + +export const l2ReorgBlockTable = pgTable( + "l2_reorg_block", + { + reorgId: bigint("reorg_id", { mode: "number" }) + .notNull() + .references(() => l2ReorgTable.id, { onDelete: "cascade" }), + height: bigint("height", { mode: "bigint" }).notNull(), + hash: varchar("hash").notNull().$type(), + }, + (t) => ({ + pk: primaryKey({ + name: "l2_reorg_block_pkey", + columns: [t.reorgId, t.hash], + }), + hashIdx: index("l2_reorg_block_hash_idx").on(t.hash), + }), +); diff --git a/services/explorer-api/src/svcs/database/schema/l2/tips.ts b/services/explorer-api/src/svcs/database/schema/l2/tips.ts index d0f041d2e..3d9254a79 100644 --- a/services/explorer-api/src/svcs/database/schema/l2/tips.ts +++ b/services/explorer-api/src/svcs/database/schema/l2/tips.ts @@ -1,6 +1,15 @@ import { ChicmozL2Tips, HexString, L2NetworkId } from "@chicmoz-pkg/types"; -import { bigint, integer, pgTable, timestamp, uniqueIndex, varchar } from "drizzle-orm/pg-core"; -import { l2NetworkIdDbEnum } from "../utils.js"; +import { sql } from "drizzle-orm"; +import { + bigint, + index, + integer, + pgTable, + timestamp, + uniqueIndex, + varchar, +} from "drizzle-orm/pg-core"; +import { generateBoundedIntegerColumn, l2NetworkIdDbEnum } from "../utils.js"; const blockNumber = (name: string) => bigint(name, { mode: "number" }); @@ -63,6 +72,7 @@ export const l2TipBoundaryMismatchTable = pgTable( lastSeenAt: timestamp("last_seen_at").notNull().defaultNow(), occurrenceCount: integer("occurrence_count").notNull().default(1), resolvedAt: timestamp("resolved_at"), + rollupVersion: generateBoundedIntegerColumn("rollup_version"), }, (table) => ({ l2TipBoundaryMismatchKey: uniqueIndex("l2_tip_boundary_mismatch_key").on( @@ -72,6 +82,9 @@ export const l2TipBoundaryMismatchTable = pgTable( table.expectedHash, table.observedDbHash, ), + unresolvedIdx: index("l2_tip_boundary_mismatch_unresolved_idx") + .on(table.l2NetworkId, table.height) + .where(sql`${table.resolvedAt} IS NULL`), }), ); diff --git a/services/explorer-api/src/svcs/database/schema/l2block/header.ts b/services/explorer-api/src/svcs/database/schema/l2block/header.ts index 6eefb1938..3dac1cda4 100644 --- a/services/explorer-api/src/svcs/database/schema/l2block/header.ts +++ b/services/explorer-api/src/svcs/database/schema/l2block/header.ts @@ -35,6 +35,7 @@ export const lastArchive = generateTreeTable( .notNull() .references(() => header.id, { onDelete: "cascade" }), "last_archive_header_id_idx", + "last_archive_root_idx", ); export const state = pgTable( diff --git a/services/explorer-api/src/svcs/database/schema/l2block/root.ts b/services/explorer-api/src/svcs/database/schema/l2block/root.ts index 53754ae35..4fa4045d7 100644 --- a/services/explorer-api/src/svcs/database/schema/l2block/root.ts +++ b/services/explorer-api/src/svcs/database/schema/l2block/root.ts @@ -1,5 +1,12 @@ import { HexString } from "@chicmoz-pkg/types"; -import { bigint, boolean, index, pgTable, varchar } from "drizzle-orm/pg-core"; +import { + bigint, + boolean, + index, + pgTable, + uniqueIndex, + varchar, +} from "drizzle-orm/pg-core"; import { sql } from "drizzle-orm"; import { @@ -31,6 +38,13 @@ export const l2Block = pgTable( t.height, t.orphan_timestamp, ), + // A chain change demotes a height's canonical block before it promotes + // another there; a statement that would leave two fails the change. + oneCanonicalPerHeightIdx: uniqueIndex( + "l2block_one_canonical_per_height_idx", + ) + .on(t.version, t.height) + .where(sql`${t.orphan_timestamp} IS NULL`), }), ); @@ -40,4 +54,5 @@ export const archive = generateTreeTable( .notNull() .references(() => l2Block.hash, { onDelete: "cascade" }), "archive_block_hash_idx", + "archive_root_idx", ); diff --git a/services/explorer-api/src/svcs/database/schema/utils.ts b/services/explorer-api/src/svcs/database/schema/utils.ts index 874f7386d..a5007db76 100644 --- a/services/explorer-api/src/svcs/database/schema/utils.ts +++ b/services/explorer-api/src/svcs/database/schema/utils.ts @@ -39,6 +39,7 @@ export const generateTreeTable = ( object >, indexName?: string, + rootIndexName?: string, ) => pgTable( name, @@ -52,6 +53,9 @@ export const generateTreeTable = ( ...(indexName ? { fkIdx: index(indexName).on(table.fk) } : {}), + ...(rootIndexName + ? { rootIdx: index(rootIndexName).on(table.root) } + : {}), }), ); diff --git a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts index 50314f620..0f1e8f38b 100644 --- a/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts +++ b/services/explorer-api/src/svcs/http-server/routes/controllers/utils/open-api-responses.ts @@ -245,10 +245,13 @@ export const l1L2ValidatorHistoryResponse = getResponse( "l1L2ValidatorHistory", ); -// Clean BigInt fields in Reorg schema -const cleanedReorgSchema = chicmozReorgSchema.extend({ - height: z.string(), // Convert height from BigInt to string -}); +// Clean BigInt fields in Reorg schema. `.extend()` returns a schema without +// the record's description, so it is carried over. +const cleanedReorgSchema = chicmozReorgSchema + .extend({ + height: z.string(), // Convert height from BigInt to string + }) + .meta(chicmozReorgSchema.meta() ?? {}); export const reorgResponse = getResponse(cleanedReorgSchema, "reorg"); export const reorgResponseArray = getResponse( z.array(cleanedReorgSchema), diff --git a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap index 6d48a486c..493331a5c 100644 --- a/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap +++ b/services/explorer-api/tests/characterization/__snapshots__/open-api-spec.json.snap @@ -8384,16 +8384,20 @@ "application/json": { "schema": { "items": { + "description": "One chain change that orphaned canonical blocks. Its count and lowest block cover only the blocks still orphaned, and the record disappears once all its blocks are back on the chain.", "properties": { "height": { "type": "string" }, "nbrOfOrphanedBlocks": { + "description": "How many of the record's blocks are still orphaned.", "maximum": 9007199254740991, "minimum": 0, "type": "integer" }, - "orphanedBlockHash": {}, + "orphanedBlockHash": { + "description": "The lowest of the record's blocks that are still orphaned." + }, "timestamp": { "format": "date-time", "type": "string" 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 3bdccdd74..82dae0d91 100644 --- a/services/explorer-api/tests/integration/block-ingest.integration.test.ts +++ b/services/explorer-api/tests/integration/block-ingest.integration.test.ts @@ -8,10 +8,11 @@ import { // Local-network blocks only: one database serves one rollup version. Hashes, // archives and tx hashes are the node's RPC fields; class ids and instance // addresses were decoded from logs and confirmed by node lookups. Delivered -// by height, as a deployment needs its class stored first. +// by height as one ordered pass: a deployment needs its class stored first. const recorded = listFixtures("local-network", "l2-block") .map((name) => loadFixture("local-network", "l2-block", name).data) .sort((a, b) => a.expected.height - b.expected.height); +const proposedTip = Math.max(...recorded.map(({ expected }) => expected.height)); describe("recorded blocks through the block handler", () => { let api: ExplorerApiForTest; @@ -26,6 +27,7 @@ describe("recorded blocks through the block handler", () => { block: hex, blockNumber: expected.height, statusHint: "proposed", + ordered: { proposedTip }, }); } }); 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 1350228fd..5e5bd9bc4 100644 --- a/services/explorer-api/tests/integration/block-reorg.integration.test.ts +++ b/services/explorer-api/tests/integration/block-reorg.integration.test.ts @@ -1,124 +1,100 @@ -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 } from "./support/blocks.js"; +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"; -// A tx hash is a primary key across the database, and a reorg orphans every -// active block of its rollup version above its height, so the cases use -// disjoint txs and ascending, disjoint heights, in file order. +// A tx hash is a primary key across the database, and an ordered block +// demotes every canonical block of its rollup version above its tip, so the +// cases use disjoint txs and ascending, disjoint heights, in file order. describe("block conflicts on a real database", () => { let api: ExplorerApiForTest; let store: (b: BuiltBlock) => Promise; - let canonicalHash: (height: bigint) => Promise; - let orphanOf: ( - hash: HexString, - ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; - let owners: (txHash: HexString) => Promise<{ blockHash: HexString; isOrphaned: boolean }[]>; + let reads: Awaited>; beforeAll(async () => { api = await startExplorerApiForTest(); const { blockHandler } = await import( "../../src/events/received/on-block/index.js" ); - // Controllers, not routes: route reads are cached for a minute. - const { getBlock } = await import( - "../../src/svcs/database/controllers/l2block/get-block.js" - ); - const { getTxEffectOwners } = await import( - "../../src/svcs/database/controllers/l2block/delete.js" - ); - store = (b) => - deliver(blockHandler, { - block: b.hex, - blockNumber: Number(b.height), - statusHint: "proposed", - }); - canonicalHash = async (height) => (await getBlock(height))?.hash; - orphanOf = async (hash) => { - const block = await getBlock(hash); - if (!block) { - return "absent"; - } - return block.orphan - ? { hasOrphanedParent: block.orphan.hasOrphanedParent } - : "active"; - }; - owners = async (txHash) => - (await getTxEffectOwners([txHash])).map((o) => ({ - blockHash: o.blockHash, - isOrphaned: o.isOrphaned, - })); + reads = await loadChainReads(); + store = (b) => deliver(blockHandler, orderedEvent(b)); }); afterAll(async () => { await api?.close(); }); - it("skips a block whose tx an active block below holds, and keeps the block at its height", async () => { + it("skips a block whose tx its canonical parent holds, and keeps the block at its height", async () => { const t = freshTxHash(); const below = await buildBlock(100n, [t]); - const current = await buildBlock(101n, [freshTxHash()]); - const incoming = await buildBlock(101n, [t]); - expect(incoming.hash).not.toBe(current.hash); + const current = await buildBlock(101n, [freshTxHash()], { parent: below }); + const incoming = await buildBlock(101n, [t], { parent: below }); await store(below); await store(current); await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(101n)).toBe(current.hash); - expect(await orphanOf(incoming.hash)).toBe("absent"); - expect(await owners(t)).toEqual([{ blockHash: below.hash, isOrphaned: false }]); - - await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(101n)).toBe(current.hash); + expect(await reads.stateOf(current.hash)).toBe("canonical"); + expect(await reads.stateOf(incoming.hash)).toBe("absent"); + expect(await reads.ownerOf(t)).toBe(below.hash); }); - it("stores a reorg block that reuses the replaced block's tx, deleting the replaced block", async () => { + it("moves a tx the replacing block includes again, and keeps the replaced block", async () => { const t = freshTxHash(); const replaced = await buildBlock(200n, [t]); const incoming = await buildBlock(200n, [t]); - expect(incoming.hash).not.toBe(replaced.hash); await store(replaced); - expect(await owners(t)).toEqual([{ blockHash: replaced.hash, isOrphaned: false }]); - await expect(store(incoming)).resolves.toBeUndefined(); - expect(await canonicalHash(200n)).toBe(incoming.hash); - expect(await orphanOf(replaced.hash)).toBe("absent"); - expect(await owners(t)).toEqual([{ blockHash: incoming.hash, isOrphaned: false }]); + await store(incoming); + expect(await reads.stateOf(incoming.hash)).toBe("canonical"); + expect(await reads.stateOf(replaced.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.ownerOf(t)).toBe(incoming.hash); + expect(await reads.isDropped(t)).toBe(false); }); - it("resolves a two-block reorg, then the redelivery of its second block", async () => { + it("records a two-block reorg once, then resolves the redelivery of its second block", async () => { const t2 = freshTxHash(); const old300 = await buildBlock(300n, [freshTxHash()]); - const old301 = await buildBlock(301n, [t2]); + const old301 = await buildBlock(301n, [t2], { parent: old300 }); const new300 = await buildBlock(300n, [freshTxHash()]); - const new301 = await buildBlock(301n, [t2]); - expect(new300.hash).not.toBe(old300.hash); - expect(new301.hash).not.toBe(old301.hash); + const new301 = await buildBlock(301n, [t2], { parent: new300 }); await store(old300); await store(old301); - await expect(store(new300)).resolves.toBeUndefined(); - expect(await canonicalHash(300n)).toBe(new300.hash); - expect(await canonicalHash(301n)).toBeUndefined(); - expect(await orphanOf(old300.hash)).toEqual({ hasOrphanedParent: false }); - expect(await orphanOf(old301.hash)).toEqual({ hasOrphanedParent: true }); - expect(await owners(t2)).toEqual([{ blockHash: old301.hash, isOrphaned: true }]); + await store(new300); + expect(await reads.stateOf(new300.hash)).toBe("canonical"); + expect(await reads.stateOf(old300.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.stateOf(old301.hash)).toEqual({ + hasOrphanedParent: true, + }); + expect(await reads.ownerOf(t2)).toBe(old301.hash); - await expect(store(new301)).resolves.toBeUndefined(); + await store(new301); const settled = async () => { - expect(await canonicalHash(300n)).toBe(new300.hash); - expect(await canonicalHash(301n)).toBe(new301.hash); - expect(await orphanOf(old301.hash)).toBe("absent"); - expect(await orphanOf(old300.hash)).toEqual({ hasOrphanedParent: false }); - expect(await owners(t2)).toEqual([{ blockHash: new301.hash, isOrphaned: false }]); + expect(await reads.stateOf(new301.hash)).toBe("canonical"); + expect(await reads.stateOf(old301.hash)).toEqual({ + hasOrphanedParent: true, + }); + expect(await reads.ownerOf(t2)).toBe(new301.hash); + expect(await reads.listed([old300, old301])).toEqual([ + { orphanedBlockHash: old300.hash, height: 300n, nbrOfOrphanedBlocks: 2 }, + ]); }; await settled(); - await expect(store(new301)).resolves.toBeUndefined(); + await store(new301); await settled(); }); }); diff --git a/services/explorer-api/tests/integration/chain-head.integration.test.ts b/services/explorer-api/tests/integration/chain-head.integration.test.ts new file mode 100644 index 000000000..912905fc9 --- /dev/null +++ b/services/explorer-api/tests/integration/chain-head.integration.test.ts @@ -0,0 +1,1113 @@ +import { TreeLeafIndex } from "@aztec-labs/foundation/branded-types"; +import { Fr } from "@aztec-labs/foundation/curves/bn254"; +import { AppendOnlyTreeSnapshot } from "@aztec-labs/stdlib/trees"; +import { type Heartbeat } from "@chicmoz-pkg/message-bus"; +import { type NewBlockEvent } from "@chicmoz-pkg/message-registry"; +import { deliver } from "@chicmoz/test-harness"; +import { BSON } from "bson"; +import { type SQL } from "drizzle-orm"; +import { Kafka, logLevel } from "kafkajs"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + type BuiltBlock, + buildBlock, + buildChain, + catchupEvent, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; +import { heads, loadChainReads } from "./support/chain.js"; +import { + type ExplorerApiForTest, + startExplorerApiForTest, +} from "./support/explorer-api.js"; + +// Each case runs on a rollup version of its own, because an ordered block +// demotes every canonical block of its version above its proposed tip, and +// on heights of its own, because repair rows are per network. +let lastVersion = 1_000; +const freshVersion = () => ++lastVersion; + +describe("the canonical chain on a real database", () => { + let api: ExplorerApiForTest; + let reads: Awaited>; + let ordered: (b: BuiltBlock, proposedTip?: number) => Promise; + let catchup: (b: BuiltBlock, options?: { finalized?: true }) => Promise; + let orderedWith: ( + event: NewBlockEvent, + heartbeat: Heartbeat, + ) => Promise; + let ignoredUnordered: (b: BuiltBlock) => Promise; + let setOrphaned: (blocks: BuiltBlock[], orphaned: boolean) => Promise; + let unseenCanonical: ( + height: bigint, + version: number, + ) => Promise; + let bareChain: (chain: { + version: number; + from: bigint; + count: number; + parent?: BuiltBlock; + offChain?: true; + }) => Promise>; + let throughBroker: ( + event: NewBlockEvent, + ) => Promise<{ deliveries: number; rebalances: number; beats: number }>; + let holdChainLock: () => Promise<() => Promise>; + let lockWaiters: () => Promise; + let fulfilByHeight: (height: bigint) => Promise; + let walkBound: number; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler, catchupHandler } = await import( + "../../src/events/received/on-block/index.js" + ); + const { WALK_BOUND, withChainLock } = await import( + "../../src/svcs/database/controllers/l2block/canonical.js" + ); + const { markOpenGapsFulfilledByHeight } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); + const { l2Block } = await import( + "../../src/svcs/database/schema/l2block/index.js" + ); + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { inArray, sql } = await import("drizzle-orm"); + const db = getDb(); + reads = await loadChainReads(); + walkBound = WALK_BOUND; + + ordered = (b, proposedTip) => + deliver(blockHandler, orderedEvent(b, proposedTip)); + catchup = (b, options) => deliver(catchupHandler, catchupEvent(b, options)); + orderedWith = (event, heartbeat) => blockHandler.cb(event, heartbeat); + ignoredUnordered = (b) => + deliver(blockHandler, { + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + } satisfies NewBlockEvent); + setOrphaned = async (blocks, orphaned) => { + await db + .update(l2Block) + .set({ + orphan_timestamp: orphaned ? Date.now() : null, + orphan_hasOrphanedParent: orphaned ? false : null, + }) + .where( + inArray( + l2Block.hash, + blocks.map((b) => b.hash), + ), + ); + }; + // Only the block row, without the header and archive rows every chain + // read joins, so no change sees it to demote it. + unseenCanonical = async (height, version) => { + const tag = version.toString(16).padStart(8, "0"); + const hash = `0x${tag}ee${height.toString(16).padStart(54, "0")}` as const; + await db.insert(l2Block).values({ + hash, + height, + version, + orphan_timestamp: null, + orphan_hasOrphanedParent: null, + }); + return hash; + }; + // Linked blocks, canonical unless `offChain`, with only the rows a link + // lookup reads, inserted in bulk: delivering thousands of blocks would + // take minutes. Returns the top block, as a parent for a built block. + bareChain = async ({ version, from, count, parent, offChain }) => { + const to = from + BigInt(count - 1); + const tag = version.toString(16).padStart(8, "0"); + const hashOf = (n: SQL) => + sql`'0x' || ${tag}::text || '00' || lpad(to_hex(${n}), 54, '0')`; + const rootOf = (n: SQL) => + sql`'0x' || ${tag}::text || 'ff' || lpad(to_hex(${n}), 54, '0')`; + const n = sql`n`; + const heights = sql`generate_series(${from}::bigint, ${to}::bigint) AS n`; + const orphanedAt = offChain ? sql`${Date.now()}::bigint` : sql`NULL`; + await db.execute( + sql`INSERT INTO "l2Block" ("hash", "height", "version", "orphan_timestamp", "orphan_hasOrphanedParent") SELECT ${hashOf(n)}, n, ${version}::bigint, ${orphanedAt}, ${offChain ? sql`false` : sql`NULL`} FROM ${heights}`, + ); + await db.execute( + sql`INSERT INTO "archive" ("root", "next_available_leaf_index", "block_hash") SELECT ${rootOf(n)}, 0, ${hashOf(n)} FROM ${heights}`, + ); + await db.execute( + sql`INSERT INTO "header" ("block_hash", "total_fees", "total_mana_used", "sponge_blob_hash") SELECT ${hashOf(n)}, 0, 0, '0x00' FROM ${heights}`, + ); + const height = sql`b."height"`; + const lowestLastArchive = parent + ? sql`${parent.archive.root.toString()}::text` + : rootOf(sql`${height} - 1`); + await db.execute( + sql`INSERT INTO "last_archive" ("root", "next_available_leaf_index", "header_id") + SELECT CASE WHEN ${height} = ${from}::bigint THEN ${lowestLastArchive} ELSE ${rootOf(sql`${height} - 1`)} END, 0, h."id" + FROM "header" h JOIN "l2Block" b ON b."hash" = h."block_hash" + WHERE b."version" = ${version}::bigint AND ${height} BETWEEN ${from}::bigint AND ${to}::bigint AND b."hash" = ${hashOf(height)}`, + ); + const top = `0x${tag}ff${to.toString(16).padStart(54, "0")}`; + return { + archive: new AppendOnlyTreeSnapshot( + Fr.fromHexString(top), + TreeLeafIndex(0), + ), + }; + }; + const kafka = new Kafka({ + clientId: `${api.namespace}-chain-walk`, + brokers: [api.stack.env.KAFKA_CONNECTION], + sasl: { + mechanism: "plain", + username: api.stack.env.KAFKA_SASL_USERNAME, + password: api.stack.env.KAFKA_SASL_PASSWORD, + }, + logLevel: logLevel.NOTHING, + }); + // Two members of one group whose session is shorter than a long walk: + // only the handler's heartbeats keep the walking member, and losing it + // would hand the partition, and the message again, to the other. + throughBroker = async (event) => { + const topic = `${api.namespace}.chain-walk`; + const groupId = `${api.namespace}-chain-walk`; + const admin = kafka.admin(); + await admin.connect(); + await admin.createTopics({ + topics: [{ topic, numPartitions: 1 }], + waitForLeaders: true, + }); + const outcome = { deliveries: 0, rebalances: 0, beats: 0 }; + let sent = false; + let settle: (error?: unknown) => void = () => undefined; + const handled = new Promise((resolve, reject) => { + settle = (error) => (error === undefined ? resolve() : reject(error)); + }); + const members = [0, 1].map(() => + kafka.consumer({ + groupId, + sessionTimeout: 6_000, + heartbeatInterval: 1_000, + }), + ); + try { + for (const member of members) { + member.on(member.events.REBALANCING, () => { + if (sent) { + outcome.rebalances++; + } + }); + await member.connect(); + await member.subscribe({ topic, fromBeginning: true }); + await member.run({ + eachMessage: async ({ message, heartbeat }) => { + outcome.deliveries++; + try { + await blockHandler.cb( + BSON.deserialize( + message.value ?? Buffer.alloc(0), + ) as NewBlockEvent, + () => { + outcome.beats++; + return heartbeat(); + }, + ); + settle(); + } catch (e) { + settle(e); + throw e; + } + }, + }); + } + const deadline = Date.now() + 30_000; + for (;;) { + const { + groups: [group], + } = await admin.describeGroups([groupId]); + if (group?.state === "Stable" && group.members.length === 2) { + break; + } + if (Date.now() > deadline) { + throw new Error(`group ${groupId} never settled with both members`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + sent = true; + const producer = kafka.producer(); + await producer.connect(); + await producer.send({ + topic, + messages: [{ value: Buffer.from(BSON.serialize(event)) }], + }); + await producer.disconnect(); + await handled; + // Read once the broker holds the commit: a member lost before it + // would have the message delivered again. + const committedBy = Date.now() + 30_000; + for (;;) { + const offsets = await admin.fetchOffsets({ + groupId, + topics: [topic], + }); + if (offsets[0]?.partitions[0]?.offset === "1") { + break; + } + if (Date.now() > committedBy) { + throw new Error(`group ${groupId} never committed the message`); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + } + // Leaving the group below rebalances it too. + return { ...outcome }; + } finally { + for (const member of members) { + await member.disconnect(); + } + 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; + }; + fulfilByHeight = markOpenGapsFulfilledByHeight; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("replaces the block at its height and its linked descendants, and demotes every block above its tip, in one record", async () => { + const version = freshVersion(); + const a = await buildChain(1_000n, 4, { version }); + const above = await buildBlock(1_005n, [freshTxHash()], { version }); + for (const block of [...a, above]) { + await ordered(block); + } + const b1 = await buildBlock(1_001n, [freshTxHash()], { + version, + parent: a[0], + }); + + await ordered(b1, 1_002); + + expect(await reads.chainOf(version)).toEqual(heads([a[0], b1])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a[1], a[2], a[3], above].map((b) => b.hash) }, + ]); + expect(await reads.causesOf(version)).toEqual([ + { hash: b1.hash, kind: "ordered" }, + ]); + expect( + await Promise.all([a[1], a[2], above].map((b) => reads.stateOf(b.hash))), + ).toEqual([ + { hasOrphanedParent: false }, + { hasOrphanedParent: true }, + { hasOrphanedParent: false }, + ]); + }); + + it("changes nothing for an ordered block already canonical, and ends a replay and a flip with the listener's chain and one active record", async () => { + const version = freshVersion(); + const a = await buildChain(2_000n, 4, { version }); + const b = await buildChain(2_001n, 2, { version, parent: a[0] }); + const pass = async () => { + for (const block of a) { + await ordered(block); + } + for (const block of b) { + await ordered(block, 2_002); + } + }; + const active = async () => + (await reads.recordsOf(version)) + .filter((r) => r.active) + .map((r) => r.blocks); + await pass(); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await active()).toEqual([[a[1], a[2], a[3]].map((x) => x.hash)]); + + await ordered(b[1], 2_002); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await reads.recordsOf(version)).toHaveLength(1); + + await pass(); + expect(await reads.chainOf(version)).toEqual(heads([a[0], ...b])); + expect(await active()).toEqual([[a[1], a[2], a[3]].map((x) => x.hash)]); + + for (const block of a.slice(1)) { + await ordered(block, 2_003); + } + expect(await reads.chainOf(version)).toEqual(heads(a)); + expect(await active()).toEqual([b.map((x) => x.hash)]); + }); + + it("demotes the old blocks above the tip with the first replacing block, and those between a gap and the tip when the pass reaches them", async () => { + const version = freshVersion(); + const [a0, a1, missing, a3, a4] = await buildChain(3_000n, 5, { version }); + for (const block of [a0, a1, a3, a4]) { + await ordered(block); + } + expect(await reads.stateOf(missing.hash)).toBe("absent"); + const b = await buildChain(3_001n, 3, { version, parent: a0 }); + + await ordered(b[0], 3_003); + expect(await reads.chainOf(version)).toEqual(heads([a0, b[0], a3])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash, a4.hash] }, + ]); + + await ordered(b[1], 3_003); + await ordered(b[2], 3_003); + expect(await reads.chainOf(version)).toEqual(heads([a0, ...b])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash, a4.hash] }, + { active: true, blocks: [a3.hash] }, + ]); + }); + + it("never demotes the live chain above a gap for an ordered block below it", async () => { + const version = freshVersion(); + const live = await buildChain(4_000n, 4, { version }); + await ordered(live[2]); + await ordered(live[3]); + + await ordered(live[0], 4_003); + expect(await reads.chainOf(version)).toEqual( + heads([live[0], live[2], live[3]]), + ); + + await ordered(live[1], 4_003); + expect(await reads.chainOf(version)).toEqual(heads(live)); + expect(await reads.recordsOf(version)).toEqual([]); + }); + + it("keeps a finalized catch-up block at a canonical height off the chain until its ordered copy arrives", async () => { + const version = freshVersion(); + const a = await buildChain(5_000n, 3, { version }); + for (const block of a) { + await ordered(block); + } + const b1 = await buildBlock(5_001n, [freshTxHash()], { + version, + parent: a[0], + }); + + await catchup(b1, { finalized: true }); + expect(await reads.chainOf(version)).toEqual(heads(a)); + expect(await reads.recordsOf(version)).toEqual([]); + + await ordered(b1); + expect(await reads.chainOf(version)).toEqual(heads([a[0], b1])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a[1].hash, a[2].hash] }, + ]); + }); + + it("joins a catch-up block at an empty height only when the chain above descends from it", async () => { + const version = freshVersion(); + const c = await buildChain(6_000n, 4, { version }); + for (const block of [c[0], c[2], c[3]]) { + await ordered(block); + } + const stranger = await buildBlock(6_001n, [freshTxHash()], { + version, + parent: c[0], + }); + + await catchup(stranger, { finalized: true }); + expect(await reads.stateOf(stranger.hash)).toEqual({ + hasOrphanedParent: false, + }); + + await catchup(c[1]); + expect(await reads.chainOf(version)).toEqual(heads(c)); + expect(await reads.recordsOf(version)).toEqual([]); + expect(await reads.ownerOf(c[1].txHashes[0])).toBe(c[1].hash); + }); + + it("keeps a finalized catch-up block above the canonical head off the chain", async () => { + const version = freshVersion(); + const [head, above] = await buildChain(16_000n, 2, { version }); + await ordered(head); + + await catchup(above, { finalized: true }); + + expect(await reads.chainOf(version)).toEqual(heads([head])); + }); + + it("demotes the block below a catch-up block joined from above when it is not its parent, and requests the parent", async () => { + const version = freshVersion(); + const [a0, a1] = await buildChain(17_000n, 2, { version }); + const b1 = await buildBlock(17_001n, [freshTxHash()], { + version, + parent: a0, + }); + const [b2, b3] = await buildChain(17_002n, 2, { version, parent: b1 }); + await ordered(a0); + await ordered(a1); + await ordered(b3); + + await catchup(b2); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b2, b3])); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: [a1.hash] }, + ]); + expect(await reads.causesOf(version)).toEqual([ + { hash: b2.hash, kind: "catchup" }, + ]); + expect(await reads.repairOpen(17_001)).toBe(true); + }); + + it("puts back an ordered block that a stale catch-up undid once the next ordered block arrives, listing one reorg", async () => { + const version = freshVersion(); + const [a1, a2, a3, a4] = await buildChain(24_001n, 4, { version }); + const [b2, b3] = await buildChain(24_002n, 2, { version, parent: a1 }); + for (const block of [a1, a2, a4]) { + await ordered(block); + } + // A4 stays canonical across the gap at 24_003, above B2. + await ordered(b2, 24_004); + // A3 links to A4, so it brings A2 back and demotes B2. + await catchup(a3); + expect(await reads.chainOf(version)).toEqual(heads([a1, a2, a3, a4])); + + await ordered(b3, 24_004); + + expect(await reads.chainOf(version)).toEqual(heads([a1, b2, b3])); + expect( + await Promise.all([a2, a3, a4].map((b) => reads.stateOf(b.hash))), + ).toEqual([ + { hasOrphanedParent: false }, + { hasOrphanedParent: true }, + { hasOrphanedParent: true }, + ]); + expect(await reads.listed([a2, a3, a4, b2, b3])).toEqual([ + { orphanedBlockHash: a2.hash, height: 24_002n, nbrOfOrphanedBlocks: 3 }, + ]); + }); + + it("opens a repair at the parent height of each catch-up block that joins below an ordered block far above the head, until one joins on the old chain", async () => { + const version = freshVersion(); + const [a0, a1] = await buildChain(18_000n, 2, { version }); + const b = await buildChain(18_001n, 5, { version, parent: a0 }); + await ordered(a0); + await ordered(a1); + await ordered(b[4]); + + for (const block of b.slice(0, 4).reverse()) { + const height = Number(block.height); + expect([ + await reads.repairOpen(height), + await reads.repairOpen(height - 1), + ]).toEqual([true, false]); + await catchup(block); + } + + expect(await reads.chainOf(version)).toEqual(heads([a0, ...b])); + expect(await reads.repairOpen(18_001)).toBe(false); + }); + + it("fills history from block 1 with finalized catch-up blocks, each only on the canonical block below as its parent", async () => { + const version = freshVersion(); + const c = await buildChain(1n, 6, { version }); + await ordered(c[4], 6); + await ordered(c[5], 6); + const stranger = await buildBlock(3n, [freshTxHash()], { version }); + + for (const block of [c[0], c[1], stranger, c[2], c[3]]) { + await catchup(block, { finalized: true }); + } + + expect(await reads.chainOf(version)).toEqual(heads(c)); + expect(await reads.stateOf(stranger.hash)).toEqual({ + hasOrphanedParent: false, + }); + expect(await reads.recordsOf(version)).toEqual([]); + }); + + it("opens a repair at the empty height below a finalized catch-up block that joins with its link from above undecided", async () => { + const version = freshVersion(); + // Its parent is not stored, so the walk down from it cannot decide. + const head = await buildBlock(26_004n, [freshTxHash()], { version }); + const block = await buildBlock(26_002n, [freshTxHash()], { version }); + await ordered(head); + + await catchup(block, { finalized: true }); + + expect(await reads.stateOf(block.hash)).toBe("canonical"); + expect(await reads.repairOpen(26_001)).toBe(true); + }); + + it("clears the dropped rows of the effects a walk-made-canonical block owns, and attaches the rest from its repair", async () => { + const version = freshVersion(); + const kept = freshTxHash(); + const shared = freshTxHash(); + const a0 = await buildBlock(7_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(7_001n, [kept, shared], { + version, + parent: a0, + }); + const b1 = await buildBlock(7_001n, [shared], { version, parent: a0 }); + const a2 = await buildBlock(7_002n, [freshTxHash()], { + version, + parent: a1, + }); + await ordered(a0); + await ordered(a1); + await ordered(b1); + expect(await reads.isDropped(kept)).toBe(true); + expect(await reads.ownerOf(shared)).toBe(b1.hash); + + await ordered(a2); + expect(await reads.chainOf(version)).toEqual(heads([a0, a1, a2])); + expect(await reads.isDropped(kept)).toBe(false); + expect(await reads.ownerOf(shared)).toBe(b1.hash); + expect(await reads.isDropped(shared)).toBe(true); + expect(await reads.repairOpen(7_001)).toBe(true); + + await catchup(a1); + expect(await reads.ownerOf(shared)).toBe(a1.hash); + expect(await reads.isDropped(shared)).toBe(false); + expect(await reads.repairOpen(7_001)).toBe(false); + }); + + it("keeps a repair open when a stale post-commit hook runs after a walk revived its height", async () => { + const version = freshVersion(); + const [p, a] = await buildChain(19_000n, 2, { version }); + const b = await buildBlock(19_001n, [freshTxHash()], { + version, + parent: p, + }); + const next = await buildBlock(19_002n, [freshTxHash()], { + version, + parent: b, + }); + await ordered(p); + await ordered(a); + await catchup(b); + await ordered(next); + expect(await reads.repairOpen(19_001)).toBe(true); + + // `a`'s hook, delayed past the change that replaced it. + await fulfilByHeight(19_001n); + + expect(await reads.repairOpen(19_001)).toBe(true); + }); + + it("flags a new off-chain block whose stored parent is off the chain, whichever of the two arrives first", async () => { + const version = freshVersion(); + const live = await buildChain(20_000n, 3, { version }); + for (const block of live) { + await ordered(block); + } + const offChainPair = async () => { + const parent = await buildBlock(20_001n, [freshTxHash()], { + version, + parent: live[0], + }); + const child = await buildBlock(20_002n, [freshTxHash()], { + version, + parent, + }); + return { parent, child }; + }; + const parentFirst = await offChainPair(); + const childFirst = await offChainPair(); + + await catchup(parentFirst.parent); + await catchup(parentFirst.child); + await catchup(childFirst.child); + await catchup(childFirst.parent); + + expect( + await Promise.all( + [parentFirst.child, childFirst.child].map((b) => reads.stateOf(b.hash)), + ), + ).toEqual([{ hasOrphanedParent: true }, { hasOrphanedParent: true }]); + }); + + it("brings back a live block the old code orphaned without demoting the chain above it", async () => { + const version = freshVersion(); + const live = await buildChain(8_000n, 5, { version }); + const wrong = await buildChain(8_001n, 2, { version, parent: live[0] }); + for (const block of live) { + await ordered(block); + } + for (const block of wrong) { + await catchup(block); + } + // What the height rule left behind: live blocks orphaned under wrong ones. + await setOrphaned([live[1], live[2]], true); + await setOrphaned(wrong, false); + + await ordered(live[2], 8_004); + + expect(await reads.chainOf(version)).toEqual(heads(live)); + expect(await reads.recordsOf(version)).toEqual([ + { active: true, blocks: wrong.map((b) => b.hash) }, + ]); + }); + + it("keeps a partly revived record active with only its blocks still off the chain, and lists a block that died twice once", async () => { + const version = freshVersion(); + const a = await buildChain(9_000n, 4, { version }); + const b1 = await buildBlock(9_001n, [freshTxHash()], { + version, + parent: a[0], + }); + for (const block of a) { + await ordered(block); + } + await ordered(b1); + + await ordered(a[1]); + expect((await reads.recordsOf(version)).map((r) => r.active)).toEqual([ + true, + true, + ]); + expect(await reads.listed([...a, b1])).toEqual([ + { orphanedBlockHash: b1.hash, height: 9_001n, nbrOfOrphanedBlocks: 1 }, + { orphanedBlockHash: a[2].hash, height: 9_002n, nbrOfOrphanedBlocks: 2 }, + ]); + + await ordered(b1); + expect(await reads.listed([...a, b1])).toEqual([ + { orphanedBlockHash: a[1].hash, height: 9_001n, nbrOfOrphanedBlocks: 1 }, + { orphanedBlockHash: a[2].hash, height: 9_002n, nbrOfOrphanedBlocks: 2 }, + ]); + }); + + it("demotes a canonical holder of an ordered block's tx above it, across a gap, so no block of the pass is skipped", async () => { + const version = freshVersion(); + const [x, y] = [freshTxHash(), freshTxHash()]; + const a5 = await buildBlock(10_005n, [freshTxHash()], { version }); + const a6 = await buildBlock(10_006n, [freshTxHash()], { + version, + parent: a5, + }); + const a7 = await buildBlock(10_007n, [freshTxHash()], { + version, + parent: a6, + }); + const a8 = await buildBlock(10_008n, [x, y], { version, parent: a7 }); + for (const block of [a5, a6, a8]) { + await ordered(block); + } + const b6 = await buildBlock(10_006n, [x], { version, parent: a5 }); + const b7 = await buildBlock(10_007n, [y], { version, parent: b6 }); + const b8 = await buildBlock(10_008n, [freshTxHash()], { + version, + parent: b7, + }); + + for (const block of [b6, b7, b8]) { + await ordered(block, 10_008); + } + + expect(await reads.chainOf(version)).toEqual(heads([a5, b6, b7, b8])); + expect([await reads.ownerOf(x), await reads.ownerOf(y)]).toEqual([ + b6.hash, + b7.hash, + ]); + }); + + it("demotes a stale canonical holder of an ordered block's tx below it, and requests the heights that leaves empty", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(15_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(15_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(15_002n, [freshTxHash()], { + version, + parent: a1, + }); + const a3 = await buildBlock(15_003n, [freshTxHash()], { + version, + parent: a2, + }); + for (const block of [a0, a1, a2, a3]) { + await ordered(block); + } + const b1 = await buildBlock(15_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(15_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(15_003n, [x], { version, parent: b2 }); + + await ordered(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect([ + await reads.repairOpen(15_001), + await reads.repairOpen(15_002), + ]).toEqual([true, true]); + }); + + it("demotes a stale canonical holder of a tx below a catch-up block joined from above, and requests the heights that leaves empty", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(21_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(21_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(21_002n, [freshTxHash()], { + version, + parent: a1, + }); + for (const block of [a0, a1, a2]) { + await ordered(block); + } + const b1 = await buildBlock(21_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(21_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(21_003n, [x], { version, parent: b2 }); + const b4 = await buildBlock(21_004n, [freshTxHash()], { + version, + parent: b3, + }); + await ordered(b4); + + await catchup(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3, b4])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect([ + await reads.repairOpen(21_001), + await reads.repairOpen(21_002), + ]).toEqual([true, true]); + }); + + it("demotes a stale canonical holder of a tx below a block a walk made canonical when its catch-up arrives, requesting the heights that leaves empty and closing the block's repair", async () => { + const version = freshVersion(); + const x = freshTxHash(); + const a0 = await buildBlock(23_000n, [freshTxHash()], { version }); + const a1 = await buildBlock(23_001n, [x], { version, parent: a0 }); + const a2 = await buildBlock(23_002n, [freshTxHash()], { + version, + parent: a1, + }); + const a3 = await buildBlock(23_003n, [freshTxHash()], { + version, + parent: a2, + }); + for (const block of [a0, a1, a2, a3]) { + await ordered(block); + } + const b1 = await buildBlock(23_001n, [freshTxHash()], { + version, + parent: a0, + }); + const b2 = await buildBlock(23_002n, [freshTxHash()], { + version, + parent: b1, + }); + const b3 = await buildBlock(23_003n, [x], { version, parent: b2 }); + const b4 = await buildBlock(23_004n, [freshTxHash()], { + version, + parent: b3, + }); + await catchup(b3); + await ordered(b4); + expect(await reads.chainOf(version)).toEqual(heads([a0, a1, b3, b4])); + expect(await reads.repairOpen(23_003)).toBe(true); + + await catchup(b3); + + expect(await reads.chainOf(version)).toEqual(heads([a0, b3, b4])); + expect(await reads.ownerOf(x)).toBe(b3.hash); + expect(await reads.stateOf(a1.hash)).toEqual({ hasOrphanedParent: false }); + expect([ + await reads.repairOpen(23_001), + await reads.repairOpen(23_002), + await reads.repairOpen(23_003), + ]).toEqual([true, true, false]); + }); + + it("treats a parent lookup that finds two blocks as a missing parent", async () => { + const version = freshVersion(); + const [p] = await buildChain(11_000n, 1, { version }); + const twin = await buildBlock(11_001n, [freshTxHash()], { + version, + parent: p, + }); + const other = await buildBlock(11_001n, [freshTxHash()], { + version, + parent: p, + archive: twin.archive, + }); + const child = await buildBlock(11_002n, [freshTxHash()], { + version, + parent: twin, + }); + await ordered(p); + await catchup(twin); + await catchup(other); + await ordered(child); + expect(await reads.chainOf(version)).toEqual(heads([p, child])); + + await catchup(twin); + expect(await reads.chainOf(version)).toEqual(heads([p, child])); + + await catchup(twin, { finalized: true }); + expect(await reads.chainOf(version)).toEqual(heads([p, twin, child])); + }); + + it("ignores a block event that is not from the ordered stream", async () => { + const version = freshVersion(); + const [block] = await buildChain(12_000n, 1, { version }); + + await ignoredUnordered(block); + + expect(await reads.stateOf(block.hash)).toBe("absent"); + }); + + it("refuses a second canonical block at a height in the database, and the block handler rethrows the refusal", async () => { + const version = freshVersion(); + const [block] = await buildChain(29_000n, 1, { version }); + const unseen = await unseenCanonical(block.height, version); + + await expect(ordered(block)).rejects.toMatchObject({ + code: "23505", + constraint: "l2block_one_canonical_per_height_idx", + }); + + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.stateOf(unseen)).toBe("canonical"); + }); + + it("serializes the block and catch-up consumers storing one height on the chain lock", async () => { + const version = freshVersion(); + const [p] = await buildChain(13_000n, 1, { version }); + const [fromStream, fromCatchup] = await Promise.all( + [0, 1].map(() => + buildBlock(13_001n, [freshTxHash()], { version, parent: p }), + ), + ); + const above = await buildBlock(13_002n, [freshTxHash()], { + version, + parent: fromCatchup, + }); + await ordered(p); + await ordered(above); + + const release = await holdChainLock(); + const finished: string[] = []; + const delivered = Promise.all([ + ordered(fromStream).then(() => finished.push("block")), + 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)); + } + expect(finished).toEqual([]); + } finally { + await release(); + } + await delivered; + + expect(await reads.chainOf(version)).toEqual(heads([p, fromStream])); + }); + + it("heartbeats while settling a block that walks and demotes nothing", async () => { + const version = freshVersion(); + const [block] = await buildChain(25_000n, 1, { version }); + let beats = 0; + + await orderedWith(orderedEvent(block), () => { + beats++; + return Promise.resolve(); + }); + + expect(await reads.stateOf(block.hash)).toBe("canonical"); + expect(beats).toBeGreaterThan(0); + }); + + it("heartbeats before each tx effect it writes", async () => { + const beatsFor = async (block: BuiltBlock) => { + let beats = 0; + await orderedWith(orderedEvent(block), () => { + beats++; + return Promise.resolve(); + }); + return beats; + }; + const one = await buildBlock(27_000n, [freshTxHash()], { + version: freshVersion(), + }); + const four = await buildBlock( + 27_010n, + [freshTxHash(), freshTxHash(), freshTxHash(), freshTxHash()], + { version: freshVersion() }, + ); + + // The rest of each change beats once per statement of up to a thousand + // rows, as often for one tx as for four. + expect((await beatsFor(four)) - (await beatsFor(one))).toBe(3); + }); + + it("rolls back a block with its tx effects and contract rows when a heartbeat fails after they are written", async () => { + const tx = freshTxHash(); + const block = await buildBlock(28_000n, [tx], { + version: freshVersion(), + publishesClass: true, + }); + let beats = 0; + // The beats before its effect and before its class row pass; the next, + // settlement's first, fails. + const failsThird = () => + ++beats > 2 + ? Promise.reject(new Error("rebalancing")) + : Promise.resolve(); + + await expect(orderedWith(orderedEvent(block), failsThird)).rejects.toThrow( + "rebalancing", + ); + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.ownerOf(tx)).toBeUndefined(); + expect(await reads.classesOf(block.hash)).toEqual([]); + + await ordered(block); + expect(await reads.classesOf(block.hash)).toHaveLength(1); + }); + + describe("bounds", () => { + it("stops a walk at the bound without throwing, keeps its partition through it, and rolls back when a heartbeat fails", async () => { + const version = freshVersion(); + const from = 100_000n; + const [base] = await buildChain(from, 1, { version }); + await ordered(base); + await bareChain({ + version, + from: from + 1n, + count: walkBound + 2, + parent: base, + }); + const replacing = await buildBlock(from + 1n, [freshTxHash()], { + version, + parent: base, + }); + const event = orderedEvent(replacing, Number(from) + 2 * walkBound); + + await expect( + orderedWith(event, () => Promise.reject(new Error("rebalancing"))), + ).rejects.toThrow("rebalancing"); + expect(await reads.stateOf(replacing.hash)).toBe("absent"); + + const { beats, ...delivery } = await throughBroker(event); + + expect(delivery).toEqual({ deliveries: 1, rebalances: 0 }); + expect(beats).toBeGreaterThanOrEqual(walkBound / 500); + const chain = await reads.chainOf(version); + expect(chain.slice(0, 2)).toEqual(heads([base, replacing])); + expect(chain.slice(2).map((b) => b.height)).toEqual([ + from + BigInt(walkBound) + 2n, + ]); + }, 300_000); + + it("stops a walk down at the bound, clearing and requesting the height below it, where the parent's catch-up then joins", async () => { + const version = freshVersion(); + const from = 400_000n; + const [base] = await buildChain(from - 1n, 1, { version }); + const [parent, competitor] = await Promise.all( + [0, 1].map(() => + buildBlock(from, [freshTxHash()], { version, parent: base }), + ), + ); + await ordered(base); + await ordered(competitor); + const top = await bareChain({ + version, + from: from + 1n, + count: walkBound, + parent, + offChain: true, + }); + const head = await buildBlock( + from + BigInt(walkBound) + 1n, + [freshTxHash()], + { version, parent: top }, + ); + + await ordered(head); + expect( + await Promise.all( + [competitor, parent].map((b) => reads.stateOf(b.hash)), + ), + ).toEqual([{ hasOrphanedParent: false }, "absent"]); + expect(await reads.repairOpen(Number(from))).toBe(true); + + await catchup(parent); + expect(await reads.stateOf(parent.hash)).toBe("canonical"); + expect(await reads.repairOpen(Number(from))).toBe(false); + }, 300_000); + + it("throws, changing nothing, on more canonical blocks above a tip than the bound, and demotes exactly the bound", async () => { + const version = freshVersion(); + const from = 200_000n; + await bareChain({ version, from: from + 1n, count: walkBound + 1 }); + const [block] = await buildChain(from, 1, { version }); + + await expect(ordered(block)).rejects.toThrow( + `More than ${walkBound} canonical blocks`, + ); + expect(await reads.stateOf(block.hash)).toBe("absent"); + expect(await reads.chainOf(version)).toHaveLength(walkBound + 1); + + // Replacing the lowest of them leaves exactly the bound above the tip. + const replacing = await buildBlock(from + 1n, [freshTxHash()], { + version, + }); + await ordered(replacing); + + expect(await reads.chainOf(version)).toEqual(heads([replacing])); + }, 300_000); + + it("rethrows a chain lock wait over 10 s", async () => { + const version = freshVersion(); + const [block] = await buildChain(300_000n, 1, { version }); + const release = await holdChainLock(); + try { + await expect(ordered(block)).rejects.toThrow("lock timeout"); + } finally { + await release(); + } + expect(await reads.stateOf(block.hash)).toBe("absent"); + }, 30_000); + }); +}); 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 new file mode 100644 index 000000000..efc26f211 --- /dev/null +++ b/services/explorer-api/tests/integration/late-replacing-block.integration.test.ts @@ -0,0 +1,175 @@ +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, + catchupEvent, + freshTxHash, + 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")}`; + +// A block at a height the chain replaced can stay stored while the replacing +// chain's next blocks are stored above it. Every canonical block of the +// version above an ordered block's tip is demoted, so the cases use +// ascending, disjoint heights, in file order. +describe("a replaced block that stays stored on a real database", () => { + let api: ExplorerApiForTest; + let store: (b: BuiltBlock) => Promise; + let storeLate: (b: BuiltBlock) => Promise; + let canonicalHash: (height: bigint) => Promise; + let orphanOf: ( + hash: HexString, + ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; + let isDropped: (txHash: HexString) => Promise; + let storeTips: ( + tips: Pick & { + finalized: BuiltBlock; + proven: BuiltBlock; + checkpointed: BuiltBlock; + }, + ) => Promise; + let repairRequestCovers: (height: number) => Promise; + + beforeAll(async () => { + api = await startExplorerApiForTest(); + const { blockHandler, catchupHandler } = 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 { getDroppedTxByHash } = await import( + "../../src/svcs/database/controllers/dropped-tx/get-tx.js" + ); + const { buildTipBoundaryRepairRequest } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); + store = (b) => deliver(blockHandler, orderedEvent(b)); + storeLate = (b) => deliver(catchupHandler, catchupEvent(b)); + canonicalHash = async (height) => (await getBlock(height))?.hash; + orphanOf = async (hash) => { + const block = await getBlock(hash); + if (!block) { + return "absent"; + } + return block.orphan + ? { hasOrphanedParent: block.orphan.hasOrphanedParent } + : "active"; + }; + isDropped = async (txHash) => (await getDroppedTxByHash(txHash)) !== null; + const at = (block: BuiltBlock) => ({ + block: { number: Number(block.height), hash: block.hash }, + checkpoint: { + number: Number(block.height), + hash: word(Number(block.height)), + }, + }); + storeTips = ({ proposed, finalized, proven, checkpointed }) => + deliver(l2TipsHandler, { + tips: { + proposed, + checkpointed: at(checkpointed), + proven: at(proven), + finalized: at(finalized), + }, + observedAt: Date.now(), + source: { rpcNodeName: "node", aztecNodeVersion: "test" }, + } satisfies L2TipsEvent); + repairRequestCovers = async (height) => { + const planned = await buildTipBoundaryRepairRequest(); + return ( + planned?.request.ranges.some( + (range) => range.from <= height && height <= range.to, + ) ?? false + ); + }; + }); + + afterAll(async () => { + await api?.close(); + }); + + it("keeps the replacing chain's stored blocks active when its block at the replaced height arrives after them", async () => { + const replaced = await buildBlock(100n, [freshTxHash()]); + const replacing = await buildBlock(100n, [freshTxHash()]); + const child = await buildBlock(101n, [freshTxHash()], { + parent: replacing, + }); + const grandchild = await buildBlock(102n, [freshTxHash()], { + parent: child, + }); + await store(replaced); + await store(child); + await store(grandchild); + + await storeLate(replacing); + + expect(await orphanOf(replaced.hash)).toEqual({ hasOrphanedParent: false }); + expect( + await Promise.all([100n, 101n, 102n].map((h) => canonicalHash(h))), + ).toEqual([replacing.hash, child.hash, grandchild.hash]); + }); + + it("stops listing a block's txs as dropped once that block is canonical again", async () => { + const t = freshTxHash(); + const first = await buildBlock(200n, [t]); + const second = await buildBlock(200n, [freshTxHash()]); + await store(first); + await store(second); + expect(await isDropped(t)).toBe(true); + + await store(first); + + expect(await canonicalHash(200n)).toBe(first.hash); + 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, + }); + const next = await buildBlock(404n, [freshTxHash()], { + parent: replacing, + }); + 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); + }, + ); +}); 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 027e17ff7..1bd7abdba 100644 --- a/services/explorer-api/tests/integration/open-gap.integration.test.ts +++ b/services/explorer-api/tests/integration/open-gap.integration.test.ts @@ -35,6 +35,8 @@ describe("open gap scheduling on a real database", () => { let blocks: (heights: number[], version?: number) => Promise; let arrive: (height: number) => Promise; let orphan: (height: number) => Promise; + let repair: (height: number) => Promise; + let fulfil: (height: number) => Promise; let seedGaps: (rows: SeededGap[]) => Promise; let elapse: (ms: number) => Promise; let openGaps: () => Promise; @@ -57,10 +59,14 @@ describe("open gap scheduling on a real database", () => { const { l2Block } = await import( "../../src/svcs/database/schema/l2block/index.js" ); - const { buildMissingBlockRangeRequest, markOpenGapsFulfilledByHeight } = - await import( - "../../src/svcs/database/controllers/l2block/missing-ranges.js" - ); + const { + buildMissingBlockRangeRequest, + fulfilRepairHeight, + markOpenGapsFulfilledByHeight, + recordRepairHeights, + } = await import( + "../../src/svcs/database/controllers/l2block/missing-ranges.js" + ); const { observeRollupVersion } = await import( "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js" ); @@ -102,6 +108,9 @@ describe("open gap scheduling on a real database", () => { .set({ orphan_timestamp: Date.now(), orphan_hasOrphanedParent: false }) .where(eq(l2Block.hash, hashOf(height, CURRENT))); }; + repair = (height) => recordRepairHeights(db, [BigInt(height)]); + // What a block message's change does when it makes its block canonical. + fulfil = (height) => fulfilRepairHeight(db, BigInt(height)); seedGaps = async (rows) => { const now = Date.now(); await db.insert(l2OpenGapTable).values( @@ -197,6 +206,15 @@ describe("open gap scheduling on a real database", () => { expect(await tick()).toEqual([[90, 90]]); }); + it("requests a repair row while its block is present, until a block message there fulfils it", async () => { + await blocks(span(1, 100)); + await repair(50); + + expect(await tick()).toEqual([[50, 50]]); + await fulfil(50); + expect(await openGaps()).toEqual([]); + }); + it("selects due rows before the candidate limit, with the backoff capped at an hour", async () => { const backedOff = span(101, 160); await blocks(except(span(1, 200), [...backedOff, 170, 180])); diff --git a/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts b/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts index 4760ed060..927058cee 100644 --- a/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts +++ b/services/explorer-api/tests/integration/rollup-version-scoping.integration.test.ts @@ -2,7 +2,12 @@ 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, freshTxHash } from "./support/blocks.js"; +import { + type BuiltBlock, + buildBlock, + freshTxHash, + orderedEvent, +} from "./support/blocks.js"; import { type ExplorerApiForTest, startExplorerApiForTest, @@ -43,7 +48,11 @@ describe("reads scoped to the current rollup version on a real database", () => let storedTips: () => Promise<{ degradedReason?: string; proposed: { number: number } } | null>; let current: BuiltBlock[]; let old: BuiltBlock[]; - let store: (height: bigint, version: number) => Promise; + let store: ( + height: bigint, + version: number, + parent?: BuiltBlock, + ) => Promise; let orphanOf: ( hash: HexString, ) => Promise<{ hasOrphanedParent: boolean } | "active" | "absent">; @@ -128,25 +137,25 @@ describe("reads scoped to the current rollup version on a real database", () => }, }); - store = async (height, version) => { - const block = await buildBlock(height, [freshTxHash()], { version }); - await deliver(blockHandler, { - block: block.hex, - blockNumber: Number(block.height), - statusHint: "proposed", + store = async (height, version, parent) => { + const block = await buildBlock(height, [freshTxHash()], { + version, + parent, }); + await deliver(blockHandler, orderedEvent(block)); return block; }; // Stored first, so a lookup at height 1 that ignores the version meets it // before the current block. old = [await store(1n, OLD)]; - current = [await store(1n, CURRENT), await store(2n, CURRENT)]; - const replaced = await store(3n, CURRENT); - current.push(await store(3n, CURRENT)); + current = [await store(1n, CURRENT)]; + current.push(await store(2n, CURRENT, current[0])); + const replaced = await store(3n, CURRENT, current[1]); + current.push(await store(3n, CURRENT, current[1])); // Old blocks arriving after current ones at the same heights, as a // replayed backlog would, are not a reorg of the current chain. for (const height of [2n, 3n, 4n, 5n]) { - old.push(await store(height, OLD)); + old.push(await store(height, OLD, old[old.length - 1])); } expect((await getBlock(replaced.hash))?.orphan).toBeDefined(); orphanOf = async (hash) => { @@ -318,10 +327,10 @@ describe("reads scoped to the current rollup version on a real database", () => // The two reorg cases change the seed, so they run last. it("orphans only current-version blocks on a reorg of the current chain", async () => { - const [, block2, block3] = current; + const [block1, block2, block3] = current; const oldAbove = old.filter((b) => b.height > 2n); - await store(2n, CURRENT); + await store(2n, CURRENT, block1); expect(await orphanOf(block2.hash)).toEqual({ hasOrphanedParent: false }); expect(await orphanOf(block3.hash)).toEqual({ hasOrphanedParent: true }); diff --git a/services/explorer-api/tests/integration/support/blocks.ts b/services/explorer-api/tests/integration/support/blocks.ts index ef2da52d7..121ea0236 100644 --- a/services/explorer-api/tests/integration/support/blocks.ts +++ b/services/explorer-api/tests/integration/support/blocks.ts @@ -2,52 +2,89 @@ import { BlockNumber } from "@aztec-labs/foundation/branded-types"; import { Fr } from "@aztec-labs/foundation/curves/bn254"; import { EthAddress } from "@aztec-labs/foundation/eth-address"; import { Body, L2Block } from "@aztec-labs/stdlib/block"; +import { AppendOnlyTreeSnapshot } from "@aztec-labs/stdlib/trees"; import { BlockHeader, GlobalVariables, TxEffect, TxHash, } from "@aztec-labs/stdlib/tx"; +import { + type CatchupBlockEvent, + type NewBlockEvent, +} from "@chicmoz-pkg/message-registry"; import { type HexString } from "@chicmoz-pkg/types"; -import { listFixtures, loadFixture } from "@chicmoz/test-harness"; +import { + type FixtureData, + listFixtures, + loadFixture, +} from "@chicmoz/test-harness"; export type BuiltBlock = { hex: string; hash: HexString; height: bigint; txHashes: HexString[]; + archive: AppendOnlyTreeSnapshot; }; -// A recorded effect with public logs and no contract-class logs, so storing a -// clone adds no contract rows that would collide across blocks. -const baseBlock = (): L2Block => { +const recorded = ( + what: string, + wanted: (expected: FixtureData["l2-block"]["expected"]) => boolean, +): L2Block => { const fixture = listFixtures("local-network", "l2-block") .map((name) => loadFixture("local-network", "l2-block", name)) - .find( - (f) => - f.data.expected.counts.publicLogs > 0 && - f.data.expected.counts.contractClassLogs === 0 && - f.data.expected.contractInstanceAddresses.length === 0, - ); + .find((f) => wanted(f.data.expected)); if (!fixture) { - throw new Error("no recorded local-network block with public logs and no contract logs"); + throw new Error(`no recorded local-network block with ${what}`); } return L2Block.fromBuffer(Buffer.from(fixture.data.hex, "hex")); }; -let base: L2Block | undefined; +// 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, + )); /** * The coinbase is salted to tell headers at one height apart. The handler * does not recompute the body's commitments, so cloned effects are accepted. - * `version` replaces the recorded rollup version. + * `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. */ export const buildBlock = async ( height: bigint, txHashes: HexString[], - { version }: { version?: number } = {}, + { + version, + parent, + archive: sharedArchive, + publishesClass, + }: { + version?: number; + parent?: Pick; + archive?: AppendOnlyTreeSnapshot; + publishesClass?: true; + } = {}, ): Promise => { - base ??= baseBlock(); + const base = baseBlock(publishesClass === true); const [effect] = base.body.txEffects; if (!effect) { throw new Error("base block has no tx effect"); @@ -58,9 +95,16 @@ export const buildBlock = async ( coinbase: EthAddress.random(), ...(version === undefined ? {} : { version: new Fr(version) }), }); + const archive = + sharedArchive ?? + new AppendOnlyTreeSnapshot(Fr.random(), base.archive.nextAvailableLeafIndex); const block = new L2Block( - base.archive, - BlockHeader.from({ ...base.header, globalVariables: globals }), + archive, + BlockHeader.from({ + ...base.header, + ...(parent ? { lastArchive: parent.archive } : {}), + globalVariables: globals, + }), new Body( txHashes.map((h) => TxEffect.from({ ...effect, txHash: TxHash.fromString(h) })), ), @@ -74,6 +118,7 @@ export const buildBlock = async ( hash: (await decoded.hash()).toString(), height: BigInt(decoded.number), txHashes: decoded.body.txEffects.map((t) => t.txHash.toString()), + archive: decoded.archive, }; if (built.height !== height || built.txHashes.join() !== txHashes.join()) { throw new Error(`built block does not round-trip: height ${built.height}, txs ${built.txHashes.join()}`); @@ -82,3 +127,45 @@ export const buildBlock = async ( }; export const freshTxHash = (): HexString => TxHash.random().toString(); + +/** `count` linked blocks from `from` up, one fresh tx each; the first links to `parent`. */ +export const buildChain = async ( + from: bigint, + count: number, + { + version, + parent, + }: { version?: number; parent?: Pick } = {}, +): Promise => { + const chain: BuiltBlock[] = []; + for (let i = 0; i < count; i++) { + chain.push( + await buildBlock(from + BigInt(i), [freshTxHash()], { + version, + parent: chain[i - 1] ?? parent, + }), + ); + } + return chain; +}; + +/** As the hash-following listener sends it: `proposedTip` defaults to the block's own height. */ +export const orderedEvent = ( + b: BuiltBlock, + proposedTip = Number(b.height), +): NewBlockEvent => ({ + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + ordered: { proposedTip }, +}); + +export const catchupEvent = ( + b: BuiltBlock, + { finalized }: { finalized?: true } = {}, +): CatchupBlockEvent => ({ + block: b.hex, + blockNumber: Number(b.height), + statusHint: "proposed", + ...(finalized ? { finalized } : {}), +}); diff --git a/services/explorer-api/tests/integration/support/chain.ts b/services/explorer-api/tests/integration/support/chain.ts new file mode 100644 index 000000000..b60dd9995 --- /dev/null +++ b/services/explorer-api/tests/integration/support/chain.ts @@ -0,0 +1,178 @@ +import { type HexString } from "@chicmoz-pkg/types"; +import { type BuiltBlock } from "./blocks.js"; + +export type Head = { height: bigint; hash: HexString }; + +export const heads = (blocks: BuiltBlock[]): Head[] => + blocks.map(({ height, hash }) => ({ height, hash })); + +export type BlockState = + | "canonical" + | "absent" + | { hasOrphanedParent: boolean }; + +export type ReorgRecord = { active: boolean; blocks: HexString[] }; + +export type ListedReorg = { + orphanedBlockHash: HexString; + height: bigint; + nbrOfOrphanedBlocks: number; +}; + +/** + * Chain state read straight from the database: route reads are cached, and + * the block reads skip blocks without a body. Call after + * startExplorerApiForTest, like any explorer-api import. + */ +export const loadChainReads = async () => { + const { getDb } = await import("@chicmoz-pkg/postgres-helper"); + const { and, asc, eq, isNull } = await import("drizzle-orm"); + const { body, l2Block, txEffect } = await import( + "../../../src/svcs/database/schema/l2block/index.js" + ); + const { droppedTx } = await import( + "../../../src/svcs/database/schema/dropped-tx/index.js" + ); + const { l2ReorgBlockTable, l2ReorgTable } = await import( + "../../../src/svcs/database/schema/l2/reorg.js" + ); + const { l2OpenGapTable } = await import( + "../../../src/svcs/database/schema/l2/open-gap.js" + ); + const { l2ContractClassRegistered } = await import( + "../../../src/svcs/database/schema/l2contract/index.js" + ); + const { getReorgs } = await import( + "../../../src/svcs/database/controllers/l2block/get-block.js" + ); + const db = getDb(); + + /** The canonical blocks of a rollup version, lowest first. */ + const chainOf = (version: number): Promise => + db + .select({ height: l2Block.height, hash: l2Block.hash }) + .from(l2Block) + .where( + and(eq(l2Block.version, version), isNull(l2Block.orphan_timestamp)), + ) + .orderBy(asc(l2Block.height)); + + const stateOf = async (hash: HexString): Promise => { + const [row] = await db + .select({ + orphanTimestamp: l2Block.orphan_timestamp, + hasOrphanedParent: l2Block.orphan_hasOrphanedParent, + }) + .from(l2Block) + .where(eq(l2Block.hash, hash)); + if (!row) { + return "absent"; + } + return row.orphanTimestamp === null + ? "canonical" + : { hasOrphanedParent: row.hasOrphanedParent ?? false }; + }; + + /** The block whose body holds the tx effect. */ + const ownerOf = async (txHash: HexString): Promise => { + const [row] = await db + .select({ blockHash: body.blockHash }) + .from(txEffect) + .innerJoin(body, eq(txEffect.bodyId, body.id)) + .where(eq(txEffect.txHash, txHash)); + return row?.blockHash; + }; + + /** The contract classes stored with a block. */ + const classesOf = async (blockHash: HexString) => + ( + await db + .select({ id: l2ContractClassRegistered.contractClassId }) + .from(l2ContractClassRegistered) + .where(eq(l2ContractClassRegistered.blockHash, blockHash)) + ).map(({ id }) => id); + + const isDropped = async (txHash: HexString) => + ( + await db + .select({ txHash: droppedTx.txHash }) + .from(droppedTx) + .where(eq(droppedTx.txHash, txHash)) + ).length > 0; + + /** The reorg records of a rollup version, oldest first, blocks by height. */ + const recordsOf = async (version: number): Promise => { + const rows = await db + .select({ + id: l2ReorgTable.id, + revivedAt: l2ReorgTable.revivedAt, + hash: l2ReorgBlockTable.hash, + }) + .from(l2ReorgTable) + .innerJoin( + l2ReorgBlockTable, + eq(l2ReorgBlockTable.reorgId, l2ReorgTable.id), + ) + .where(eq(l2ReorgTable.rollupVersion, version)) + .orderBy( + asc(l2ReorgTable.id), + asc(l2ReorgBlockTable.height), + asc(l2ReorgBlockTable.hash), + ); + const records = new Map(); + for (const row of rows) { + const record = records.get(row.id) ?? { + active: row.revivedAt === null, + blocks: [], + }; + record.blocks.push(row.hash); + records.set(row.id, record); + } + return [...records.values()]; + }; + + /** The block that wrote each reorg record of a rollup version, oldest first. */ + const causesOf = (version: number) => + db + .select({ hash: l2ReorgTable.causeHash, kind: l2ReorgTable.causeKind }) + .from(l2ReorgTable) + .where(eq(l2ReorgTable.rollupVersion, version)) + .orderBy(asc(l2ReorgTable.id)); + + /** The `/l2/reorgs` entries that show one of `blocks`. */ + const listed = async (blocks: BuiltBlock[]): Promise => + (await getReorgs()) + .filter((r) => blocks.some((b) => b.hash === r.orphanedBlockHash)) + .map(({ orphanedBlockHash, height, nbrOfOrphanedBlocks }) => ({ + orphanedBlockHash, + height, + nbrOfOrphanedBlocks, + })); + + const repairOpen = async (height: number) => + ( + await db + .select({ id: l2OpenGapTable.id }) + .from(l2OpenGapTable) + .where( + and( + eq(l2OpenGapTable.reason, "reorg_repair"), + eq(l2OpenGapTable.fromHeight, height), + eq(l2OpenGapTable.toHeight, height), + eq(l2OpenGapTable.status, "open"), + ), + ) + ).length > 0; + + return { + chainOf, + stateOf, + ownerOf, + classesOf, + isDropped, + recordsOf, + listed, + repairOpen, + causesOf, + }; +}; diff --git a/services/explorer-api/tests/integration/support/recorded-blocks.ts b/services/explorer-api/tests/integration/support/recorded-blocks.ts index c16f61493..dbebd55df 100644 --- a/services/explorer-api/tests/integration/support/recorded-blocks.ts +++ b/services/explorer-api/tests/integration/support/recorded-blocks.ts @@ -19,19 +19,24 @@ import { join } from "node:path"; // explorer-api modules read their environment at import, so everything from // src is imported dynamically, after startExplorerApiForTest(). -/** The recorded blocks of one source in chain order, as aztec-listener publishes them. */ -export const recordedBlocks = (source: FixtureSource) => - listFixtures(source, "l2-block") - .map((name) => { - const { data } = loadFixture(source, "l2-block", name); +/** The recorded blocks of one source in chain order, as one ordered pass of aztec-listener. */ +export const recordedBlocks = (source: FixtureSource) => { + const fixtures = listFixtures(source, "l2-block").map( + (name) => [name, loadFixture(source, "l2-block", name).data] as const, + ); + const proposedTip = Math.max(...fixtures.map(([, data]) => data.expected.height)); + return fixtures + .map(([name, data]) => { const event: NewBlockEvent = { blockNumber: data.expected.height, statusHint: "proposed", block: data.hex, + ordered: { proposedTip }, }; return { name, expected: data.expected, event }; }) .sort((a, b) => a.expected.height - b.expected.height); +}; /** Bytecode, artifacts and class-publish logs run to hundreds of kilobytes per copy. */ const BULKY_KEYS = new Set([ diff --git a/services/explorer-api/tests/unit/block-tx-conflict.test.ts b/services/explorer-api/tests/unit/block-tx-conflict.test.ts deleted file mode 100644 index 47c27de32..000000000 --- a/services/explorer-api/tests/unit/block-tx-conflict.test.ts +++ /dev/null @@ -1,283 +0,0 @@ -import { type NewBlockEvent } from "@chicmoz-pkg/message-registry"; -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const mocks = vi.hoisted(() => ({ - logger: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }, - store: vi.fn<() => Promise>(), - markOpenGapsFulfilledByHeight: vi.fn(() => Promise.resolve()), - removePendingAndDroppedTx: vi.fn(() => Promise.resolve()), - storeContracts: vi.fn(() => Promise.resolve()), - deleteL2BlockByHash: vi.fn(() => Promise.resolve()), - deleteL2BlockByHeight: vi.fn(() => Promise.resolve()), - getTxEffectOwners: vi.fn(), - unOrphanBlock: vi.fn(() => Promise.resolve()), - detectReorg: vi.fn(() => Promise.resolve(false)), - handleReorg: vi.fn(() => Promise.resolve()), - parseBlock: vi.fn(), -})); - -vi.mock("../../src/environment.js", () => ({ L2_NETWORK_ID: "SANDBOX" })); -vi.mock("../../src/logger.js", () => ({ logger: mocks.logger })); -vi.mock("@chicmoz-pkg/backend-utils", () => ({ - blockFromBuffer: () => ({}), - parseBlock: mocks.parseBlock, -})); -vi.mock("../../src/svcs/database/index.js", () => ({ - controllers: { - l2Block: { - store: mocks.store, - markOpenGapsFulfilledByHeight: mocks.markOpenGapsFulfilledByHeight, - }, - l2Tx: { removePendingAndDroppedTx: mocks.removePendingAndDroppedTx }, - }, -})); -vi.mock("../../src/svcs/database/controllers/l2block/delete.js", () => ({ - deleteL2BlockByHash: mocks.deleteL2BlockByHash, - deleteL2BlockByHeight: mocks.deleteL2BlockByHeight, - getTxEffectOwners: mocks.getTxEffectOwners, -})); -vi.mock("../../src/svcs/database/controllers/l2block/orphan.js", () => ({ - unOrphanBlock: mocks.unOrphanBlock, -})); -vi.mock( - "../../src/svcs/database/controllers/l2/chain-info/rollup-version-cache.js", - () => ({ observeRollupVersion: () => Promise.resolve() }), -); -vi.mock("../../src/events/received/on-block/contracts.js", () => ({ - storeContracts: mocks.storeContracts, -})); -vi.mock("../../src/events/received/on-block/reorg-handler.js", () => ({ - detectReorg: mocks.detectReorg, - handleReorg: mocks.handleReorg, -})); - -const { blockHandler, catchupHandler } = await import( - "../../src/events/received/on-block/index.js" -); - -const noHeartbeat = () => Promise.resolve(); - -// Block 103158 from the 2026-09-29 incident: its tx was held by the active, -// stale-fork block 103172. -const parsed = () => ({ - height: 103158n, - hash: "0x0394", - header: { globalVariables: { version: 4248422647 } }, - body: { txEffects: [{ txHash: "0x2ba1" }, { txHash: "0x2ba2" }] }, -}); -const event: NewBlockEvent = { - block: "00", - blockNumber: 103158, - statusHint: "proposed", -}; -const txHashConflict = { - code: "23505", - detail: "Key (tx_hash)=(0x2ba1) already exists.", -}; -const owner = (overrides: object) => ({ - txHash: "0x2ba1", - blockHash: "0x2c3d", - blockHeight: 103172n, - rollupVersion: 4248422647, - isOrphaned: false, - ...overrides, -}); -const hooks = () => [ - mocks.markOpenGapsFulfilledByHeight, - mocks.storeContracts, - mocks.removePendingAndDroppedTx, -]; - -beforeEach(() => { - vi.clearAllMocks(); - mocks.detectReorg.mockResolvedValue(false); - mocks.parseBlock.mockImplementation(() => Promise.resolve(parsed())); - mocks.store - .mockReset() - .mockRejectedValueOnce(txHashConflict) - .mockResolvedValue(undefined); -}); - -describe("a tx held by an active block", () => { - it.each([ - ["live", () => blockHandler.cb(event, noHeartbeat)], - ["catch-up", () => catchupHandler.cb(event, noHeartbeat)], - ])( - "skips the %s block: acked, nothing stored or deleted, logged", - async (_name, run) => { - mocks.getTxEffectOwners.mockResolvedValue([owner({})]); - - await expect(run()).resolves.toBeUndefined(); - - // Decided before any write: not even an insert attempt. - expect(mocks.store).not.toHaveBeenCalled(); - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - "SKIPPED_BLOCK_TX_CONFLICT height=103158 hash=0x0394 owners=0x2ba1 in active block 103172 (0x2c3d)", - ); - }, - ); - - it("skips without pruning the orphaned holders among them either", async () => { - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ blockHash: "0xorphan", isOrphaned: true }), - owner({ txHash: "0x2ba2" }), - ]); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - expect(mocks.store).not.toHaveBeenCalled(); - }); -}); - -describe("a holder that turns active between the check and the insert", () => { - it("is still skipped, as the conflict's outcome, with no hooks", async () => { - mocks.getTxEffectOwners - .mockResolvedValueOnce([]) - .mockResolvedValue([owner({})]); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - expect(mocks.store).toHaveBeenCalledOnce(); - expect(mocks.deleteL2BlockByHash).not.toHaveBeenCalled(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringMatching(/^SKIPPED_BLOCK_TX_CONFLICT /), - ); - }); -}); - -describe("a reorg at the block's height", () => { - beforeEach(() => { - mocks.detectReorg.mockResolvedValue(true); - }); - - it("lets its own reorg orphan an active holder above it, then prunes it and stores", async () => { - const holders = [owner({ blockHeight: 103159n })]; - mocks.getTxEffectOwners.mockImplementation(() => - Promise.resolve(holders.map((holder) => ({ ...holder }))), - ); - // handleReorg orphans the block at the height and the ones above it. - mocks.handleReorg.mockImplementation(() => { - holders[0] = { ...holders[0], isOrphaned: true }; - return Promise.resolve(); - }); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.handleReorg).toHaveBeenCalled(); - expect(mocks.deleteL2BlockByHash).toHaveBeenCalledWith("0x2c3d"); - expect(mocks.store).toHaveBeenCalledTimes(2); - expect(mocks.logger.error).not.toHaveBeenCalled(); - }); - - it.each([ - ["below the height", owner({ blockHeight: 103157n })], - ["on another rollup version", owner({ rollupVersion: 1 })], - ])( - "skips before the reorg writes anything when the holder is %s", - async (_name, holder) => { - mocks.getTxEffectOwners.mockResolvedValue([holder]); - - await expect( - blockHandler.cb(event, noHeartbeat), - ).resolves.toBeUndefined(); - - expect(mocks.handleReorg).not.toHaveBeenCalled(); - expect(mocks.store).not.toHaveBeenCalled(); - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringMatching(/^SKIPPED_BLOCK_TX_CONFLICT height=103158 /), - ); - }, - ); -}); - -describe("the block itself already stored and active (redelivery)", () => { - it("is not a conflict: the duplicate hash counts as stored and the hooks run", async () => { - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ blockHash: "0x0394", blockHeight: 103158n }), - ]); - mocks.store.mockReset().mockRejectedValue({ - code: "23505", - detail: "Key (hash)=(0x0394) already exists.", - }); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.unOrphanBlock).toHaveBeenCalledWith("0x0394"); - for (const hook of hooks()) { - expect(hook).toHaveBeenCalledOnce(); - } - }); -}); - -describe("a duplicate on a key the handler does not know", () => { - it("does not count as stored: no hooks, logged", async () => { - mocks.getTxEffectOwners.mockResolvedValue([]); - mocks.store.mockReset().mockRejectedValue({ - code: "23505", - detail: "Key (address)=(0x01) already exists.", - }); - - await expect(blockHandler.cb(event, noHeartbeat)).resolves.toBeUndefined(); - - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - expect(mocks.logger.error).toHaveBeenCalledWith( - expect.stringContaining("DB duplicate on an unexpected key"), - ); - }); -}); - -describe("txs held only by orphaned blocks (multi-block reorg)", () => { - it("prunes them and stores the rebuilt block", async () => { - // A reorg at 103157 orphaned 103157-103159; the rebuilt 103158 - // re-includes txs from the old 103158 and 103159. - mocks.getTxEffectOwners.mockResolvedValue([ - owner({ - blockHash: "0xold-103158", - blockHeight: 103158n, - isOrphaned: true, - }), - owner({ - txHash: "0x2ba2", - blockHash: "0xold-103159", - blockHeight: 103159n, - isOrphaned: true, - }), - ]); - - await blockHandler.cb(event, noHeartbeat); - - expect(mocks.deleteL2BlockByHash.mock.calls).toEqual([ - ["0xold-103158"], - ["0xold-103159"], - ]); - expect(mocks.store).toHaveBeenCalledTimes(2); - for (const hook of hooks()) { - expect(hook).toHaveBeenCalledOnce(); - } - }); -}); - -describe("store errors that are not duplicates", () => { - it("are rethrown so the message bus redelivers the block", async () => { - mocks.store.mockReset().mockRejectedValue(new Error("connection reset")); - - await expect(blockHandler.cb(event, noHeartbeat)).rejects.toThrow( - "connection reset", - ); - - expect(mocks.store).toHaveBeenCalledOnce(); - for (const hook of hooks()) { - expect(hook).not.toHaveBeenCalled(); - } - }); -}); diff --git a/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts b/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts new file mode 100644 index 000000000..09e274f03 --- /dev/null +++ b/services/explorer-api/tests/unit/chain-write-heartbeats.test.ts @@ -0,0 +1,85 @@ +import { type HexString } from "@chicmoz-pkg/types"; +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 { removePendingAndDroppedTx } = await import( + "../../src/svcs/database/controllers/l2Tx/remove-pending-and-dropped.js" +); +const { storeBlockContracts } = await import( + "../../src/svcs/database/controllers/l2contract/store.js" +); + +type DbTx = Parameters[0]; + +// A chain change runs these loops inside the chain lock, one statement per +// row: a heartbeat before each keeps the consumer's partition. +describe("the per-row write loops of a chain change", () => { + it("heartbeats before copying each pending tx's fields onto its tx effect", async () => { + const order: string[] = []; + const txHashes: HexString[] = ["0x01", "0x02"]; + let deletes = 0; + const dbTx = { + delete: () => ({ + where: () => ({ + returning: () => + Promise.resolve( + deletes++ === 0 ? txHashes.map((txHash) => ({ txHash })) : [], + ), + }), + }), + update: () => ({ + set: () => ({ + where: () => { + order.push("copy"); + return Promise.resolve(); + }, + }), + }), + } as unknown as DbTx; + + await removePendingAndDroppedTx(dbTx, txHashes, () => { + order.push("beat"); + return Promise.resolve(); + }); + + expect(order).toEqual(["beat", "copy", "beat", "copy"]); + }); + + it("heartbeats before each contract row's savepoint, and lets a failed heartbeat abort the block", async () => { + const order: string[] = []; + const savepoint = { insert: () => ({ values: () => Promise.resolve() }) }; + const dbTx = { + transaction: (write: (executor: unknown) => Promise) => { + order.push("row"); + return write(savepoint); + }, + } as unknown as DbTx; + const contracts = { + classes: [{ contractClassId: "0x0a" }, { contractClassId: "0x0b" }], + instancesDeployed: [{ address: "0x0c" }], + instancesUpdated: [], + } as unknown as Parameters[1]; + + await storeBlockContracts(dbTx, contracts, () => { + order.push("beat"); + return Promise.resolve(); + }); + expect(order).toEqual(["beat", "row", "beat", "row", "beat", "row"]); + + order.length = 0; + await expect( + storeBlockContracts(dbTx, contracts, () => + Promise.reject(new Error("rebalancing")), + ), + ).rejects.toThrow("rebalancing"); + expect(order).toEqual([]); + }); +}); diff --git a/services/explorer-api/tests/unit/duplicate-block-error.test.ts b/services/explorer-api/tests/unit/duplicate-block-error.test.ts deleted file mode 100644 index 5a8fc84e5..000000000 --- a/services/explorer-api/tests/unit/duplicate-block-error.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const mocks = vi.hoisted(() => ({ - error: vi.fn(), - info: vi.fn(), - warn: vi.fn(), -})); - -vi.mock("../../src/logger.js", () => ({ - logger: mocks, -})); - -const { handleDuplicateBlockError } = await import( - "../../src/events/received/utils.js" -); - -const duplicate = (detail: string) => ({ code: "23505", detail }); -const callbacks = (resolves = true) => ({ - deleteIncomingHeight: vi.fn<() => Promise>(() => Promise.resolve()), - unOrphan: vi.fn<() => Promise>(() => Promise.resolve()), - resolveDuplicateTxOwner: vi.fn<() => Promise>(() => - Promise.resolve(resolves), - ), -}); -const handle = ( - error: { code: string; detail: string }, - cb: ReturnType, -) => - handleDuplicateBlockError( - error, - "block 9897", - cb.deleteIncomingHeight, - cb.unOrphan, - cb.resolveDuplicateTxOwner, - ); - -beforeEach(() => { - mocks.error.mockClear(); - mocks.info.mockClear(); - mocks.warn.mockClear(); -}); - -describe("handleDuplicateBlockError", () => { - it("uses the tx owner resolver for duplicate tx_hash errors", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (tx_hash)=(0xabc) already exists."), - cb, - ); - - expect(outcome).toBe("retry"); - expect(cb.resolveDuplicateTxOwner).toHaveBeenCalledOnce(); - expect(cb.deleteIncomingHeight).not.toHaveBeenCalled(); - expect(cb.unOrphan).not.toHaveBeenCalled(); - }); - - it("skips when the tx owner resolver cannot clear the conflict", async () => { - await expect( - handle( - duplicate("Key (tx_hash)=(0xabc) already exists."), - callbacks(false), - ), - ).resolves.toBe("skip"); - }); - - it("keeps the existing height-delete retry path for duplicate height errors", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (height)=(9897) already exists."), - cb, - ); - - expect(outcome).toBe("retry"); - expect(cb.deleteIncomingHeight).toHaveBeenCalledOnce(); - expect(cb.resolveDuplicateTxOwner).not.toHaveBeenCalled(); - }); - - it("un-orphans an existing block with the same hash, which counts as stored", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (hash)=(0x0394) already exists."), - cb, - ); - - expect(outcome).toBe("done"); - expect(cb.unOrphan).toHaveBeenCalledOnce(); - }); - - it("does not count a duplicate on an unexpected key as stored", async () => { - const cb = callbacks(); - - const outcome = await handle( - duplicate("Key (address)=(0x01) already exists."), - cb, - ); - - expect(outcome).toBe("skip"); - expect(mocks.error).toHaveBeenCalledWith( - expect.stringContaining("DB duplicate on an unexpected key"), - ); - expect(cb.unOrphan).not.toHaveBeenCalled(); - expect(cb.deleteIncomingHeight).not.toHaveBeenCalled(); - }); -}); 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 caf240838..379ecdbce 100644 --- a/services/explorer-api/tests/unit/open-gap-scheduler.test.ts +++ b/services/explorer-api/tests/unit/open-gap-scheduler.test.ts @@ -33,6 +33,7 @@ const mocks = vi.hoisted(() => { set: Record; }>, inserted: [] as Array>, + insertStatements: 0, deleted: [] as unknown[], updates: [] as Array>, updateTargets: [] as unknown[][], @@ -98,18 +99,25 @@ const mocks = vi.hoisted(() => { }, }), }), - insert: () => ({ - values: (values: Record) => ({ - onConflictDoUpdate: ({ set }: { set: Record }) => { - state.upserts.push({ values, set }); - return Promise.resolve(); - }, - onConflictDoNothing: () => { - state.inserted.push(values); - return Promise.resolve(); - }, - }), - }), + insert: () => { + state.insertStatements++; + return { + values: ( + values: Record | Record[], + ) => ({ + onConflictDoUpdate: ({ set }: { set: Record }) => { + for (const row of [values].flat()) { + state.upserts.push({ values: row, set }); + } + return Promise.resolve(); + }, + onConflictDoNothing: () => { + state.inserted.push(...[values].flat()); + return Promise.resolve(); + }, + }), + }; + }, update: () => ({ set: (values: Record) => ({ where: (condition: unknown) => { @@ -178,11 +186,13 @@ const { buildTipBoundaryRepairRequest, coverageOf, gapRowMaxWidth, + recordRepairHeights, requestableGapFilter, splitRange, } = await import( "../../src/svcs/database/controllers/l2block/missing-ranges.js" ); +const { getDb } = await import("@chicmoz-pkg/postgres-helper"); const { l2BlockRangeRequest } = await import( "../../src/events/emitted/index.js" ); @@ -225,6 +235,7 @@ beforeEach(() => { presentHeights: heights(1, TIP), upserts: [], inserted: [], + insertStatements: 0, deleted: [], updates: [], updateTargets: [], @@ -642,3 +653,20 @@ describe("buildTipBoundaryRepairRequest", () => { await expect(buildTipBoundaryRepairRequest()).resolves.toBeNull(); }); }); + +describe("recordRepairHeights", () => { + it("records its heights in one statement, once each", async () => { + await recordRepairHeights(getDb(), [5n, 6n, 5n]); + + expect(mocks.state.insertStatements).toBe(1); + expect( + mocks.state.upserts.map(({ values }) => [ + values.reason, + values.fromHeight, + ]), + ).toEqual([ + ["reorg_repair", 5], + ["reorg_repair", 6], + ]); + }); +});