@aztec/archiver 0.0.1-commit.d431d1c → 0.0.1-commit.d58ff9d0

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