@aztec/archiver 0.0.1-commit.2448fdb → 0.0.1-commit.2606882

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