@aztec/archiver 0.0.1-commit.993d240 → 0.0.1-commit.9a89641

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 (86) hide show
  1. package/dest/archiver.d.ts +44 -8
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +103 -35
  4. package/dest/config.d.ts +5 -4
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +28 -7
  7. package/dest/factory.d.ts +8 -1
  8. package/dest/factory.d.ts.map +1 -1
  9. package/dest/factory.js +41 -5
  10. package/dest/l1/calldata_retriever.d.ts +8 -1
  11. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  12. package/dest/l1/calldata_retriever.js +7 -6
  13. package/dest/l1/data_retrieval.d.ts +7 -2
  14. package/dest/l1/data_retrieval.d.ts.map +1 -1
  15. package/dest/modules/contract_data_source_adapter.d.ts +2 -2
  16. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -1
  17. package/dest/modules/contract_data_source_adapter.js +1 -9
  18. package/dest/modules/data_source_base.d.ts +5 -6
  19. package/dest/modules/data_source_base.d.ts.map +1 -1
  20. package/dest/modules/data_source_base.js +9 -38
  21. package/dest/modules/data_store_updater.d.ts +1 -1
  22. package/dest/modules/data_store_updater.d.ts.map +1 -1
  23. package/dest/modules/data_store_updater.js +4 -3
  24. package/dest/modules/instrumentation.d.ts +9 -1
  25. package/dest/modules/instrumentation.d.ts.map +1 -1
  26. package/dest/modules/instrumentation.js +23 -2
  27. package/dest/modules/l1_synchronizer.d.ts +3 -3
  28. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  29. package/dest/modules/l1_synchronizer.js +78 -41
  30. package/dest/modules/outbox_trees_resolver.d.ts +64 -0
  31. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  32. package/dest/modules/outbox_trees_resolver.js +184 -0
  33. package/dest/modules/validation.d.ts +29 -7
  34. package/dest/modules/validation.d.ts.map +1 -1
  35. package/dest/modules/validation.js +31 -13
  36. package/dest/store/block_store.d.ts +26 -22
  37. package/dest/store/block_store.d.ts.map +1 -1
  38. package/dest/store/block_store.js +105 -78
  39. package/dest/store/contract_class_store.d.ts +1 -1
  40. package/dest/store/contract_class_store.d.ts.map +1 -1
  41. package/dest/store/contract_class_store.js +19 -1
  42. package/dest/store/contract_instance_store.d.ts +1 -1
  43. package/dest/store/contract_instance_store.d.ts.map +1 -1
  44. package/dest/store/contract_instance_store.js +18 -1
  45. package/dest/store/log_store.d.ts +1 -1
  46. package/dest/store/log_store.d.ts.map +1 -1
  47. package/dest/store/log_store.js +3 -3
  48. package/dest/store/log_store_codec.d.ts +9 -1
  49. package/dest/store/log_store_codec.d.ts.map +1 -1
  50. package/dest/store/log_store_codec.js +9 -0
  51. package/dest/test/fake_l1_state.js +3 -3
  52. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  53. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  54. package/dest/test/mock_l1_to_l2_message_source.js +1 -2
  55. package/dest/test/mock_l2_block_source.d.ts +4 -11
  56. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  57. package/dest/test/mock_l2_block_source.js +15 -39
  58. package/dest/test/mock_structs.d.ts +1 -1
  59. package/dest/test/mock_structs.d.ts.map +1 -1
  60. package/dest/test/mock_structs.js +2 -2
  61. package/dest/test/noop_l1_archiver.d.ts +8 -3
  62. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  63. package/dest/test/noop_l1_archiver.js +12 -9
  64. package/package.json +13 -13
  65. package/src/archiver.ts +147 -42
  66. package/src/config.ts +34 -16
  67. package/src/factory.ts +48 -4
  68. package/src/l1/calldata_retriever.ts +13 -6
  69. package/src/l1/data_retrieval.ts +8 -1
  70. package/src/modules/contract_data_source_adapter.ts +1 -10
  71. package/src/modules/data_source_base.ts +17 -44
  72. package/src/modules/data_store_updater.ts +4 -3
  73. package/src/modules/instrumentation.ts +15 -2
  74. package/src/modules/l1_synchronizer.ts +120 -57
  75. package/src/modules/outbox_trees_resolver.ts +220 -0
  76. package/src/modules/validation.ts +71 -15
  77. package/src/store/block_store.ts +108 -101
  78. package/src/store/contract_class_store.ts +19 -1
  79. package/src/store/contract_instance_store.ts +18 -1
  80. package/src/store/log_store.ts +3 -2
  81. package/src/store/log_store_codec.ts +11 -0
  82. package/src/test/fake_l1_state.ts +3 -3
  83. package/src/test/mock_l1_to_l2_message_source.ts +0 -1
  84. package/src/test/mock_l2_block_source.ts +14 -53
  85. package/src/test/mock_structs.ts +5 -2
  86. package/src/test/noop_l1_archiver.ts +30 -11
@@ -16,8 +16,19 @@ import { retryTimes } from '@aztec/foundation/retry';
16
16
  import { count } from '@aztec/foundation/string';
17
17
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
18
18
  import { isDefined, isErrorClass } from '@aztec/foundation/types';
19
- import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
20
- import { Checkpoint, type CheckpointData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
+ import {
20
+ type ArchiverEmitter,
21
+ type L2Block,
22
+ L2BlockSourceEvents,
23
+ type ValidateCheckpointResult,
24
+ } from '@aztec/stdlib/block';
25
+ import {
26
+ Checkpoint,
27
+ type CheckpointData,
28
+ type CheckpointInfo,
29
+ type L1PublishedData,
30
+ PublishedCheckpoint,
31
+ } from '@aztec/stdlib/checkpoint';
21
32
  import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
22
33
  import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
23
34
  import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
@@ -39,7 +50,7 @@ import { MessageStoreError } from '../store/message_store.js';
39
50
  import type { InboxMessage } from '../structs/inbox_message.js';
40
51
  import { ArchiverDataStoreUpdater } from './data_store_updater.js';
41
52
  import type { ArchiverInstrumentation } from './instrumentation.js';
42
- import { validateCheckpointAttestations } from './validation.js';
53
+ import { validateCheckpointAttestationsFromCalldata } from './validation.js';
43
54
 
44
55
  type RollupStatus = {
45
56
  provenCheckpointNumber: CheckpointNumber;
@@ -50,7 +61,9 @@ type RollupStatus = {
50
61
  /** Last valid checkpoint observed on L1 and synced on this iteration */
51
62
  lastRetrievedCheckpoint?: PublishedCheckpoint;
52
63
  /** Last checkpoint observed on L1 across both valid and rejected entries on this iteration */
53
- lastSeenCheckpoint?: PublishedCheckpoint;
64
+ lastSeenCheckpoint?: { checkpointNumber: CheckpointNumber; l1: L1PublishedData };
65
+ /** Blocks added while handling checkpoints this iteration, for the aggregate block source update event. */
66
+ blocksAdded: L2Block[];
54
67
  };
55
68
 
56
69
  /**
@@ -139,7 +152,9 @@ export class ArchiverL1Synchronizer implements Traceable {
139
152
  }
140
153
 
141
154
  @trackSpan('Archiver.syncFromL1')
142
- public async syncFromL1(initialSyncComplete: boolean): Promise<void> {
155
+ public async syncFromL1(initialSyncComplete: boolean): Promise<L2Block[]> {
156
+ const blocksAdded: L2Block[] = [];
157
+
143
158
  // In between the various calls to L1, the block number can move meaning some of the following
144
159
  // calls will return data for blocks that were not present during earlier calls. To combat this
145
160
  // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
@@ -152,7 +167,7 @@ export class ArchiverL1Synchronizer implements Traceable {
152
167
 
153
168
  if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
154
169
  this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
155
- return;
170
+ return blocksAdded;
156
171
  }
157
172
 
158
173
  // Log at error if the latest L1 block timestamp is too old
@@ -190,6 +205,7 @@ export class ArchiverL1Synchronizer implements Traceable {
190
205
  // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
191
206
  // pending chain validation status, proven checkpoint number, and synched L1 block number.
192
207
  const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
208
+ blocksAdded.push(...rollupStatus.blocksAdded);
193
209
 
194
210
  // Then we try pruning uncheckpointed blocks if a new slot was mined without checkpoints
195
211
  await this.pruneUncheckpointedBlocks(currentL1Timestamp);
@@ -231,6 +247,8 @@ export class ArchiverL1Synchronizer implements Traceable {
231
247
  l1TimestampAtStart: currentL1Timestamp,
232
248
  l1BlockNumberAtEnd,
233
249
  });
250
+
251
+ return blocksAdded;
234
252
  }
235
253
 
236
254
  /** Updates the finalized checkpoint using the pre-fetched finalized L1 block from the current sync iteration. */
@@ -261,7 +279,7 @@ export class ArchiverL1Synchronizer implements Traceable {
261
279
  }
262
280
 
263
281
  /** Prune all proposed local blocks that should have been checkpointed by now. */
264
- private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
282
+ private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint): Promise<void> {
265
283
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
266
284
  this.stores.blocks.getCheckpointedL2BlockNumber(),
267
285
  this.stores.blocks.getLatestL2BlockNumber(),
@@ -296,6 +314,7 @@ export class ArchiverL1Synchronizer implements Traceable {
296
314
 
297
315
  const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
298
316
  if (prunedBlocks.length > 0) {
317
+ this.instrumentation.recordPrune('uncheckpointed');
299
318
  this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
300
319
  type: L2BlockSourceEvents.L2PruneUncheckpointed,
301
320
  slotNumber: firstUncheckpointedBlockSlot,
@@ -616,6 +635,7 @@ export class ArchiverL1Synchronizer implements Traceable {
616
635
  currentL1BlockNumber: bigint,
617
636
  initialSyncComplete: boolean,
618
637
  ): Promise<RollupStatus> {
638
+ const blocksAdded: L2Block[] = [];
619
639
  const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
620
640
  const initialValidationResult: ValidateCheckpointResult | undefined =
621
641
  await this.stores.blocks.getPendingChainValidationStatus();
@@ -634,6 +654,7 @@ export class ArchiverL1Synchronizer implements Traceable {
634
654
  pendingCheckpointNumber,
635
655
  pendingArchive: pendingArchive.toString(),
636
656
  validationResult: initialValidationResult,
657
+ blocksAdded,
637
658
  };
638
659
  this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
639
660
  localPendingCheckpointNumber,
@@ -776,6 +797,9 @@ export class ArchiverL1Synchronizer implements Traceable {
776
797
 
777
798
  const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
778
799
  await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
800
+ if (checkpointsToRemove > 0) {
801
+ this.instrumentation.recordPrune('l1_mismatch');
802
+ }
779
803
 
780
804
  this.log.warn(
781
805
  `Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` +
@@ -790,7 +814,7 @@ export class ArchiverL1Synchronizer implements Traceable {
790
814
  let searchStartBlock: bigint = blocksSynchedTo;
791
815
  let searchEndBlock: bigint = blocksSynchedTo;
792
816
  let lastRetrievedCheckpoint: PublishedCheckpoint | undefined;
793
- let lastSeenCheckpoint: PublishedCheckpoint | undefined;
817
+ let lastSeenCheckpoint: { checkpointNumber: CheckpointNumber; l1: L1PublishedData } | undefined;
794
818
 
795
819
  do {
796
820
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
@@ -835,37 +859,21 @@ export class ArchiverL1Synchronizer implements Traceable {
835
859
  const evictProposedFrom =
836
860
  promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
837
861
 
838
- // Then fetch blobs in parallel and build the full published checkpoints
839
- const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
840
- const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
841
- retrievedToPublishedCheckpoint({
842
- ...checkpoint,
843
- checkpointBlobData: await getCheckpointBlobDataFromBlobs(
844
- this.blobClient,
845
- checkpoint.l1.blockHash,
846
- checkpoint.blobHashes,
847
- checkpoint.checkpointNumber,
848
- this.log,
849
- !initialSyncComplete,
850
- checkpoint.parentBeaconBlockRoot,
851
- checkpoint.l1.timestamp,
852
- ),
853
- }),
854
- );
855
-
856
- // And add the promoted checkpoint to the list of all checkpoints
857
- const publishedCheckpoints = checkpointToPromote ? [...blobFetched, checkpointToPromote] : blobFetched;
858
- const validCheckpoints: PublishedCheckpoint[] = [];
862
+ // Validate attestations from CALLDATA before fetching any blobs. A checkpoint with invalid
863
+ // attestations (or one descending from a rejected ancestor) is rejected here without fetching its
864
+ // blobs, so a malformed blob does not throw during decode before the rejection path runs and
865
+ // stall sync. The signed consensus payload (header, archive root, fee asset price
866
+ // modifier) is fully available from calldata.
867
+ const checkpointsToIngest: RetrievedCheckpointFromCalldata[] = [];
859
868
 
860
- // Now loop through all checkpoints and validate their attestations
861
- for (const published of publishedCheckpoints) {
862
- // Check the attestations uploaded by the publisher to L1 are correct
869
+ for (const calldataCheckpoint of calldataCheckpoints) {
870
+ // Check the attestations uploaded by the publisher to L1 are correct.
863
871
  // Rollup contract does not validate attestations to save on gas, so this
864
872
  // falls on the nodes to verify offchain and skip those checkpoints.
865
873
  const validationResult = this.config.skipValidateCheckpointAttestations
866
874
  ? { valid: true as const }
867
- : await validateCheckpointAttestations(
868
- published,
875
+ : await validateCheckpointAttestationsFromCalldata(
876
+ calldataCheckpoint,
869
877
  this.epochCache,
870
878
  this.l1Constants,
871
879
  this.getSignatureContext(),
@@ -877,7 +885,7 @@ export class ArchiverL1Synchronizer implements Traceable {
877
885
  // ancestor was skipped earlier (e.g. due to invalid attestations), the catch handler
878
886
  // would roll back the L1 sync point, and the next iteration would re-fetch and re-throw.
879
887
  const rejectedAncestor = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(
880
- published.checkpoint.header.lastArchiveRoot,
888
+ calldataCheckpoint.header.lastArchiveRoot,
881
889
  );
882
890
 
883
891
  // Update the validation result if it has changed, so we can keep track of the first invalid checkpoint
@@ -899,9 +907,9 @@ export class ArchiverL1Synchronizer implements Traceable {
899
907
  }
900
908
 
901
909
  if (!validationResult.valid) {
902
- this.log.warn(`Skipping checkpoint ${published.checkpoint.number} due to invalid attestations`, {
903
- checkpointHash: published.checkpoint.hash(),
904
- l1BlockNumber: published.l1.blockNumber,
910
+ this.log.warn(`Skipping checkpoint ${calldataCheckpoint.checkpointNumber} due to invalid attestations`, {
911
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
912
+ l1BlockNumber: calldataCheckpoint.l1.blockNumber,
905
913
  ...pick(validationResult, 'reason'),
906
914
  });
907
915
 
@@ -915,11 +923,11 @@ export class ArchiverL1Synchronizer implements Traceable {
915
923
  // is detected and skipped (rather than tripping the addCheckpoints consecutive-number
916
924
  // check and causing the sync point to roll back in a loop).
917
925
  await this.stores.blocks.addRejectedCheckpoint({
918
- checkpointNumber: published.checkpoint.number,
919
- archiveRoot: published.checkpoint.archive.root,
920
- parentArchiveRoot: published.checkpoint.header.lastArchiveRoot,
921
- slotNumber: published.checkpoint.header.slotNumber,
922
- l1: published.l1,
926
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
927
+ archiveRoot: calldataCheckpoint.archiveRoot,
928
+ parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
929
+ slotNumber: calldataCheckpoint.header.slotNumber,
930
+ l1: calldataCheckpoint.l1,
923
931
  reason: 'invalid-attestations' as const,
924
932
  });
925
933
 
@@ -927,15 +935,20 @@ export class ArchiverL1Synchronizer implements Traceable {
927
935
  }
928
936
 
929
937
  if (rejectedAncestor) {
930
- const descendantInfo = published.checkpoint.toCheckpointInfo();
938
+ const descendantInfo: CheckpointInfo = {
939
+ archive: calldataCheckpoint.archiveRoot,
940
+ lastArchive: calldataCheckpoint.header.lastArchiveRoot,
941
+ slotNumber: calldataCheckpoint.header.slotNumber,
942
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
943
+ timestamp: calldataCheckpoint.header.timestamp,
944
+ };
931
945
  this.log.warn(
932
- `Skipping checkpoint ${published.checkpoint.number} as it is a descendant of ` +
946
+ `Skipping checkpoint ${calldataCheckpoint.checkpointNumber} as it is a descendant of ` +
933
947
  `rejected checkpoint ${rejectedAncestor.checkpointNumber} (${rejectedAncestor.reason})`,
934
948
  {
935
- checkpointNumber: published.checkpoint.number,
936
- checkpointHash: published.checkpoint.hash(),
937
- l1BlockNumber: published.l1.blockNumber,
938
- l1BlockHash: published.l1.blockHash,
949
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
950
+ l1BlockNumber: calldataCheckpoint.l1.blockNumber,
951
+ l1BlockHash: calldataCheckpoint.l1.blockHash,
939
952
  ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
940
953
  ancestorArchiveRoot: rejectedAncestor.archiveRoot.toString(),
941
954
  ancestorReason: rejectedAncestor.reason,
@@ -952,17 +965,54 @@ export class ArchiverL1Synchronizer implements Traceable {
952
965
  // Persist this chainpoint as rejected as well, so we can construct a chain of
953
966
  // skipped checkpoints starting from the first one with invalid attestations.
954
967
  await this.stores.blocks.addRejectedCheckpoint({
955
- checkpointNumber: published.checkpoint.number,
956
- archiveRoot: published.checkpoint.archive.root,
957
- parentArchiveRoot: published.checkpoint.header.lastArchiveRoot,
958
- slotNumber: published.checkpoint.header.slotNumber,
959
- l1: published.l1,
968
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
969
+ archiveRoot: calldataCheckpoint.archiveRoot,
970
+ parentArchiveRoot: calldataCheckpoint.header.lastArchiveRoot,
971
+ slotNumber: calldataCheckpoint.header.slotNumber,
972
+ l1: calldataCheckpoint.l1,
960
973
  reason: 'descends-from-invalid-attestations' as const,
961
974
  });
962
975
 
963
976
  continue;
964
977
  }
965
978
 
979
+ checkpointsToIngest.push(calldataCheckpoint);
980
+ }
981
+
982
+ // Fetch blobs in parallel only for the surviving (attestation-valid, non-descendant) checkpoints,
983
+ // then build the full published checkpoints. The last calldata checkpoint may be promotable from a
984
+ // local proposed block (checkpointToPromote), in which case it carries no blob to fetch. A missing or
985
+ // undecodable blob throws and propagates, rolling back the L1 sync point so the fetch is retried.
986
+ const toFetchBlobs = checkpointToPromote
987
+ ? checkpointsToIngest.filter(c => c.checkpointNumber !== checkpointToPromote.checkpoint.number)
988
+ : checkpointsToIngest;
989
+ const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
990
+ retrievedToPublishedCheckpoint({
991
+ ...checkpoint,
992
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(
993
+ this.blobClient,
994
+ checkpoint.l1.blockHash,
995
+ checkpoint.blobHashes,
996
+ checkpoint.checkpointNumber,
997
+ this.log,
998
+ !initialSyncComplete,
999
+ checkpoint.parentBeaconBlockRoot,
1000
+ checkpoint.l1.timestamp,
1001
+ ),
1002
+ }),
1003
+ );
1004
+
1005
+ // Index the built checkpoints by number so we can ingest them in calldata order, slotting in the
1006
+ // promoted checkpoint (built from a local proposed block rather than blobs).
1007
+ const publishedByNumber = new Map(blobFetched.map(published => [published.checkpoint.number, published]));
1008
+ if (checkpointToPromote) {
1009
+ publishedByNumber.set(checkpointToPromote.checkpoint.number, checkpointToPromote);
1010
+ }
1011
+
1012
+ const validCheckpoints: PublishedCheckpoint[] = [];
1013
+ for (const calldataCheckpoint of checkpointsToIngest) {
1014
+ const published = publishedByNumber.get(calldataCheckpoint.checkpointNumber)!;
1015
+
966
1016
  // Check the inHash of the checkpoint against the l1->l2 messages.
967
1017
  // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
968
1018
  // checkpoints we just retrieved.
@@ -1035,6 +1085,11 @@ export class ArchiverL1Synchronizer implements Traceable {
1035
1085
  );
1036
1086
  }
1037
1087
 
1088
+ // Record blocks newly fetched from L1 checkpoint payloads as added. The promoted checkpoint (if any) is
1089
+ // excluded: its blocks were already in local archiver storage (added via the proposed-block path) so the
1090
+ // block stream does not need them re-downloaded.
1091
+ blocksAdded.push(...checkpointsToAdd.flatMap(c => c.checkpoint.blocks));
1092
+
1038
1093
  // If blocks were pruned due to conflict with L1 checkpoints, emit event
1039
1094
  if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1040
1095
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
@@ -1045,6 +1100,8 @@ export class ArchiverL1Synchronizer implements Traceable {
1045
1100
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
1046
1101
  );
1047
1102
 
1103
+ this.instrumentation.recordPrune('l1_conflict');
1104
+
1048
1105
  // Emit event for listening services to react to the prune.
1049
1106
  // Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
1050
1107
  // only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
@@ -1095,7 +1152,9 @@ export class ArchiverL1Synchronizer implements Traceable {
1095
1152
  });
1096
1153
  }
1097
1154
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1098
- lastSeenCheckpoint = publishedCheckpoints.at(-1) ?? lastSeenCheckpoint;
1155
+ // The last checkpoint seen on L1 this batch (valid or rejected), tracked from calldata since
1156
+ // rejected checkpoints are no longer built into PublishedCheckpoints.
1157
+ lastSeenCheckpoint = lastCalldataCheckpoint;
1099
1158
  } while (searchEndBlock < currentL1BlockNumber);
1100
1159
 
1101
1160
  // Important that we update AFTER inserting the blocks.
@@ -1205,7 +1264,7 @@ export class ArchiverL1Synchronizer implements Traceable {
1205
1264
  // Compare the last checkpoint (valid or not) we have (either retrieved in this round or loaded from store)
1206
1265
  // with what the rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
1207
1266
  const latestLocalCheckpointNumber =
1208
- lastSeenCheckpoint?.checkpoint.number ??
1267
+ lastSeenCheckpoint?.checkpointNumber ??
1209
1268
  CheckpointNumber.max(
1210
1269
  await this.stores.blocks.getLatestCheckpointNumber(),
1211
1270
  await this.stores.blocks.getLatestRejectedCheckpointNumber(),
@@ -1218,7 +1277,11 @@ export class ArchiverL1Synchronizer implements Traceable {
1218
1277
  // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
1219
1278
  // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
1220
1279
  // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
1221
- const latestLocalCheckpoint: PublishedCheckpoint | CheckpointData | RejectedCheckpoint | undefined =
1280
+ const latestLocalCheckpoint:
1281
+ | { checkpointNumber: CheckpointNumber; l1: L1PublishedData }
1282
+ | CheckpointData
1283
+ | RejectedCheckpoint
1284
+ | undefined =
1222
1285
  lastSeenCheckpoint ??
1223
1286
  (await this.stores.blocks.getCheckpointData(latestLocalCheckpointNumber)) ??
1224
1287
  (await this.stores.blocks.getRejectedCheckpointByNumber(latestLocalCheckpointNumber));
@@ -0,0 +1,220 @@
1
+ import type { OutboxContract } from '@aztec/ethereum/contracts';
2
+ import type { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
3
+ import { chunkBy } from '@aztec/foundation/collection';
4
+ import type { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { type Logger, createLogger } from '@aztec/foundation/log';
6
+ import type { AztecAsyncKVStore } from '@aztec/kv-store';
7
+ import type { L2Block } from '@aztec/stdlib/block';
8
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
9
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
10
+ import { type L2ToL1MembershipWitness, computeL2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
11
+ import type { IndexedTxEffect, TxHash } from '@aztec/stdlib/tx';
12
+
13
+ /**
14
+ * Archiver-side view of the data the resolver needs to assemble a witness. The archiver implements
15
+ * each of these natively, so no L2 RPC plumbing is required.
16
+ */
17
+ export interface OutboxTreesArchiverView {
18
+ getBlocks(query: { epoch: EpochNumber; onlyCheckpointed: true }): Promise<L2Block[]>;
19
+ getBlock(query: { number: BlockNumber }): Promise<L2Block | undefined>;
20
+ getCheckpointsData(query: { epoch: EpochNumber }): Promise<CheckpointData[]>;
21
+ getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined>;
22
+ }
23
+
24
+ /** A cached per-epoch set of Outbox roots, tagged with the synced L1 block they were read at. */
25
+ type CachedRoots = {
26
+ /** The `MAX_CHECKPOINTS_PER_EPOCH`-length array of partial-proof roots the L1 Outbox holds for the epoch. */
27
+ roots: Fr[];
28
+ /** The node's synced L1 block number at the moment we fetched these roots. */
29
+ fetchedAtL1Block: bigint;
30
+ };
31
+
32
+ /**
33
+ * Holds an in-memory cache of per-epoch Outbox roots used to build L2-to-L1 message membership
34
+ * witnesses, plus the single-flight registry that dedupes concurrent fetches.
35
+ *
36
+ * Roots are fetched lazily on request and cached against the node's synced L1 block: a cached entry
37
+ * is reused only while the synced L1 block is unchanged, and re-fetched from L1 once the node
38
+ * advances. The cache is intentionally not persisted — entries are valid for at most one L1 slot, so
39
+ * there is nothing worth carrying across restarts. The four merkle-tree levels are rebuilt per
40
+ * request from the archiver's raw L2 data via `computeL2ToL1MembershipWitness`; no trees or
41
+ * intermediate out-hashes are cached.
42
+ *
43
+ * TODO: Re-add permanent caching for sealed-and-L1-finalized epochs so their roots can be frozen
44
+ * and served without any L1 read once they can no longer change. That logic was dropped here to keep
45
+ * the cache simple; it would likely want a persisted store again.
46
+ */
47
+ export class OutboxTreesResolver {
48
+ /** In-memory cache of per-epoch Outbox roots, keyed by epoch number. */
49
+ #cache: Map<EpochNumber, CachedRoots> = new Map();
50
+
51
+ /** Single-flight registry for in-flight roots fetches, keyed by epoch number. */
52
+ #pending: Map<EpochNumber, Promise<Fr[] | undefined>> = new Map();
53
+
54
+ /** Adapter exposing the slice of the node API that `computeL2ToL1MembershipWitness` requires. */
55
+ #node: Parameters<typeof computeL2ToL1MembershipWitness>[0];
56
+
57
+ constructor(
58
+ private readonly outbox: OutboxContract,
59
+ private readonly archiver: OutboxTreesArchiverView,
60
+ private readonly store: AztecAsyncKVStore,
61
+ private readonly getSyncedL1BlockNumber: () => Promise<bigint | undefined>,
62
+ private readonly epochDuration: number,
63
+ private readonly log: Logger = createLogger('archiver:outbox'),
64
+ ) {
65
+ this.#node = this.makeNodeView();
66
+ }
67
+
68
+ /**
69
+ * Builds the L2-to-L1 membership witness for `message` in tx `txHash`. Returns `undefined` if the
70
+ * tx isn't yet in a block/epoch, or if the Outbox holds no covering partial-proof root for the
71
+ * tx's checkpoint as of the node's synced L1 block — callers should retry in that case.
72
+ */
73
+ public async getL2ToL1MembershipWitness(
74
+ txHash: TxHash,
75
+ message: Fr,
76
+ messageIndexInTx?: number,
77
+ ): Promise<L2ToL1MembershipWitness | undefined> {
78
+ // Read the tx effect once up front only to learn which epoch's Outbox roots to fetch. The roots
79
+ // read hits L1, so it stays outside the store transaction below: holding the archiver's writer
80
+ // lock across a network round-trip would stall block sync.
81
+ const indexed = await this.archiver.getTxEffect(txHash);
82
+ if (!indexed) {
83
+ this.log.trace(`No tx effect for tx, no witness available`, { txHash });
84
+ return undefined;
85
+ }
86
+
87
+ // Derive the epoch from the tx's slot the same way the node assembles a mined receipt, so the
88
+ // witness helper sees the same view a `getTxReceipt` caller would.
89
+ const epochNumber = getEpochAtSlot(indexed.slotNumber, { epochDuration: this.epochDuration });
90
+ const roots = await this.#getRoots(epochNumber);
91
+ if (roots === undefined) {
92
+ return undefined;
93
+ }
94
+
95
+ const syncedBefore = await this.getSyncedL1BlockNumber();
96
+ try {
97
+ // Assemble the witness inside a single store transaction so every archiver read it depends on
98
+ // (the tx effect, the epoch's blocks, the target block and the checkpoint metadata) observes one
99
+ // consistent snapshot. `transactionAsync` serializes against writers, and the substore reads
100
+ // below bind to it automatically, so no store commit can land mid-assembly and splice together
101
+ // two different chain states — which would otherwise surface as a spurious "message does not
102
+ // exist" error even when the tx-effect index is healthy.
103
+ return await this.store.transactionAsync(async () => {
104
+ // Re-read the tx effect within the snapshot so the receipt's block number and tx index stay
105
+ // consistent with the block and checkpoint data read while building the witness. The epoch is
106
+ // reused from the pre-transaction read (it selected the roots above); if a reorg moved the tx
107
+ // to a different epoch in between, the block lookups simply miss and the helper returns
108
+ // undefined for the caller to retry.
109
+ const indexedInSnapshot = await this.archiver.getTxEffect(txHash);
110
+ if (!indexedInSnapshot) {
111
+ return undefined;
112
+ }
113
+ const receipt = {
114
+ txHash,
115
+ epochNumber,
116
+ blockNumber: indexedInSnapshot.l2BlockNumber,
117
+ txIndexInBlock: indexedInSnapshot.txIndexInBlock,
118
+ };
119
+ return await computeL2ToL1MembershipWitness(this.#node, roots, message, receipt, messageIndexInTx);
120
+ });
121
+ } catch (err) {
122
+ // The helper throws if the locally-assembled epoch root disagrees with the cached Outbox root.
123
+ // The cached roots are pinned to the node's synced L1 block, but the block / checkpoint data is
124
+ // read from a store snapshot taken after that fetch, so if the archiver advanced in between the
125
+ // two can reflect different heights and produce a transient mismatch. When the synced block moved
126
+ // during assembly we treat the mismatch as transient and return undefined so the caller can
127
+ // retry; a mismatch at a stable synced block is a genuine node/L1 disagreement and must surface.
128
+ const syncedAfter = await this.getSyncedL1BlockNumber();
129
+ if (syncedBefore !== syncedAfter && err instanceof Error && err.message.includes('does not match Outbox')) {
130
+ this.log.debug(`Transient outbox root mismatch during sync, returning no witness`, {
131
+ txHash,
132
+ epoch: epochNumber,
133
+ });
134
+ return undefined;
135
+ }
136
+ throw err;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Lazily returns the per-epoch Outbox roots, reusing the cached entry while the node's synced L1
142
+ * block is unchanged and re-fetching from L1 once it advances. Returns `undefined` if the node has
143
+ * not established a synced L1 block yet. Concurrent requests for the same epoch share a single
144
+ * in-flight fetch via {@link #pending}.
145
+ */
146
+ #getRoots(epoch: EpochNumber): Promise<Fr[] | undefined> {
147
+ const inFlight = this.#pending.get(epoch);
148
+ if (inFlight) {
149
+ return inFlight;
150
+ }
151
+
152
+ const promise = this.#refreshRoots(epoch).finally(() => {
153
+ this.#pending.delete(epoch);
154
+ });
155
+ this.#pending.set(epoch, promise);
156
+ return promise;
157
+ }
158
+
159
+ /**
160
+ * Single-flight body for {@link #getRoots}. Re-reads the cached entry and synced block here —
161
+ * rather than capturing them before winning the {@link #pending} slot — so a late entrant that
162
+ * missed the slot cannot overwrite a fresher entry the previous winner just wrote.
163
+ */
164
+ async #refreshRoots(epoch: EpochNumber): Promise<Fr[] | undefined> {
165
+ const synced = await this.getSyncedL1BlockNumber();
166
+ if (synced === undefined) {
167
+ // The archiver has no synced L1 block yet, so there is no consistent height to read the Outbox
168
+ // at. The caller retries once the node has synced.
169
+ return undefined;
170
+ }
171
+
172
+ const cached = this.#cache.get(epoch);
173
+ if (cached && cached.fetchedAtL1Block === synced) {
174
+ return cached.roots;
175
+ }
176
+
177
+ // TODO: Re-add permanent caching for sealed-and-L1-finalized epochs so we can skip the L1 read
178
+ // entirely once an epoch's roots can no longer change. For now the cache is valid only for the
179
+ // current synced L1 block and we re-query the Outbox whenever the node advances.
180
+ const roots = await this.outbox.getRoots(epoch, { blockNumber: synced });
181
+ this.#cache.set(epoch, { roots, fetchedAtL1Block: synced });
182
+ this.log.trace(`Fetched outbox roots for epoch ${epoch}`, {
183
+ epoch,
184
+ syncedL1Block: synced,
185
+ nonZeroRoots: roots.filter(r => !r.isZero()).length,
186
+ });
187
+ return roots;
188
+ }
189
+
190
+ /**
191
+ * Returns the L2-to-L1 messages in `epoch`, organized as `checkpoint[] → block[] → tx[] →
192
+ * message[]`. Mirrors `AztecNodeService.getL2ToL1Messages` so the resolver can run off the
193
+ * archiver directly without going through the node RPC surface.
194
+ */
195
+ async #getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
196
+ const blocks = await this.archiver.getBlocks({ epoch, onlyCheckpointed: true });
197
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
198
+ return blocksInCheckpoints.map(slotBlocks =>
199
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Builds the node-shaped adapter handed to `computeL2ToL1MembershipWitness`. The helper invokes
205
+ * `getL2ToL1Messages` / `getBlock` / `getCheckpointsData`; `getTxReceipt` is part of the helper's
206
+ * node type but is never invoked because we always pass an already-resolved receipt.
207
+ */
208
+ private makeNodeView(): Parameters<typeof computeL2ToL1MembershipWitness>[0] {
209
+ return {
210
+ getL2ToL1Messages: (epoch: EpochNumber) => this.#getL2ToL1Messages(epoch),
211
+ getBlock: ((param: BlockNumber) => this.archiver.getBlock({ number: param })) as Parameters<
212
+ typeof computeL2ToL1MembershipWitness
213
+ >[0]['getBlock'],
214
+ getCheckpointsData: (query: { epoch: EpochNumber }) => this.archiver.getCheckpointsData(query),
215
+ getTxReceipt: (() => {
216
+ throw new Error('OutboxTreesResolver always passes a resolved receipt; getTxReceipt must not be called');
217
+ }) as Parameters<typeof computeL2ToL1MembershipWitness>[0]['getTxReceipt'],
218
+ };
219
+ }
220
+ }