@aztec/archiver 5.0.0-private.20260319 → 5.0.0-rc.2

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 (121) hide show
  1. package/README.md +19 -13
  2. package/dest/archiver.d.ts +71 -15
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +268 -74
  5. package/dest/config.d.ts +7 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +39 -16
  8. package/dest/errors.d.ts +44 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +66 -12
  11. package/dest/factory.d.ts +12 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +40 -25
  14. package/dest/index.d.ts +11 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -2
  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 +15 -5
  20. package/dest/l1/data_retrieval.d.ts +19 -10
  21. package/dest/l1/data_retrieval.d.ts.map +1 -1
  22. package/dest/l1/data_retrieval.js +25 -32
  23. package/dest/l1/trace_tx.d.ts +12 -66
  24. package/dest/l1/trace_tx.d.ts.map +1 -1
  25. package/dest/l1/validate_historical_logs.d.ts +23 -0
  26. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  27. package/dest/l1/validate_historical_logs.js +108 -0
  28. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  29. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  30. package/dest/modules/contract_data_source_adapter.js +32 -0
  31. package/dest/modules/data_source_base.d.ts +72 -48
  32. package/dest/modules/data_source_base.d.ts.map +1 -1
  33. package/dest/modules/data_source_base.js +266 -143
  34. package/dest/modules/data_store_updater.d.ts +30 -13
  35. package/dest/modules/data_store_updater.d.ts.map +1 -1
  36. package/dest/modules/data_store_updater.js +172 -117
  37. package/dest/modules/instrumentation.d.ts +7 -2
  38. package/dest/modules/instrumentation.d.ts.map +1 -1
  39. package/dest/modules/instrumentation.js +25 -7
  40. package/dest/modules/l1_synchronizer.d.ts +11 -6
  41. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  42. package/dest/modules/l1_synchronizer.js +437 -217
  43. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  44. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  45. package/dest/modules/outbox_trees_resolver.js +162 -0
  46. package/dest/modules/validation.d.ts +24 -5
  47. package/dest/modules/validation.d.ts.map +1 -1
  48. package/dest/modules/validation.js +40 -15
  49. package/dest/store/block_store.d.ts +164 -66
  50. package/dest/store/block_store.d.ts.map +1 -1
  51. package/dest/store/block_store.js +638 -233
  52. package/dest/store/contract_class_store.d.ts +17 -4
  53. package/dest/store/contract_class_store.d.ts.map +1 -1
  54. package/dest/store/contract_class_store.js +36 -68
  55. package/dest/store/contract_instance_store.d.ts +28 -1
  56. package/dest/store/contract_instance_store.d.ts.map +1 -1
  57. package/dest/store/contract_instance_store.js +48 -2
  58. package/dest/store/data_stores.d.ts +68 -0
  59. package/dest/store/data_stores.d.ts.map +1 -0
  60. package/dest/store/data_stores.js +54 -0
  61. package/dest/store/function_names_cache.d.ts +17 -0
  62. package/dest/store/function_names_cache.d.ts.map +1 -0
  63. package/dest/store/function_names_cache.js +30 -0
  64. package/dest/store/l2_tips_cache.d.ts +13 -7
  65. package/dest/store/l2_tips_cache.d.ts.map +1 -1
  66. package/dest/store/l2_tips_cache.js +13 -76
  67. package/dest/store/log_store.d.ts +42 -40
  68. package/dest/store/log_store.d.ts.map +1 -1
  69. package/dest/store/log_store.js +257 -480
  70. package/dest/store/log_store_codec.d.ts +78 -0
  71. package/dest/store/log_store_codec.d.ts.map +1 -0
  72. package/dest/store/log_store_codec.js +110 -0
  73. package/dest/store/message_store.d.ts +9 -3
  74. package/dest/store/message_store.d.ts.map +1 -1
  75. package/dest/store/message_store.js +39 -10
  76. package/dest/test/fake_l1_state.d.ts +15 -3
  77. package/dest/test/fake_l1_state.d.ts.map +1 -1
  78. package/dest/test/fake_l1_state.js +80 -18
  79. package/dest/test/mock_l2_block_source.d.ts +48 -50
  80. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  81. package/dest/test/mock_l2_block_source.js +223 -179
  82. package/dest/test/mock_structs.d.ts +1 -1
  83. package/dest/test/mock_structs.d.ts.map +1 -1
  84. package/dest/test/mock_structs.js +2 -2
  85. package/dest/test/noop_l1_archiver.d.ts +14 -6
  86. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  87. package/dest/test/noop_l1_archiver.js +25 -9
  88. package/package.json +14 -14
  89. package/src/archiver.ts +353 -80
  90. package/src/config.ts +43 -20
  91. package/src/errors.ts +103 -18
  92. package/src/factory.ts +56 -24
  93. package/src/index.ts +18 -2
  94. package/src/l1/calldata_retriever.ts +16 -5
  95. package/src/l1/data_retrieval.ts +38 -46
  96. package/src/l1/validate_historical_logs.ts +140 -0
  97. package/src/modules/contract_data_source_adapter.ts +46 -0
  98. package/src/modules/data_source_base.ts +340 -189
  99. package/src/modules/data_store_updater.ts +211 -148
  100. package/src/modules/instrumentation.ts +28 -8
  101. package/src/modules/l1_synchronizer.ts +583 -255
  102. package/src/modules/outbox_trees_resolver.ts +199 -0
  103. package/src/modules/validation.ts +81 -21
  104. package/src/store/block_store.ts +792 -285
  105. package/src/store/contract_class_store.ts +43 -103
  106. package/src/store/contract_instance_store.ts +62 -5
  107. package/src/store/data_stores.ts +104 -0
  108. package/src/store/function_names_cache.ts +37 -0
  109. package/src/store/l2_tips_cache.ts +16 -70
  110. package/src/store/log_store.ts +296 -652
  111. package/src/store/log_store_codec.ts +143 -0
  112. package/src/store/message_store.ts +43 -12
  113. package/src/structs/inbox_message.ts +1 -1
  114. package/src/test/fake_l1_state.ts +99 -27
  115. package/src/test/mock_l2_block_source.ts +279 -233
  116. package/src/test/mock_structs.ts +5 -2
  117. package/src/test/noop_l1_archiver.ts +52 -9
  118. package/dest/store/kv_archiver_store.d.ts +0 -367
  119. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  120. package/dest/store/kv_archiver_store.js +0 -481
  121. package/src/store/kv_archiver_store.ts +0 -697
@@ -1,30 +1,28 @@
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, validateCheckpoint } 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';
21
+ import { MAX_CAPACITY_BLOCKS_PER_CHECKPOINT } from '@aztec/stdlib/deserialization';
22
22
  import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
23
  import type { UInt64 } from '@aztec/stdlib/types';
24
24
 
25
- import groupBy from 'lodash.groupby';
26
-
27
- import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
25
+ import type { ArchiverDataStores } from '../store/data_stores.js';
28
26
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
29
27
 
30
28
  /** Operation type for contract data updates. */
@@ -46,7 +44,7 @@ export class ArchiverDataStoreUpdater {
46
44
  private readonly log = createLogger('archiver:store_updater');
47
45
 
48
46
  constructor(
49
- private store: KVArchiverDataStore,
47
+ private stores: ArchiverDataStores,
50
48
  private l2TipsCache?: L2TipsCache,
51
49
  private opts: { rollupManaLimit?: number } = {},
52
50
  ) {}
@@ -54,8 +52,7 @@ export class ArchiverDataStoreUpdater {
54
52
  /**
55
53
  * Adds a proposed block to the store with contract class/instance extraction from logs.
56
54
  * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
57
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
58
- * and individually broadcasted functions from the block logs.
55
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
59
56
  *
60
57
  * @param block - The proposed L2 block to add.
61
58
  * @param pendingChainValidationStatus - Optional validation status to set.
@@ -65,21 +62,22 @@ export class ArchiverDataStoreUpdater {
65
62
  block: L2Block,
66
63
  pendingChainValidationStatus?: ValidateCheckpointResult,
67
64
  ): Promise<boolean> {
68
- const result = await this.store.transactionAsync(async () => {
69
- await this.store.addProposedBlock(block);
65
+ const result = await this.stores.db.transactionAsync(async () => {
66
+ await this.stores.blocks.addProposedBlock(block);
70
67
 
71
68
  const opResults = await Promise.all([
72
69
  // Update the pending chain validation status if provided
73
- pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
70
+ pendingChainValidationStatus &&
71
+ this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
74
72
  // Add any logs emitted during the retrieved block
75
- this.store.addLogs([block]),
73
+ this.stores.logs.addLogs([block]),
76
74
  // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
77
75
  this.addContractDataToDb(block),
78
76
  ]);
79
77
 
80
- await this.l2TipsCache?.refresh();
81
78
  return opResults.every(Boolean);
82
79
  });
80
+ await this.l2TipsCache?.refresh();
83
81
  return result;
84
82
  }
85
83
 
@@ -87,26 +85,45 @@ export class ArchiverDataStoreUpdater {
87
85
  * Reconciles local blocks with incoming checkpoints from L1.
88
86
  * Adds new checkpoints to the store with contract class/instance extraction from logs.
89
87
  * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
90
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
91
- * and individually broadcasted functions from the checkpoint block logs.
88
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
89
+ * If `promoteProposed` is supplied, the proposed-checkpoint promotion runs inside the same transaction
90
+ * as the added checkpoints so both updates are applied atomically.
92
91
  *
93
- * @param checkpoints - The published checkpoints to add.
92
+ * @param checkpoints - The published checkpoints to add (excluding any being promoted from proposed).
94
93
  * @param pendingChainValidationStatus - Optional validation status to set.
94
+ * @param promoteProposed - Optional promotion of the current proposed checkpoint (fast path when blocks are already local).
95
95
  * @returns Result with information about any pruned blocks.
96
96
  */
97
97
  public async addCheckpoints(
98
98
  checkpoints: PublishedCheckpoint[],
99
99
  pendingChainValidationStatus?: ValidateCheckpointResult,
100
+ promoteProposed?: {
101
+ l1: L1PublishedData;
102
+ attestations: CommitteeAttestation[];
103
+ checkpoint: PublishedCheckpoint;
104
+ },
105
+ evictProposedFrom?: CheckpointNumber,
100
106
  ): Promise<ReconcileCheckpointsResult> {
107
+ // Checkpoints here are already accepted by L1, so tolerate up to the physical blob-capacity
108
+ // ceiling rather than the conservative attestable limit used when building/attesting.
101
109
  for (const checkpoint of checkpoints) {
102
- validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
110
+ validateCheckpoint(checkpoint.checkpoint, {
111
+ rollupManaLimit: this.opts?.rollupManaLimit,
112
+ maxBlocksPerCheckpoint: MAX_CAPACITY_BLOCKS_PER_CHECKPOINT,
113
+ });
114
+ }
115
+ if (promoteProposed) {
116
+ validateCheckpoint(promoteProposed.checkpoint.checkpoint, {
117
+ rollupManaLimit: this.opts?.rollupManaLimit,
118
+ maxBlocksPerCheckpoint: MAX_CAPACITY_BLOCKS_PER_CHECKPOINT,
119
+ });
103
120
  }
104
121
 
105
- const result = await this.store.transactionAsync(async () => {
122
+ const result = await this.stores.db.transactionAsync(async () => {
106
123
  // Before adding checkpoints, check for conflicts with local blocks if any
107
124
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
108
125
 
109
- await this.store.addCheckpoints(checkpoints);
126
+ await this.stores.blocks.addCheckpoints(checkpoints);
110
127
 
111
128
  // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
112
129
  const newBlocks = checkpoints
@@ -115,29 +132,59 @@ export class ArchiverDataStoreUpdater {
115
132
 
116
133
  await Promise.all([
117
134
  // Update the pending chain validation status if provided
118
- pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
135
+ pendingChainValidationStatus &&
136
+ this.stores.blocks.setPendingChainValidationStatus(pendingChainValidationStatus),
119
137
  // Add any logs emitted during the retrieved blocks
120
- this.store.addLogs(newBlocks),
138
+ this.stores.logs.addLogs(newBlocks),
121
139
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
122
140
  ...newBlocks.map(block => this.addContractDataToDb(block)),
141
+ // Promote the proposed checkpoint if requested (uses explicit checkpoint number)
142
+ promoteProposed
143
+ ? this.stores.blocks.promoteProposedToCheckpointed(
144
+ promoteProposed.checkpoint.checkpoint.number,
145
+ promoteProposed.l1,
146
+ promoteProposed.attestations,
147
+ promoteProposed.checkpoint.checkpoint.archive.root,
148
+ )
149
+ : undefined,
150
+ // Evict pending checkpoints that diverged from what L1 mined
151
+ evictProposedFrom !== undefined
152
+ ? this.stores.blocks.evictProposedCheckpointsFrom(evictProposedFrom)
153
+ : undefined,
123
154
  ]);
124
155
 
125
- await this.l2TipsCache?.refresh();
126
156
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
127
157
  });
158
+ await this.l2TipsCache?.refresh();
159
+ return result;
160
+ }
161
+
162
+ public async addProposedCheckpoint(proposedCheckpoint: ProposedCheckpointInput) {
163
+ const result = await this.stores.db.transactionAsync(async () => {
164
+ await this.stores.blocks.addProposedCheckpoint(proposedCheckpoint);
165
+ });
166
+ await this.l2TipsCache?.refresh();
128
167
  return result;
129
168
  }
130
169
 
131
170
  /**
132
171
  * Checks for local proposed blocks that do not match the ones to be checkpointed and prunes them.
133
- * This method handles multiple checkpoints but returns after pruning the first conflict found.
134
- * This is correct because pruning from the first conflict point removes all subsequent blocks,
135
- * and when checkpoints are added afterward, they include all the correct blocks.
172
+ * Conflict detection is keyed on `blockNumber`: when a local proposed block and an L1
173
+ * checkpointed block share a block number but live at different slots (e.g. a different proposer
174
+ * mined the same block number one slot earlier), we still treat them as a conflict and prune.
175
+ * The trailing per-checkpoint prune that handles "local has extra trailing blocks within the
176
+ * same slot as the published checkpoint" remains scoped by slot to preserve pipelining: local
177
+ * blocks that live at a later slot than the checkpoint being processed represent speculation
178
+ * atop the just-confirmed tip (and may be referenced by a pending proposed checkpoint), so we
179
+ * leave them in place. This method handles multiple checkpoints but returns after pruning the
180
+ * first conflict found. This is correct because pruning from the first conflict point removes
181
+ * all subsequent blocks, and when checkpoints are added afterward, they include all the correct
182
+ * blocks.
136
183
  */
137
184
  private async pruneMismatchingLocalBlocks(checkpoints: PublishedCheckpoint[]): Promise<ReconcileCheckpointsResult> {
138
185
  const [lastCheckpointedBlockNumber, lastBlockNumber] = await Promise.all([
139
- this.store.getCheckpointedL2BlockNumber(),
140
- this.store.getLatestBlockNumber(),
186
+ this.stores.blocks.getCheckpointedL2BlockNumber(),
187
+ this.stores.blocks.getLatestL2BlockNumber(),
141
188
  ]);
142
189
 
143
190
  // Exit early if there are no local uncheckpointed blocks
@@ -146,29 +193,29 @@ export class ArchiverDataStoreUpdater {
146
193
  }
147
194
 
148
195
  // Get all uncheckpointed local blocks
149
- const uncheckpointedLocalBlocks = await this.store.getBlocks(
150
- BlockNumber.add(lastCheckpointedBlockNumber, 1),
151
- lastBlockNumber - lastCheckpointedBlockNumber,
152
- );
196
+ const uncheckpointedLocalBlocks = await this.stores.blocks.getBlocksData({
197
+ from: BlockNumber.add(lastCheckpointedBlockNumber, 1),
198
+ limit: lastBlockNumber - lastCheckpointedBlockNumber,
199
+ });
153
200
 
154
201
  let lastAlreadyInsertedBlockNumber: BlockNumber | undefined;
155
202
 
156
203
  for (const publishedCheckpoint of checkpoints) {
157
204
  const checkpointBlocks = publishedCheckpoint.checkpoint.blocks;
158
205
  const slot = publishedCheckpoint.checkpoint.slot;
159
- const localBlocksInSlot = uncheckpointedLocalBlocks.filter(b => b.slot === slot);
160
206
 
161
207
  if (checkpointBlocks.length === 0) {
162
208
  this.log.warn(`Checkpoint ${publishedCheckpoint.checkpoint.number} for slot ${slot} has no blocks`);
163
209
  continue;
164
210
  }
165
211
 
166
- // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards
212
+ // Find the first checkpoint block that conflicts with an existing local block and prune local afterwards.
213
+ // Conflict detection joins on block number only — same block number at a different slot is still a conflict.
167
214
  for (const checkpointBlock of checkpointBlocks) {
168
215
  const blockNumber = checkpointBlock.number;
169
- const existingBlock = localBlocksInSlot.find(b => b.number === blockNumber);
216
+ const existingBlock = uncheckpointedLocalBlocks.find(b => b.header.getBlockNumber() === blockNumber);
170
217
  const blockInfos = {
171
- existingBlock: existingBlock?.toBlockInfo(),
218
+ existingBlock: existingBlock?.header.toInspect(),
172
219
  checkpointBlock: checkpointBlock.toBlockInfo(),
173
220
  };
174
221
 
@@ -180,20 +227,24 @@ export class ArchiverDataStoreUpdater {
180
227
  } else {
181
228
  this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
182
229
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
230
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
183
231
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
184
232
  }
185
233
  }
186
234
 
187
- // If local has more blocks than the checkpoint (e.g., local has [2,3,4] but checkpoint has [2,3]),
188
- // we need to prune the extra local blocks so they match what was checkpointed
235
+ // If the sequencer locally proposed extra blocks within this checkpoint's slot (e.g. local has
236
+ // [N, N+1] but L1 confirmed just [N]), prune the extras. Scoped to the checkpoint's slot so we
237
+ // do not throw away speculative blocks at later slots that belong to a pending proposed checkpoint.
189
238
  const lastCheckpointBlockNumber = checkpointBlocks.at(-1)!.number;
190
- const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.number;
239
+ const localBlocksInSlot = uncheckpointedLocalBlocks.filter(b => b.header.getSlot() === slot);
240
+ const lastLocalBlockNumber = localBlocksInSlot.at(-1)?.header.getBlockNumber();
191
241
 
192
242
  if (lastLocalBlockNumber !== undefined && lastLocalBlockNumber > lastCheckpointBlockNumber) {
193
243
  this.log.warn(
194
244
  `Local chain for slot ${slot} ends at block ${lastLocalBlockNumber} but checkpoint ends at ${lastCheckpointBlockNumber}. Pruning blocks after block ${lastCheckpointBlockNumber}.`,
195
245
  );
196
246
  const prunedBlocks = await this.removeBlocksAfter(lastCheckpointBlockNumber);
247
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
197
248
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
198
249
  }
199
250
  }
@@ -211,33 +262,74 @@ export class ArchiverDataStoreUpdater {
211
262
  * @throws Error if any block to be removed is checkpointed.
212
263
  */
213
264
  public async removeUncheckpointedBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
214
- const result = await this.store.transactionAsync(async () => {
265
+ const result = await this.stores.db.transactionAsync(async () => {
215
266
  // Verify we're only removing uncheckpointed blocks
216
- const lastCheckpointedBlockNumber = await this.store.getCheckpointedL2BlockNumber();
267
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getCheckpointedL2BlockNumber();
217
268
  if (blockNumber < lastCheckpointedBlockNumber) {
218
269
  throw new Error(
219
270
  `Cannot remove blocks after ${blockNumber} because checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
220
271
  );
221
272
  }
222
273
 
223
- const result = await this.removeBlocksAfter(blockNumber);
224
- await this.l2TipsCache?.refresh();
225
- return result;
274
+ const prunedBlocks = await this.removeBlocksAfter(blockNumber);
275
+ await this.evictProposedCheckpointsForPrunedBlocks(prunedBlocks);
276
+
277
+ return prunedBlocks;
278
+ });
279
+ await this.l2TipsCache?.refresh();
280
+ return result;
281
+ }
282
+
283
+ /**
284
+ * Removes all blocks without a proposed checkpoint strictly after the specified block number and cleans up associated contract data.
285
+ * This handles removal of provisionally added blocks along with their contract classes/instances.
286
+ * Verifies that each block being removed is not part of a stored checkpoint (proposed or not).
287
+ * This differs from `removeUncheckpointedBlocksAfter` in that it also checks proposed checkpoints.
288
+ *
289
+ * @param blockNumber - Remove all blocks with number greater than this.
290
+ * @returns The removed blocks.
291
+ * @throws Error if any block to be removed is checkpointed.
292
+ */
293
+ public async removeBlocksWithoutProposedCheckpointAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
294
+ const result = await this.stores.db.transactionAsync(async () => {
295
+ // Verify we're only removing uncheckpointed blocks
296
+ const lastCheckpointedBlockNumber = await this.stores.blocks.getProposedCheckpointL2BlockNumber();
297
+ if (blockNumber < lastCheckpointedBlockNumber) {
298
+ throw new Error(
299
+ `Cannot remove blocks after ${blockNumber} because proposed checkpointed blocks exist up to ${lastCheckpointedBlockNumber}`,
300
+ );
301
+ }
302
+
303
+ return await this.removeBlocksAfter(blockNumber);
226
304
  });
305
+ await this.l2TipsCache?.refresh();
227
306
  return result;
228
307
  }
229
308
 
309
+ /**
310
+ * Evicts pending proposed checkpoints that referenced any of the just-pruned blocks. Pruned
311
+ * blocks invalidate all proposed checkpoints from the lowest pruned block's checkpoint number
312
+ * onwards: those checkpoints either reference the pruned blocks directly or chain off them.
313
+ */
314
+ private async evictProposedCheckpointsForPrunedBlocks(prunedBlocks: L2Block[]): Promise<void> {
315
+ if (prunedBlocks.length === 0) {
316
+ return;
317
+ }
318
+ const fromCheckpointNumber = prunedBlocks[0].checkpointNumber;
319
+ await this.stores.blocks.evictProposedCheckpointsFrom(fromCheckpointNumber);
320
+ }
321
+
230
322
  /**
231
323
  * Removes all blocks strictly after the given block number along with any logs and contract data.
232
324
  * Does not remove their checkpoints.
233
325
  */
234
326
  private async removeBlocksAfter(blockNumber: BlockNumber): Promise<L2Block[]> {
235
327
  // First get the blocks to be removed so we can clean up contract data
236
- const removedBlocks = await this.store.removeBlocksAfter(blockNumber);
328
+ const removedBlocks = await this.stores.blocks.removeBlocksAfter(blockNumber);
237
329
 
238
330
  // Clean up contract data and logs for the removed blocks
239
331
  await Promise.all([
240
- this.store.deleteLogs(removedBlocks),
332
+ this.stores.logs.deleteLogs(removedBlocks),
241
333
  ...removedBlocks.map(block => this.removeContractDataFromDb(block)),
242
334
  ]);
243
335
 
@@ -254,20 +346,21 @@ export class ArchiverDataStoreUpdater {
254
346
  * @returns True if the operation is successful.
255
347
  */
256
348
  public async removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
257
- return await this.store.transactionAsync(async () => {
258
- const { blocksRemoved = [] } = await this.store.removeCheckpointsAfter(checkpointNumber);
349
+ const result = await this.stores.db.transactionAsync(async () => {
350
+ const { blocksRemoved = [] } = await this.stores.blocks.removeCheckpointsAfter(checkpointNumber);
259
351
 
260
352
  const opResults = await Promise.all([
261
353
  // Prune rolls back to the last proven block, which is by definition valid
262
- this.store.setPendingChainValidationStatus({ valid: true }),
354
+ this.stores.blocks.setPendingChainValidationStatus({ valid: true }),
263
355
  // Remove contract data for all blocks being removed
264
356
  ...blocksRemoved.map(block => this.removeContractDataFromDb(block)),
265
- this.store.deleteLogs(blocksRemoved),
357
+ this.stores.logs.deleteLogs(blocksRemoved),
266
358
  ]);
267
359
 
268
- await this.l2TipsCache?.refresh();
269
360
  return opResults.every(Boolean);
270
361
  });
362
+ await this.l2TipsCache?.refresh();
363
+ return result;
271
364
  }
272
365
 
273
366
  /**
@@ -275,10 +368,10 @@ export class ArchiverDataStoreUpdater {
275
368
  * @param checkpointNumber - The checkpoint number to set as proven.
276
369
  */
277
370
  public async setProvenCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
278
- await this.store.transactionAsync(async () => {
279
- await this.store.setProvenCheckpointNumber(checkpointNumber);
280
- await this.l2TipsCache?.refresh();
371
+ await this.stores.db.transactionAsync(async () => {
372
+ await this.stores.blocks.setProvenCheckpointNumber(checkpointNumber);
281
373
  });
374
+ await this.l2TipsCache?.refresh();
282
375
  }
283
376
 
284
377
  /**
@@ -286,10 +379,10 @@ export class ArchiverDataStoreUpdater {
286
379
  * @param checkpointNumber - The checkpoint number to set as finalized.
287
380
  */
288
381
  public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
289
- await this.store.transactionAsync(async () => {
290
- await this.store.setFinalizedCheckpointNumber(checkpointNumber);
291
- await this.l2TipsCache?.refresh();
382
+ await this.stores.db.transactionAsync(async () => {
383
+ await this.stores.blocks.setFinalizedCheckpointNumber(checkpointNumber);
292
384
  });
385
+ await this.l2TipsCache?.refresh();
293
386
  }
294
387
 
295
388
  /** Extracts and stores contract data from a single block. */
@@ -313,9 +406,6 @@ export class ArchiverDataStoreUpdater {
313
406
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
314
407
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
315
408
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
316
- operation === Operation.Store
317
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
318
- : Promise.resolve(true),
319
409
  ])
320
410
  ).every(Boolean);
321
411
  }
@@ -332,18 +422,37 @@ export class ArchiverDataStoreUpdater {
332
422
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
333
423
  .map(log => ContractClassPublishedEvent.fromLog(log));
334
424
 
335
- const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
336
- if (contractClasses.length > 0) {
337
- contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
338
- if (operation == Operation.Store) {
339
- // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
340
- const commitments = await Promise.all(
341
- contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
425
+ if (operation == Operation.Delete) {
426
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
427
+ if (contractClasses.length > 0) {
428
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
429
+ return await this.stores.contractClasses.deleteContractClasses(contractClasses, blockNum);
430
+ }
431
+ return true;
432
+ }
433
+
434
+ // Compute bytecode commitments and validate class IDs in a single pass.
435
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
436
+ for (const event of contractClassPublishedEvents) {
437
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
438
+ const computedClassId = await computeContractClassId({
439
+ artifactHash: contractClass.artifactHash,
440
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
441
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
442
+ });
443
+ if (!computedClassId.equals(contractClass.id)) {
444
+ this.log.warn(
445
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
446
+ { blockNum, contractClassId: event.contractClassId.toString() },
342
447
  );
343
- return await this.store.addContractClasses(contractClasses, commitments, blockNum);
344
- } else if (operation == Operation.Delete) {
345
- return await this.store.deleteContractClasses(contractClasses, blockNum);
448
+ continue;
346
449
  }
450
+ contractClasses.push(contractClass);
451
+ }
452
+
453
+ if (contractClasses.length > 0) {
454
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
455
+ return await this.stores.contractClasses.addContractClasses(contractClasses, blockNum);
347
456
  }
348
457
  return true;
349
458
  }
@@ -356,18 +465,35 @@ export class ArchiverDataStoreUpdater {
356
465
  blockNum: BlockNumber,
357
466
  operation: Operation,
358
467
  ): Promise<boolean> {
359
- const contractInstances = allLogs
468
+ const allInstances = allLogs
360
469
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
361
470
  .map(log => ContractInstancePublishedEvent.fromLog(log))
362
471
  .map(e => e.toContractInstance());
472
+
473
+ // Verify that each instance's address matches the one derived from its fields if we're adding
474
+ const contractInstances =
475
+ operation === Operation.Delete
476
+ ? allInstances
477
+ : await filterAsync(allInstances, async instance => {
478
+ const computedAddress = await computeContractAddressFromInstance(instance);
479
+ if (!computedAddress.equals(instance.address)) {
480
+ this.log.warn(
481
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
482
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
483
+ );
484
+ return false;
485
+ }
486
+ return true;
487
+ });
488
+
363
489
  if (contractInstances.length > 0) {
364
490
  contractInstances.forEach(c =>
365
491
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
366
492
  );
367
493
  if (operation == Operation.Store) {
368
- return await this.store.addContractInstances(contractInstances, blockNum);
494
+ return await this.stores.contractInstances.addContractInstances(contractInstances, blockNum);
369
495
  } else if (operation == Operation.Delete) {
370
- return await this.store.deleteContractInstances(contractInstances, blockNum);
496
+ return await this.stores.contractInstances.deleteContractInstances(contractInstances);
371
497
  }
372
498
  }
373
499
  return true;
@@ -391,73 +517,10 @@ export class ArchiverDataStoreUpdater {
391
517
  this.log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`),
392
518
  );
393
519
  if (operation == Operation.Store) {
394
- return await this.store.addContractInstanceUpdates(contractUpdates, timestamp);
520
+ return await this.stores.contractInstances.addContractInstanceUpdates(contractUpdates, timestamp);
395
521
  } else if (operation == Operation.Delete) {
396
- return await this.store.deleteContractInstanceUpdates(contractUpdates, timestamp);
397
- }
398
- }
399
- return true;
400
- }
401
-
402
- /**
403
- * Stores the functions that were broadcasted individually.
404
- *
405
- * @dev Beware that there is not a delete variant of this, since they are added to contract classes
406
- * and will be deleted as part of the class if needed.
407
- */
408
- private async storeBroadcastedIndividualFunctions(
409
- allLogs: ContractClassLog[],
410
- _blockNum: BlockNumber,
411
- ): Promise<boolean> {
412
- // Filter out private and utility function broadcast events
413
- const privateFnEvents = allLogs
414
- .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
415
- .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
416
- const utilityFnEvents = allLogs
417
- .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
418
- .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
419
-
420
- // Group all events by contract class id
421
- for (const [classIdString, classEvents] of Object.entries(
422
- groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
423
- )) {
424
- const contractClassId = Fr.fromHexString(classIdString);
425
- const contractClass = await this.store.getContractClass(contractClassId);
426
- if (!contractClass) {
427
- this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
428
- continue;
429
- }
430
-
431
- // Split private and utility functions, and filter out invalid ones
432
- const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
433
- const privateFns = allFns.filter(
434
- (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
435
- );
436
- const utilityFns = allFns.filter(
437
- (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
438
- );
439
-
440
- const privateFunctionsWithValidity = await Promise.all(
441
- privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
442
- );
443
- const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
444
- const utilityFunctionsWithValidity = await Promise.all(
445
- utilityFns.map(async fn => ({
446
- fn,
447
- valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
448
- })),
449
- );
450
- const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
451
- const validFnCount = validPrivateFns.length + validUtilityFns.length;
452
- if (validFnCount !== allFns.length) {
453
- this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
454
- }
455
-
456
- // Store the functions in the contract class in a single operation
457
- if (validFnCount > 0) {
458
- this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
522
+ return await this.stores.contractInstances.deleteContractInstanceUpdates(contractUpdates, timestamp);
459
523
  }
460
- await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
461
524
  }
462
525
  return true;
463
526
  }
@@ -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));
118
- this.blockHeight.record(Math.max(...blocks.map(b => b.number)));
119
- this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
120
- this.syncBlockCount.add(blocks.length);
121
126
 
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);
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;
126
136
  }
137
+
138
+ this.syncDurationPerCheckpoint.record(Math.ceil(syncTimePerCheckpoint));
139
+ this.blockHeight.record(Math.max(...blocks.map(b => b.number)), { [Attributes.STATUS]: 'checkpointed' });
140
+ this.checkpointHeight.record(Math.max(...blocks.map(b => b.checkpointNumber)));
141
+ this.syncBlockCount.add(blocks.length);
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
  */