@aztec/archiver 0.0.1-commit.934299a21 → 0.0.1-commit.949a33fd8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +12 -6
  2. package/dest/archiver.d.ts +18 -10
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +146 -57
  5. package/dest/config.d.ts +5 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +16 -4
  8. package/dest/errors.d.ts +61 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +88 -14
  11. package/dest/factory.d.ts +4 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +26 -22
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -1
  17. package/dest/l1/calldata_retriever.d.ts +2 -1
  18. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  19. package/dest/l1/calldata_retriever.js +11 -5
  20. package/dest/l1/data_retrieval.d.ts +24 -12
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +36 -37
  23. package/dest/l1/validate_historical_logs.d.ts +23 -0
  24. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  25. package/dest/l1/validate_historical_logs.js +108 -0
  26. package/dest/modules/data_source_base.d.ts +12 -6
  27. package/dest/modules/data_source_base.d.ts.map +1 -1
  28. package/dest/modules/data_source_base.js +24 -6
  29. package/dest/modules/data_store_updater.d.ts +28 -15
  30. package/dest/modules/data_store_updater.d.ts.map +1 -1
  31. package/dest/modules/data_store_updater.js +102 -80
  32. package/dest/modules/instrumentation.d.ts +7 -2
  33. package/dest/modules/instrumentation.d.ts.map +1 -1
  34. package/dest/modules/instrumentation.js +22 -6
  35. package/dest/modules/l1_synchronizer.d.ts +8 -2
  36. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  37. package/dest/modules/l1_synchronizer.js +292 -144
  38. package/dest/modules/validation.d.ts +4 -3
  39. package/dest/modules/validation.d.ts.map +1 -1
  40. package/dest/modules/validation.js +6 -6
  41. package/dest/store/block_store.d.ts +83 -17
  42. package/dest/store/block_store.d.ts.map +1 -1
  43. package/dest/store/block_store.js +399 -124
  44. package/dest/store/contract_class_store.d.ts +2 -3
  45. package/dest/store/contract_class_store.d.ts.map +1 -1
  46. package/dest/store/contract_class_store.js +7 -67
  47. package/dest/store/contract_instance_store.d.ts +1 -1
  48. package/dest/store/contract_instance_store.d.ts.map +1 -1
  49. package/dest/store/contract_instance_store.js +6 -2
  50. package/dest/store/kv_archiver_store.d.ts +70 -23
  51. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  52. package/dest/store/kv_archiver_store.js +88 -27
  53. package/dest/store/l2_tips_cache.d.ts +2 -1
  54. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  55. package/dest/store/l2_tips_cache.js +27 -7
  56. package/dest/store/log_store.d.ts +6 -3
  57. package/dest/store/log_store.d.ts.map +1 -1
  58. package/dest/store/log_store.js +95 -20
  59. package/dest/store/message_store.d.ts +5 -1
  60. package/dest/store/message_store.d.ts.map +1 -1
  61. package/dest/store/message_store.js +21 -9
  62. package/dest/test/fake_l1_state.d.ts +20 -1
  63. package/dest/test/fake_l1_state.d.ts.map +1 -1
  64. package/dest/test/fake_l1_state.js +114 -18
  65. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  66. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  67. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  68. package/dest/test/mock_l2_block_source.d.ts +19 -4
  69. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  70. package/dest/test/mock_l2_block_source.js +57 -7
  71. package/dest/test/mock_structs.d.ts +4 -1
  72. package/dest/test/mock_structs.d.ts.map +1 -1
  73. package/dest/test/mock_structs.js +13 -1
  74. package/dest/test/noop_l1_archiver.d.ts +4 -1
  75. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  76. package/dest/test/noop_l1_archiver.js +9 -3
  77. package/package.json +13 -13
  78. package/src/archiver.ts +179 -56
  79. package/src/config.ts +23 -2
  80. package/src/errors.ts +133 -22
  81. package/src/factory.ts +24 -15
  82. package/src/index.ts +2 -1
  83. package/src/l1/calldata_retriever.ts +17 -5
  84. package/src/l1/data_retrieval.ts +52 -53
  85. package/src/l1/validate_historical_logs.ts +140 -0
  86. package/src/modules/data_source_base.ts +43 -7
  87. package/src/modules/data_store_updater.ts +126 -109
  88. package/src/modules/instrumentation.ts +27 -7
  89. package/src/modules/l1_synchronizer.ts +371 -178
  90. package/src/modules/validation.ts +10 -9
  91. package/src/store/block_store.ts +489 -143
  92. package/src/store/contract_class_store.ts +8 -106
  93. package/src/store/contract_instance_store.ts +8 -5
  94. package/src/store/kv_archiver_store.ts +133 -39
  95. package/src/store/l2_tips_cache.ts +58 -13
  96. package/src/store/log_store.ts +128 -32
  97. package/src/store/message_store.ts +27 -10
  98. package/src/structs/inbox_message.ts +1 -1
  99. package/src/test/fake_l1_state.ts +142 -29
  100. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  101. package/src/test/mock_l2_block_source.ts +73 -5
  102. package/src/test/mock_structs.ts +20 -6
  103. package/src/test/noop_l1_archiver.ts +10 -2
@@ -0,0 +1,140 @@
1
+ import { getPublicClient, getRpcUrlsFromClient } from '@aztec/ethereum/client';
2
+ import { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
4
+ import type { ViemPublicClient } from '@aztec/ethereum/types';
5
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
6
+
7
+ /** Subset of L1 contract addresses whose historical logs the Aztec node relies on. */
8
+ export type HistoricalLogsContractAddresses = Pick<
9
+ L1ContractAddresses,
10
+ 'rollupAddress' | 'inboxAddress' | 'registryAddress' | 'governanceProposerAddress'
11
+ >;
12
+
13
+ /** Result of probing a single RPC URL. */
14
+ type ProbeResult = { ok: true } | { ok: false; reason: string; clientVersion: string | undefined };
15
+
16
+ /**
17
+ * Validates that every configured L1 RPC URL returns historical logs for the Rollup contract.
18
+ *
19
+ * Some RPC providers prune old logs, which would cause L1 syncing to silently fail. To detect this,
20
+ * we query for the `OwnershipTransferred` event which every Rollup emits in its constructor (via
21
+ * Ownable) on the block it was deployed (`l1StartBlock`). The `client` is typically a viem fallback
22
+ * transport over several user-configured RPC URLs — checking only the first URL would miss a bad
23
+ * secondary, so we probe each URL independently. The first URL that fails aborts startup, unless
24
+ * the operator has explicitly opted out.
25
+ *
26
+ * @param client - The L1 public client built from the user-configured RPC URLs.
27
+ * @param addresses - The subset of L1 contract addresses we rely on for historical log retrieval.
28
+ * @param skipCheck - If true, log warnings instead of throwing.
29
+ * @param bindings - Optional logger bindings for context.
30
+ * @throws Error if any URL fails the probe and skipCheck is false.
31
+ */
32
+ export async function validateAndLogHistoricalLogsAvailability(
33
+ client: ViemPublicClient,
34
+ addresses: HistoricalLogsContractAddresses,
35
+ skipCheck: boolean,
36
+ bindings?: LoggerBindings,
37
+ ): Promise<void> {
38
+ const logger = createLogger('archiver:validate_historical_logs', bindings);
39
+ logger.debug('Validating historical log availability on L1 RPCs');
40
+
41
+ const urls = getRpcUrlsFromClient(client);
42
+ if (urls.length === 0) {
43
+ logger.warn('Could not determine L1 RPC URLs from the public client; skipping historical logs check.');
44
+ return;
45
+ }
46
+
47
+ const chainId = client.chain?.id;
48
+ if (chainId === undefined) {
49
+ logger.warn('Could not determine L1 chain ID from the public client; skipping historical logs check.');
50
+ return;
51
+ }
52
+
53
+ for (const url of urls) {
54
+ const probeClient = getPublicClient({ l1RpcUrls: [url], l1ChainId: chainId });
55
+ const rollup = new RollupContract(probeClient, addresses.rollupAddress.toString());
56
+ const result = await probeRpcUrl(rollup, probeClient, logger);
57
+
58
+ if (result.ok) {
59
+ logger.debug(`L1 RPC ${url} returned historical OwnershipTransferred log for the Rollup contract.`);
60
+ continue;
61
+ }
62
+
63
+ const errorMessage = buildErrorMessage(url, result, addresses);
64
+ if (skipCheck) {
65
+ logger.warn(`${errorMessage}\nContinuing because ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK is true.`);
66
+ continue;
67
+ }
68
+
69
+ logger.error(errorMessage);
70
+ throw new Error(errorMessage);
71
+ }
72
+ }
73
+
74
+ /** Runs the OwnershipTransferred probe against a single RPC and queries its client version. */
75
+ async function probeRpcUrl(rollup: RollupContract, client: ViemPublicClient, logger: Logger): Promise<ProbeResult> {
76
+ let queryError: unknown;
77
+ try {
78
+ const logs = await rollup.getOwnershipTransferredEventsAtDeploy();
79
+ if (logs.length > 0) {
80
+ return { ok: true };
81
+ }
82
+ } catch (err) {
83
+ queryError = err;
84
+ }
85
+
86
+ const clientVersion = await getClientVersion(client, logger);
87
+
88
+ let reason: string;
89
+ if (queryError instanceof Error) {
90
+ reason = `Query for historical logs failed: ${queryError.message}`;
91
+ } else if (queryError !== undefined) {
92
+ reason = 'Query for historical logs failed with a non-Error value.';
93
+ } else {
94
+ reason = 'No OwnershipTransferred event was returned by the L1 RPC for the Rollup deploy block.';
95
+ }
96
+ return { ok: false, reason, clientVersion };
97
+ }
98
+
99
+ /** Builds the operator-facing error message for a failing RPC URL. */
100
+ function buildErrorMessage(
101
+ url: string,
102
+ result: Extract<ProbeResult, { ok: false }>,
103
+ addresses: HistoricalLogsContractAddresses,
104
+ ): string {
105
+ return [
106
+ `L1 RPC at ${url} does not return historical logs for the Rollup contract. ${result.reason}`,
107
+ `This likely means this Ethereum RPC node prunes old logs, which would cause the archiver ` +
108
+ `to silently miss data during L1 sync.`,
109
+ result.clientVersion
110
+ ? `Detected L1 client version for ${url}: ${result.clientVersion}.`
111
+ : `Could not determine L1 client version for ${url}.`,
112
+ `The following L1 contract addresses must have their historical logs retained by the RPC node:`,
113
+ ` - Rollup: ${addresses.rollupAddress.toString()}`,
114
+ ` - Inbox: ${addresses.inboxAddress.toString()}`,
115
+ ` - Registry: ${addresses.registryAddress.toString()}`,
116
+ ` - GovernanceProposer: ${addresses.governanceProposerAddress.toString()}`,
117
+ isReth(result.clientVersion)
118
+ ? `To retain logs for these contracts, configure reth with a ` +
119
+ `prune.segments.receipts_log_filter entry for each address above ` +
120
+ `so reth does not prune their receipts/logs. See https://reth.rs/run/pruning.html for details.`
121
+ : `Point this RPC endpoint at a node that retains full log history for the addresses above.`,
122
+ `Set ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK=true to bypass this check at your own risk.`,
123
+ ].join('\n');
124
+ }
125
+
126
+ /** Queries `web3_clientVersion` on the L1 RPC. Returns undefined if the call fails or returns a non-string. */
127
+ async function getClientVersion(client: ViemPublicClient, logger: Logger): Promise<string | undefined> {
128
+ try {
129
+ const result = await client.request({ method: 'web3_clientVersion' });
130
+ return typeof result === 'string' ? result : undefined;
131
+ } catch (err) {
132
+ logger.debug(`Failed to query web3_clientVersion: ${err instanceof Error ? err.message : err}`);
133
+ return undefined;
134
+ }
135
+ }
136
+
137
+ /** Heuristic check for reth based on the web3_clientVersion string (reth returns e.g. "reth/v1.0.0-..."). */
138
+ function isReth(clientVersion: string | undefined): boolean {
139
+ return !!clientVersion && /reth/i.test(clientVersion);
140
+ }
@@ -6,7 +6,13 @@ import { isDefined } from '@aztec/foundation/types';
6
6
  import type { FunctionSelector } from '@aztec/stdlib/abi';
7
7
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
8
8
  import { type BlockData, type BlockHash, CheckpointedL2Block, L2Block, type L2Tips } from '@aztec/stdlib/block';
9
- import { Checkpoint, type CheckpointData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
+ import {
10
+ Checkpoint,
11
+ type CheckpointData,
12
+ type CommonCheckpointData,
13
+ type ProposedCheckpointData,
14
+ PublishedCheckpoint,
15
+ } from '@aztec/stdlib/checkpoint';
10
16
  import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/stdlib/contract';
11
17
  import { type L1RollupConstants, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
12
18
  import type { GetContractClassLogsResponse, GetPublicLogsResponse } from '@aztec/stdlib/interfaces/client';
@@ -46,9 +52,9 @@ export abstract class ArchiverDataSourceBase
46
52
 
47
53
  abstract getL2Tips(): Promise<L2Tips>;
48
54
 
49
- abstract getL2SlotNumber(): Promise<SlotNumber | undefined>;
55
+ abstract getSyncedL2SlotNumber(): Promise<SlotNumber | undefined>;
50
56
 
51
- abstract getL2EpochNumber(): Promise<EpochNumber | undefined>;
57
+ abstract getSyncedL2EpochNumber(): Promise<EpochNumber | undefined>;
52
58
 
53
59
  abstract isEpochComplete(epochNumber: EpochNumber): Promise<boolean>;
54
60
 
@@ -121,6 +127,22 @@ export abstract class ArchiverDataSourceBase
121
127
  return this.store.getCheckpointedBlocks(from, limit);
122
128
  }
123
129
 
130
+ public getCheckpointData(checkpointNumber: CheckpointNumber): Promise<CheckpointData | undefined> {
131
+ return this.store.getCheckpointData(checkpointNumber);
132
+ }
133
+
134
+ public getCheckpointDataRange(from: CheckpointNumber, limit: number): Promise<CheckpointData[]> {
135
+ return this.store.getCheckpointDataRange(from, limit);
136
+ }
137
+
138
+ public getCheckpointNumberBySlot(slot: SlotNumber): Promise<CheckpointNumber | undefined> {
139
+ return this.store.getCheckpointNumberBySlot(slot);
140
+ }
141
+
142
+ public getBlockDataWithCheckpointContext(blockNumber: BlockNumber) {
143
+ return this.store.getBlockDataWithCheckpointContext(blockNumber);
144
+ }
145
+
124
146
  public getBlockHeaderByHash(blockHash: BlockHash): Promise<BlockHeader | undefined> {
125
147
  return this.store.getBlockHeaderByHash(blockHash);
126
148
  }
@@ -154,7 +176,15 @@ export abstract class ArchiverDataSourceBase
154
176
  }
155
177
 
156
178
  public getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
157
- return this.store.getSettledTxReceipt(txHash);
179
+ return this.store.getSettledTxReceipt(txHash, this.l1Constants);
180
+ }
181
+
182
+ public getLastCheckpoint(): Promise<CommonCheckpointData | undefined> {
183
+ return this.store.getLastCheckpoint();
184
+ }
185
+
186
+ public getLastProposedCheckpoint(): Promise<ProposedCheckpointData | undefined> {
187
+ return this.store.getLastProposedCheckpoint();
158
188
  }
159
189
 
160
190
  public isPendingChainInvalid(): Promise<boolean> {
@@ -165,16 +195,21 @@ export abstract class ArchiverDataSourceBase
165
195
  return (await this.store.getPendingChainValidationStatus()) ?? { valid: true };
166
196
  }
167
197
 
168
- public getPrivateLogsByTags(tags: SiloedTag[], page?: number): Promise<TxScopedL2Log[][]> {
169
- return this.store.getPrivateLogsByTags(tags, page);
198
+ public getPrivateLogsByTags(
199
+ tags: SiloedTag[],
200
+ page?: number,
201
+ upToBlockNumber?: BlockNumber,
202
+ ): Promise<TxScopedL2Log[][]> {
203
+ return this.store.getPrivateLogsByTags(tags, page, upToBlockNumber);
170
204
  }
171
205
 
172
206
  public getPublicLogsByTagsFromContract(
173
207
  contractAddress: AztecAddress,
174
208
  tags: Tag[],
175
209
  page?: number,
210
+ upToBlockNumber?: BlockNumber,
176
211
  ): Promise<TxScopedL2Log[][]> {
177
- return this.store.getPublicLogsByTagsFromContract(contractAddress, tags, page);
212
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
178
213
  }
179
214
 
180
215
  public getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
@@ -244,6 +279,7 @@ export abstract class ArchiverDataSourceBase
244
279
  checkpoint.header,
245
280
  blocksForCheckpoint,
246
281
  checkpoint.checkpointNumber,
282
+ checkpoint.feeAssetPriceModifier,
247
283
  );
248
284
  return new PublishedCheckpoint(fullCheckpoint, checkpoint.l1, checkpoint.attestations);
249
285
  }
@@ -1,29 +1,26 @@
1
1
  import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
- import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { filterAsync } from '@aztec/foundation/collection';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
- import {
5
- ContractClassPublishedEvent,
6
- PrivateFunctionBroadcastedEvent,
7
- UtilityFunctionBroadcastedEvent,
8
- } from '@aztec/protocol-contracts/class-registry';
4
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
9
5
  import {
10
6
  ContractInstancePublishedEvent,
11
7
  ContractInstanceUpdatedEvent,
12
8
  } from '@aztec/protocol-contracts/instance-registry';
13
- import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
9
+ import type { CommitteeAttestation, L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
10
+ import {
11
+ type L1PublishedData,
12
+ type ProposedCheckpointInput,
13
+ type PublishedCheckpoint,
14
+ validateCheckpoint,
15
+ } from '@aztec/stdlib/checkpoint';
15
16
  import {
16
- type ExecutablePrivateFunctionWithMembershipProof,
17
- type UtilityFunctionWithMembershipProof,
18
- computePublicBytecodeCommitment,
19
- isValidPrivateFunctionMembershipProof,
20
- isValidUtilityFunctionMembershipProof,
17
+ type ContractClassPublicWithCommitment,
18
+ computeContractAddressFromInstance,
19
+ computeContractClassId,
21
20
  } from '@aztec/stdlib/contract';
22
21
  import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
22
  import type { UInt64 } from '@aztec/stdlib/types';
24
23
 
25
- import groupBy from 'lodash.groupby';
26
-
27
24
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
28
25
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
29
26
 
@@ -48,32 +45,32 @@ export class ArchiverDataStoreUpdater {
48
45
  constructor(
49
46
  private store: KVArchiverDataStore,
50
47
  private l2TipsCache?: L2TipsCache,
48
+ private opts: { rollupManaLimit?: number } = {},
51
49
  ) {}
52
50
 
53
51
  /**
54
- * Adds proposed blocks to the store with contract class/instance extraction from logs.
55
- * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
56
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
57
- * and individually broadcasted functions from the block logs.
52
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
53
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
54
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
58
55
  *
59
- * @param blocks - The proposed L2 blocks to add.
56
+ * @param block - The proposed L2 block to add.
60
57
  * @param pendingChainValidationStatus - Optional validation status to set.
61
58
  * @returns True if the operation is successful.
62
59
  */
63
- public async addProposedBlocks(
64
- blocks: L2Block[],
60
+ public async addProposedBlock(
61
+ block: L2Block,
65
62
  pendingChainValidationStatus?: ValidateCheckpointResult,
66
63
  ): Promise<boolean> {
67
64
  const result = await this.store.transactionAsync(async () => {
68
- await this.store.addProposedBlocks(blocks);
65
+ await this.store.addProposedBlock(block);
69
66
 
70
67
  const opResults = await Promise.all([
71
68
  // Update the pending chain validation status if provided
72
69
  pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
73
- // Add any logs emitted during the retrieved blocks
74
- this.store.addLogs(blocks),
75
- // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
76
- ...blocks.map(block => this.addContractDataToDb(block)),
70
+ // Add any logs emitted during the retrieved block
71
+ this.store.addLogs([block]),
72
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
73
+ this.addContractDataToDb(block),
77
74
  ]);
78
75
 
79
76
  await this.l2TipsCache?.refresh();
@@ -86,24 +83,39 @@ export class ArchiverDataStoreUpdater {
86
83
  * Reconciles local blocks with incoming checkpoints from L1.
87
84
  * Adds new checkpoints to the store with contract class/instance extraction from logs.
88
85
  * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
89
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
90
- * and individually broadcasted functions from the checkpoint block logs.
86
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
87
+ * If `promoteProposed` is supplied, the proposed-checkpoint promotion runs inside the same transaction
88
+ * as the added checkpoints so both updates are applied atomically.
91
89
  *
92
- * @param checkpoints - The published checkpoints to add.
90
+ * @param checkpoints - The published checkpoints to add (excluding any being promoted from proposed).
93
91
  * @param pendingChainValidationStatus - Optional validation status to set.
92
+ * @param promoteProposed - Optional promotion of the current proposed checkpoint (fast path when blocks are already local).
94
93
  * @returns Result with information about any pruned blocks.
95
94
  */
96
95
  public async addCheckpoints(
97
96
  checkpoints: PublishedCheckpoint[],
98
97
  pendingChainValidationStatus?: ValidateCheckpointResult,
98
+ promoteProposed?: {
99
+ l1: L1PublishedData;
100
+ attestations: CommitteeAttestation[];
101
+ checkpoint: PublishedCheckpoint;
102
+ },
103
+ evictProposedFrom?: CheckpointNumber,
99
104
  ): Promise<ReconcileCheckpointsResult> {
105
+ for (const checkpoint of checkpoints) {
106
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
107
+ }
108
+ if (promoteProposed) {
109
+ validateCheckpoint(promoteProposed.checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
110
+ }
111
+
100
112
  const result = await this.store.transactionAsync(async () => {
101
113
  // Before adding checkpoints, check for conflicts with local blocks if any
102
114
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
103
115
 
104
116
  await this.store.addCheckpoints(checkpoints);
105
117
 
106
- // Filter out blocks that were already inserted via addProposedBlocks() to avoid duplicating logs/contract data
118
+ // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
107
119
  const newBlocks = checkpoints
108
120
  .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
109
121
  .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
@@ -115,6 +127,17 @@ export class ArchiverDataStoreUpdater {
115
127
  this.store.addLogs(newBlocks),
116
128
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
117
129
  ...newBlocks.map(block => this.addContractDataToDb(block)),
130
+ // Promote the proposed checkpoint if requested (uses explicit checkpoint number)
131
+ promoteProposed
132
+ ? this.store.promoteProposedToCheckpointed(
133
+ promoteProposed.checkpoint.checkpoint.number,
134
+ promoteProposed.l1,
135
+ promoteProposed.attestations,
136
+ promoteProposed.checkpoint.checkpoint.archive.root,
137
+ )
138
+ : undefined,
139
+ // Evict pending checkpoints that diverged from what L1 mined
140
+ evictProposedFrom !== undefined ? this.store.evictProposedCheckpointsFrom(evictProposedFrom) : undefined,
118
141
  ]);
119
142
 
120
143
  await this.l2TipsCache?.refresh();
@@ -123,6 +146,15 @@ export class ArchiverDataStoreUpdater {
123
146
  return result;
124
147
  }
125
148
 
149
+ public async addProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
150
+ const result = await this.store.transactionAsync(async () => {
151
+ await this.store.addProposedCheckpoint(proposedCheckpoint);
152
+ await this.l2TipsCache?.refresh();
153
+ });
154
+
155
+ return result;
156
+ }
157
+
126
158
  /**
127
159
  * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
128
160
  * This method handles multiple checkpoints but returns after pruning the first conflict found.
@@ -173,7 +205,7 @@ export class ArchiverDataStoreUpdater {
173
205
  this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
174
206
  lastAlreadyInsertedBlockNumber = blockNumber;
175
207
  } else {
176
- this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
208
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
177
209
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
178
210
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
179
211
  }
@@ -216,6 +248,10 @@ export class ArchiverDataStoreUpdater {
216
248
  }
217
249
 
218
250
  const result = await this.removeBlocksAfter(blockNumber);
251
+
252
+ // Clear all pending proposed checkpoints since their blocks have been pruned
253
+ await this.store.deleteProposedCheckpoints();
254
+
219
255
  await this.l2TipsCache?.refresh();
220
256
  return result;
221
257
  });
@@ -276,6 +312,17 @@ export class ArchiverDataStoreUpdater {
276
312
  });
277
313
  }
278
314
 
315
+ /**
316
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
317
+ * @param checkpointNumber - The checkpoint number to set as finalized.
318
+ */
319
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
320
+ await this.store.transactionAsync(async () => {
321
+ await this.store.setFinalizedCheckpointNumber(checkpointNumber);
322
+ await this.l2TipsCache?.refresh();
323
+ });
324
+ }
325
+
279
326
  /** Extracts and stores contract data from a single block. */
280
327
  private addContractDataToDb(block: L2Block): Promise<boolean> {
281
328
  return this.updateContractDataOnDb(block, Operation.Store);
@@ -297,9 +344,6 @@ export class ArchiverDataStoreUpdater {
297
344
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
298
345
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
299
346
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
300
- operation === Operation.Store
301
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
302
- : Promise.resolve(true),
303
347
  ])
304
348
  ).every(Boolean);
305
349
  }
@@ -316,18 +360,37 @@ export class ArchiverDataStoreUpdater {
316
360
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
317
361
  .map(log => ContractClassPublishedEvent.fromLog(log));
318
362
 
319
- const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
320
- if (contractClasses.length > 0) {
321
- contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
322
- if (operation == Operation.Store) {
323
- // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
324
- const commitments = await Promise.all(
325
- contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
326
- );
327
- return await this.store.addContractClasses(contractClasses, commitments, blockNum);
328
- } else if (operation == Operation.Delete) {
363
+ if (operation == Operation.Delete) {
364
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
365
+ if (contractClasses.length > 0) {
366
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
329
367
  return await this.store.deleteContractClasses(contractClasses, blockNum);
330
368
  }
369
+ return true;
370
+ }
371
+
372
+ // Compute bytecode commitments and validate class IDs in a single pass.
373
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
374
+ for (const event of contractClassPublishedEvents) {
375
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
376
+ const computedClassId = await computeContractClassId({
377
+ artifactHash: contractClass.artifactHash,
378
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
379
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
380
+ });
381
+ if (!computedClassId.equals(contractClass.id)) {
382
+ this.log.warn(
383
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
384
+ { blockNum, contractClassId: event.contractClassId.toString() },
385
+ );
386
+ continue;
387
+ }
388
+ contractClasses.push(contractClass);
389
+ }
390
+
391
+ if (contractClasses.length > 0) {
392
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
393
+ return await this.store.addContractClasses(contractClasses, blockNum);
331
394
  }
332
395
  return true;
333
396
  }
@@ -340,10 +403,27 @@ export class ArchiverDataStoreUpdater {
340
403
  blockNum: BlockNumber,
341
404
  operation: Operation,
342
405
  ): Promise<boolean> {
343
- const contractInstances = allLogs
406
+ const allInstances = allLogs
344
407
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
345
408
  .map(log => ContractInstancePublishedEvent.fromLog(log))
346
409
  .map(e => e.toContractInstance());
410
+
411
+ // Verify that each instance's address matches the one derived from its fields if we're adding
412
+ const contractInstances =
413
+ operation === Operation.Delete
414
+ ? allInstances
415
+ : await filterAsync(allInstances, async instance => {
416
+ const computedAddress = await computeContractAddressFromInstance(instance);
417
+ if (!computedAddress.equals(instance.address)) {
418
+ this.log.warn(
419
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
420
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
421
+ );
422
+ return false;
423
+ }
424
+ return true;
425
+ });
426
+
347
427
  if (contractInstances.length > 0) {
348
428
  contractInstances.forEach(c =>
349
429
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
@@ -382,67 +462,4 @@ export class ArchiverDataStoreUpdater {
382
462
  }
383
463
  return true;
384
464
  }
385
-
386
- /**
387
- * Stores the functions that were broadcasted individually.
388
- *
389
- * @dev Beware that there is not a delete variant of this, since they are added to contract classes
390
- * and will be deleted as part of the class if needed.
391
- */
392
- private async storeBroadcastedIndividualFunctions(
393
- allLogs: ContractClassLog[],
394
- _blockNum: BlockNumber,
395
- ): Promise<boolean> {
396
- // Filter out private and utility function broadcast events
397
- const privateFnEvents = allLogs
398
- .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
399
- .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
400
- const utilityFnEvents = allLogs
401
- .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
402
- .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
403
-
404
- // Group all events by contract class id
405
- for (const [classIdString, classEvents] of Object.entries(
406
- groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
407
- )) {
408
- const contractClassId = Fr.fromHexString(classIdString);
409
- const contractClass = await this.store.getContractClass(contractClassId);
410
- if (!contractClass) {
411
- this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
412
- continue;
413
- }
414
-
415
- // Split private and utility functions, and filter out invalid ones
416
- const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
417
- const privateFns = allFns.filter(
418
- (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
419
- );
420
- const utilityFns = allFns.filter(
421
- (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
422
- );
423
-
424
- const privateFunctionsWithValidity = await Promise.all(
425
- privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
426
- );
427
- const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
428
- const utilityFunctionsWithValidity = await Promise.all(
429
- utilityFns.map(async fn => ({
430
- fn,
431
- valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
432
- })),
433
- );
434
- const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
435
- const validFnCount = validPrivateFns.length + validUtilityFns.length;
436
- if (validFnCount !== allFns.length) {
437
- this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
438
- }
439
-
440
- // Store the functions in the contract class in a single operation
441
- if (validFnCount > 0) {
442
- this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
443
- }
444
- return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
445
- }
446
- return true;
447
- }
448
465
  }
@@ -32,6 +32,7 @@ export class ArchiverInstrumentation {
32
32
  private pruneCount: UpDownCounter;
33
33
 
34
34
  private syncDurationPerBlock: Histogram;
35
+ private syncDurationPerCheckpoint: Histogram;
35
36
  private syncBlockCount: UpDownCounter;
36
37
  private manaPerBlock: Histogram;
37
38
  private txsPerBlock: Histogram;
@@ -42,6 +43,7 @@ export class ArchiverInstrumentation {
42
43
  private blockProposalTxTargetCount: UpDownCounter;
43
44
 
44
45
  private checkpointL1InclusionDelay: Histogram;
46
+ private checkpointPromotedCount: UpDownCounter;
45
47
 
46
48
  private log = createLogger('archiver:instrumentation');
47
49
 
@@ -68,6 +70,8 @@ export class ArchiverInstrumentation {
68
70
 
69
71
  this.syncDurationPerBlock = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_BLOCK);
70
72
 
73
+ this.syncDurationPerCheckpoint = meter.createHistogram(Metrics.ARCHIVER_SYNC_PER_CHECKPOINT);
74
+
71
75
  this.syncBlockCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_SYNC_BLOCK_COUNT);
72
76
 
73
77
  this.manaPerBlock = meter.createHistogram(Metrics.ARCHIVER_MANA_PER_BLOCK);
@@ -92,6 +96,8 @@ export class ArchiverInstrumentation {
92
96
 
93
97
  this.checkpointL1InclusionDelay = meter.createHistogram(Metrics.ARCHIVER_CHECKPOINT_L1_INCLUSION_DELAY);
94
98
 
99
+ this.checkpointPromotedCount = createUpDownCounterWithDefault(meter, Metrics.ARCHIVER_CHECKPOINT_PROMOTED_COUNT);
100
+
95
101
  this.dbMetrics = new LmdbMetrics(
96
102
  meter,
97
103
  {
@@ -113,17 +119,26 @@ export class ArchiverInstrumentation {
113
119
  return this.telemetry.isEnabled();
114
120
  }
115
121
 
116
- public processNewBlocks(syncTimePerBlock: number, blocks: L2Block[]) {
122
+ public processNewProposedBlock(syncTimePerBlock: number, block: L2Block) {
123
+ const attrs = { [Attributes.STATUS]: 'proposed' };
124
+ this.blockHeight.record(block.number, attrs);
117
125
  this.syncDurationPerBlock.record(Math.ceil(syncTimePerBlock));
126
+
127
+ // Per block metrics
128
+ this.txCount.add(block.body.txEffects.length);
129
+ this.txsPerBlock.record(block.body.txEffects.length);
130
+ this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
131
+ }
132
+
133
+ public processNewCheckpointedBlocks(syncTimePerCheckpoint: number, blocks: L2Block[]) {
134
+ if (blocks.length === 0) {
135
+ return;
136
+ }
137
+
138
+ this.syncDurationPerCheckpoint.record(Math.ceil(syncTimePerCheckpoint));
118
139
  this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
119
140
  this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
120
141
  this.syncBlockCount.add(blocks.length);
121
-
122
- for (const block of blocks) {
123
- this.txCount.add(block.body.txEffects.length);
124
- this.txsPerBlock.record(block.body.txEffects.length);
125
- this.manaPerBlock.record(block.header.totalManaUsed.toNumber() / 1e6);
126
- }
127
142
  }
128
143
 
129
144
  public processNewMessages(count: number, syncPerMessageMs: number) {
@@ -169,6 +184,11 @@ export class ArchiverInstrumentation {
169
184
  });
170
185
  }
171
186
 
187
+ /** Records a checkpoint promoted from proposed (blob fetch skipped). */
188
+ public processCheckpointPromoted() {
189
+ this.checkpointPromotedCount.add(1);
190
+ }
191
+
172
192
  /**
173
193
  * Records L1 inclusion timing for a checkpoint observed on L1 (seconds into the L2 slot).
174
194
  */