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

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 (116) hide show
  1. package/README.md +21 -6
  2. package/dest/archiver.d.ts +17 -12
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +108 -127
  5. package/dest/config.d.ts +3 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +3 -2
  8. package/dest/errors.d.ts +39 -10
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +52 -15
  11. package/dest/factory.d.ts +4 -2
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +29 -23
  14. package/dest/index.d.ts +2 -1
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -0
  17. package/dest/l1/bin/retrieve-calldata.js +35 -32
  18. package/dest/l1/calldata_retriever.d.ts +73 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +191 -259
  21. package/dest/l1/data_retrieval.d.ts +11 -11
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +38 -37
  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/validate_trace.d.ts +6 -3
  28. package/dest/l1/validate_trace.d.ts.map +1 -1
  29. package/dest/l1/validate_trace.js +13 -9
  30. package/dest/modules/data_source_base.d.ts +29 -23
  31. package/dest/modules/data_source_base.d.ts.map +1 -1
  32. package/dest/modules/data_source_base.js +55 -124
  33. package/dest/modules/data_store_updater.d.ts +43 -26
  34. package/dest/modules/data_store_updater.d.ts.map +1 -1
  35. package/dest/modules/data_store_updater.js +158 -129
  36. package/dest/modules/instrumentation.d.ts +19 -4
  37. package/dest/modules/instrumentation.d.ts.map +1 -1
  38. package/dest/modules/instrumentation.js +53 -18
  39. package/dest/modules/l1_synchronizer.d.ts +7 -9
  40. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  41. package/dest/modules/l1_synchronizer.js +186 -145
  42. package/dest/modules/validation.d.ts +1 -1
  43. package/dest/modules/validation.d.ts.map +1 -1
  44. package/dest/modules/validation.js +2 -2
  45. package/dest/store/block_store.d.ts +86 -34
  46. package/dest/store/block_store.d.ts.map +1 -1
  47. package/dest/store/block_store.js +414 -152
  48. package/dest/store/contract_class_store.d.ts +2 -3
  49. package/dest/store/contract_class_store.d.ts.map +1 -1
  50. package/dest/store/contract_class_store.js +16 -72
  51. package/dest/store/contract_instance_store.d.ts +1 -1
  52. package/dest/store/contract_instance_store.d.ts.map +1 -1
  53. package/dest/store/contract_instance_store.js +6 -2
  54. package/dest/store/kv_archiver_store.d.ts +80 -39
  55. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  56. package/dest/store/kv_archiver_store.js +86 -35
  57. package/dest/store/l2_tips_cache.d.ts +20 -0
  58. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  59. package/dest/store/l2_tips_cache.js +109 -0
  60. package/dest/store/log_store.d.ts +9 -6
  61. package/dest/store/log_store.d.ts.map +1 -1
  62. package/dest/store/log_store.js +151 -56
  63. package/dest/store/message_store.d.ts +5 -1
  64. package/dest/store/message_store.d.ts.map +1 -1
  65. package/dest/store/message_store.js +21 -9
  66. package/dest/test/fake_l1_state.d.ts +24 -4
  67. package/dest/test/fake_l1_state.d.ts.map +1 -1
  68. package/dest/test/fake_l1_state.js +133 -26
  69. package/dest/test/index.js +3 -1
  70. package/dest/test/mock_archiver.d.ts +1 -1
  71. package/dest/test/mock_archiver.d.ts.map +1 -1
  72. package/dest/test/mock_archiver.js +3 -2
  73. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  74. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  75. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  76. package/dest/test/mock_l2_block_source.d.ts +44 -23
  77. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  78. package/dest/test/mock_l2_block_source.js +185 -115
  79. package/dest/test/mock_structs.d.ts +6 -2
  80. package/dest/test/mock_structs.d.ts.map +1 -1
  81. package/dest/test/mock_structs.js +24 -10
  82. package/dest/test/noop_l1_archiver.d.ts +26 -0
  83. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  84. package/dest/test/noop_l1_archiver.js +71 -0
  85. package/package.json +14 -13
  86. package/src/archiver.ts +144 -159
  87. package/src/config.ts +9 -2
  88. package/src/errors.ts +82 -26
  89. package/src/factory.ts +46 -22
  90. package/src/index.ts +1 -0
  91. package/src/l1/README.md +25 -68
  92. package/src/l1/bin/retrieve-calldata.ts +45 -33
  93. package/src/l1/calldata_retriever.ts +250 -379
  94. package/src/l1/data_retrieval.ts +35 -41
  95. package/src/l1/spire_proposer.ts +7 -15
  96. package/src/l1/validate_trace.ts +24 -6
  97. package/src/modules/data_source_base.ts +98 -169
  98. package/src/modules/data_store_updater.ts +178 -160
  99. package/src/modules/instrumentation.ts +64 -20
  100. package/src/modules/l1_synchronizer.ts +212 -182
  101. package/src/modules/validation.ts +2 -2
  102. package/src/store/block_store.ts +533 -207
  103. package/src/store/contract_class_store.ts +16 -110
  104. package/src/store/contract_instance_store.ts +8 -5
  105. package/src/store/kv_archiver_store.ts +141 -59
  106. package/src/store/l2_tips_cache.ts +134 -0
  107. package/src/store/log_store.ts +232 -74
  108. package/src/store/message_store.ts +27 -10
  109. package/src/structs/inbox_message.ts +1 -1
  110. package/src/test/fake_l1_state.ts +180 -32
  111. package/src/test/index.ts +3 -0
  112. package/src/test/mock_archiver.ts +3 -2
  113. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  114. package/src/test/mock_l2_block_source.ts +247 -130
  115. package/src/test/mock_structs.ts +45 -15
  116. package/src/test/noop_l1_archiver.ts +114 -0
@@ -0,0 +1,71 @@
1
+ import { SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { Buffer32 } from '@aztec/foundation/buffer';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { getTelemetryClient } from '@aztec/telemetry-client';
5
+ import { mock } from 'jest-mock-extended';
6
+ import { EventEmitter } from 'node:events';
7
+ import { Archiver } from '../archiver.js';
8
+ import { ArchiverInstrumentation } from '../modules/instrumentation.js';
9
+ /** Noop L1 synchronizer for testing without L1 connectivity. */ class NoopL1Synchronizer {
10
+ tracer;
11
+ constructor(tracer){
12
+ this.tracer = tracer;
13
+ }
14
+ setConfig(_config) {}
15
+ getL1BlockNumber() {
16
+ return 0n;
17
+ }
18
+ getL1Timestamp() {
19
+ return undefined;
20
+ }
21
+ testEthereumNodeSynced() {
22
+ return Promise.resolve();
23
+ }
24
+ syncFromL1(_initialSyncComplete) {
25
+ return Promise.resolve();
26
+ }
27
+ }
28
+ /**
29
+ * Archiver with mocked L1 connectivity for testing.
30
+ * Uses mock L1 clients and a noop synchronizer, enabling tests that
31
+ * don't require real Ethereum connectivity.
32
+ */ export class NoopL1Archiver extends Archiver {
33
+ constructor(dataStore, l1Constants, instrumentation){
34
+ // Create mocks for L1 clients
35
+ const publicClient = mock();
36
+ const debugClient = mock();
37
+ const rollup = mock();
38
+ const blobClient = mock();
39
+ // Mock methods called during start()
40
+ blobClient.testSources.mockResolvedValue();
41
+ publicClient.getBlockNumber.mockResolvedValue(1n);
42
+ const events = new EventEmitter();
43
+ const synchronizer = new NoopL1Synchronizer(instrumentation.tracer);
44
+ super(publicClient, debugClient, rollup, {
45
+ registryAddress: EthAddress.ZERO,
46
+ governanceProposerAddress: EthAddress.ZERO,
47
+ slashingProposerAddress: EthAddress.ZERO
48
+ }, dataStore, {
49
+ pollingIntervalMs: 1000,
50
+ batchSize: 100,
51
+ skipValidateCheckpointAttestations: true,
52
+ maxAllowedEthClientDriftSeconds: 300,
53
+ ethereumAllowNoDebugHosts: true
54
+ }, blobClient, instrumentation, {
55
+ ...l1Constants,
56
+ l1StartBlockHash: Buffer32.random()
57
+ }, synchronizer, events);
58
+ }
59
+ /** Override start to skip L1 validation checks. */ start(_blockUntilSynced) {
60
+ // Just start the running promise without L1 checks
61
+ this.runningPromise.start();
62
+ return Promise.resolve();
63
+ }
64
+ /** Always reports as fully synced since there is no real L1 to sync from. */ getSyncedL2SlotNumber() {
65
+ return Promise.resolve(SlotNumber(Number.MAX_SAFE_INTEGER));
66
+ }
67
+ }
68
+ /** Creates an archiver with mocked L1 connectivity for testing. */ export async function createNoopL1Archiver(dataStore, l1Constants, telemetry = getTelemetryClient()) {
69
+ const instrumentation = await ArchiverInstrumentation.new(telemetry, ()=>dataStore.estimateSize());
70
+ return new NoopL1Archiver(dataStore, l1Constants, instrumentation);
71
+ }
package/package.json CHANGED
@@ -1,10 +1,11 @@
1
1
  {
2
2
  "name": "@aztec/archiver",
3
- "version": "0.0.1-commit.d431d1c",
3
+ "version": "0.0.1-commit.d939eb5aa",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
7
7
  "./test": "./dest/test/index.js",
8
+ "./test/noop-l1": "./dest/test/noop_l1_archiver.js",
8
9
  "./config": "./dest/config.js"
9
10
  },
10
11
  "typedocOptions": {
@@ -64,18 +65,18 @@
64
65
  ]
65
66
  },
66
67
  "dependencies": {
67
- "@aztec/blob-client": "0.0.1-commit.d431d1c",
68
- "@aztec/blob-lib": "0.0.1-commit.d431d1c",
69
- "@aztec/constants": "0.0.1-commit.d431d1c",
70
- "@aztec/epoch-cache": "0.0.1-commit.d431d1c",
71
- "@aztec/ethereum": "0.0.1-commit.d431d1c",
72
- "@aztec/foundation": "0.0.1-commit.d431d1c",
73
- "@aztec/kv-store": "0.0.1-commit.d431d1c",
74
- "@aztec/l1-artifacts": "0.0.1-commit.d431d1c",
75
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.d431d1c",
76
- "@aztec/protocol-contracts": "0.0.1-commit.d431d1c",
77
- "@aztec/stdlib": "0.0.1-commit.d431d1c",
78
- "@aztec/telemetry-client": "0.0.1-commit.d431d1c",
68
+ "@aztec/blob-client": "0.0.1-commit.d939eb5aa",
69
+ "@aztec/blob-lib": "0.0.1-commit.d939eb5aa",
70
+ "@aztec/constants": "0.0.1-commit.d939eb5aa",
71
+ "@aztec/epoch-cache": "0.0.1-commit.d939eb5aa",
72
+ "@aztec/ethereum": "0.0.1-commit.d939eb5aa",
73
+ "@aztec/foundation": "0.0.1-commit.d939eb5aa",
74
+ "@aztec/kv-store": "0.0.1-commit.d939eb5aa",
75
+ "@aztec/l1-artifacts": "0.0.1-commit.d939eb5aa",
76
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.d939eb5aa",
77
+ "@aztec/protocol-contracts": "0.0.1-commit.d939eb5aa",
78
+ "@aztec/stdlib": "0.0.1-commit.d939eb5aa",
79
+ "@aztec/telemetry-client": "0.0.1-commit.d939eb5aa",
79
80
  "lodash.groupby": "^4.6.0",
80
81
  "lodash.omit": "^4.5.0",
81
82
  "tslib": "^2.5.0",
package/src/archiver.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { BlobClientInterface } from '@aztec/blob-client/client';
2
- import { GENESIS_BLOCK_HEADER_HASH, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
3
2
  import { EpochCache } from '@aztec/epoch-cache';
4
3
  import { BlockTagTooOldError, RollupContract } from '@aztec/ethereum/contracts';
5
4
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
@@ -12,41 +11,40 @@ import { EthAddress } from '@aztec/foundation/eth-address';
12
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
13
12
  import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
14
13
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
15
- import { DateProvider } from '@aztec/foundation/timer';
14
+ import { DateProvider, elapsed } from '@aztec/foundation/timer';
16
15
  import {
17
16
  type ArchiverEmitter,
18
- type CheckpointId,
19
- GENESIS_CHECKPOINT_HEADER_HASH,
20
- L2BlockNew,
17
+ L2Block,
21
18
  type L2BlockSink,
22
19
  type L2Tips,
23
20
  type ValidateCheckpointResult,
24
21
  } from '@aztec/stdlib/block';
25
- import { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
22
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
26
23
  import {
27
24
  type L1RollupConstants,
28
- getEpochNumberAtTimestamp,
29
- getSlotAtTimestamp,
25
+ getEpochAtSlot,
26
+ getSlotAtNextL1Block,
30
27
  getSlotRangeForEpoch,
31
28
  getTimestampRangeForEpoch,
32
29
  } from '@aztec/stdlib/epoch-helpers';
33
30
  import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
34
31
 
35
32
  import { type ArchiverConfig, mapArchiverConfig } from './config.js';
36
- import { NoBlobBodiesFoundError } from './errors.js';
33
+ import { BlockAlreadyCheckpointedError, NoBlobBodiesFoundError } from './errors.js';
37
34
  import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
38
35
  import { ArchiverDataSourceBase } from './modules/data_source_base.js';
39
36
  import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
40
37
  import type { ArchiverInstrumentation } from './modules/instrumentation.js';
41
38
  import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
42
39
  import type { KVArchiverDataStore } from './store/kv_archiver_store.js';
40
+ import { L2TipsCache } from './store/l2_tips_cache.js';
43
41
 
44
42
  /** Export ArchiverEmitter for use in factory and tests. */
45
43
  export type { ArchiverEmitter };
46
44
 
47
45
  /** Request to add a block to the archiver, queued for processing by the sync loop. */
48
46
  type AddBlockRequest = {
49
- block: L2BlockNew;
47
+ block: L2Block;
50
48
  resolve: () => void;
51
49
  reject: (err: Error) => void;
52
50
  };
@@ -68,7 +66,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
68
66
  public readonly events: ArchiverEmitter;
69
67
 
70
68
  /** A loop in which we will be continually fetching new checkpoints. */
71
- private runningPromise: RunningPromise;
69
+ protected runningPromise: RunningPromise;
72
70
 
73
71
  /** L1 synchronizer that handles fetching checkpoints and messages from L1. */
74
72
  private readonly synchronizer: ArchiverL1Synchronizer;
@@ -82,19 +80,23 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
82
80
  /** Helper to handle updates to the store */
83
81
  private readonly updater: ArchiverDataStoreUpdater;
84
82
 
83
+ /** In-memory cache for L2 chain tips. */
84
+ private readonly l2TipsCache: L2TipsCache;
85
+
85
86
  public readonly tracer: Tracer;
86
87
 
88
+ private readonly instrumentation: ArchiverInstrumentation;
89
+
87
90
  /**
88
91
  * Creates a new instance of the Archiver.
89
92
  * @param publicClient - A client for interacting with the Ethereum node.
90
93
  * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
91
94
  * @param rollup - Rollup contract instance.
92
95
  * @param inbox - Inbox contract instance.
93
- * @param l1Addresses - L1 contract addresses (registry, governance proposer, slash factory, slashing proposer).
96
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
94
97
  * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
95
98
  * @param config - Archiver configuration options.
96
99
  * @param blobClient - Client for retrieving blob data.
97
- * @param epochCache - Cache for epoch-related data.
98
100
  * @param dateProvider - Provider for current date/time.
99
101
  * @param instrumentation - Instrumentation for metrics and tracing.
100
102
  * @param l1Constants - L1 rollup constants.
@@ -104,10 +106,9 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
104
106
  private readonly publicClient: ViemPublicClient,
105
107
  private readonly debugClient: ViemPublicDebugClient,
106
108
  private readonly rollup: RollupContract,
107
- private readonly l1Addresses: Pick<
108
- L1ContractAddresses,
109
- 'registryAddress' | 'governanceProposerAddress' | 'slashFactoryAddress'
110
- > & { slashingProposerAddress: EthAddress },
109
+ private readonly l1Addresses: Pick<L1ContractAddresses, 'registryAddress' | 'governanceProposerAddress'> & {
110
+ slashingProposerAddress: EthAddress;
111
+ },
111
112
  readonly dataStore: KVArchiverDataStore,
112
113
  private config: {
113
114
  pollingIntervalMs: number;
@@ -118,18 +119,26 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
118
119
  },
119
120
  private readonly blobClient: BlobClientInterface,
120
121
  instrumentation: ArchiverInstrumentation,
121
- protected override readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
122
+ protected override readonly l1Constants: L1RollupConstants & {
123
+ l1StartBlockHash: Buffer32;
124
+ genesisArchiveRoot: Fr;
125
+ },
122
126
  synchronizer: ArchiverL1Synchronizer,
123
127
  events: ArchiverEmitter,
128
+ l2TipsCache?: L2TipsCache,
124
129
  private readonly log: Logger = createLogger('archiver'),
125
130
  ) {
126
131
  super(dataStore, l1Constants);
127
132
 
128
133
  this.tracer = instrumentation.tracer;
134
+ this.instrumentation = instrumentation;
129
135
  this.initialSyncPromise = promiseWithResolvers();
130
136
  this.synchronizer = synchronizer;
131
137
  this.events = events;
132
- this.updater = new ArchiverDataStoreUpdater(this.dataStore);
138
+ this.l2TipsCache = l2TipsCache ?? new L2TipsCache(this.dataStore.blockStore);
139
+ this.updater = new ArchiverDataStoreUpdater(this.dataStore, this.l2TipsCache, {
140
+ rollupManaLimit: l1Constants.rollupManaLimit,
141
+ });
133
142
 
134
143
  // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
135
144
  // are done as fast as possible. This then gets updated once the initial sync completes.
@@ -158,7 +167,11 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
158
167
 
159
168
  await this.blobClient.testSources();
160
169
  await this.synchronizer.testEthereumNodeSynced();
161
- await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
170
+ await validateAndLogTraceAvailability(
171
+ this.debugClient,
172
+ this.config.ethereumAllowNoDebugHosts ?? false,
173
+ this.log.getBindings(),
174
+ );
162
175
 
163
176
  // Log initial state for the archiver
164
177
  const { l1StartBlock } = this.l1Constants;
@@ -187,7 +200,7 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
187
200
  * @param block - The L2 block to add.
188
201
  * @returns A promise that resolves when the block has been added to the store, or rejects on error.
189
202
  */
190
- public addBlock(block: L2BlockNew): Promise<void> {
203
+ public addBlock(block: L2Block): Promise<void> {
191
204
  return new Promise<void>((resolve, reject) => {
192
205
  this.blockQueue.push({ block, resolve, reject });
193
206
  this.log.debug(`Queued block ${block.number} for processing`);
@@ -198,6 +211,10 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
198
211
  });
199
212
  }
200
213
 
214
+ public async setProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
215
+ await this.updater.setProposedCheckpoint(pending);
216
+ }
217
+
201
218
  /**
202
219
  * Processes all queued blocks, adding them to the store.
203
220
  * Called at the beginning of each sync iteration.
@@ -212,13 +229,34 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
212
229
  const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
213
230
  this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
214
231
 
232
+ // Calculate slot threshold for validation
233
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
234
+ const slotAtNextL1Block =
235
+ l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
236
+
215
237
  // Process each block individually to properly resolve/reject each promise
216
238
  for (const { block, resolve, reject } of queuedItems) {
239
+ const blockSlot = block.header.globalVariables.slotNumber;
240
+ if (slotAtNextL1Block !== undefined && blockSlot < slotAtNextL1Block) {
241
+ this.log.warn(
242
+ `Rejecting proposed block ${block.number} for past slot ${blockSlot} (current is ${slotAtNextL1Block})`,
243
+ { block: block.toBlockInfo(), l1Timestamp, slotAtNextL1Block },
244
+ );
245
+ reject(new Error(`Block ${block.number} is for past slot ${blockSlot} (current is ${slotAtNextL1Block})`));
246
+ continue;
247
+ }
248
+
217
249
  try {
218
- await this.updater.addBlocks([block]);
250
+ const [durationMs] = await elapsed(() => this.updater.addProposedBlock(block));
251
+ this.instrumentation.processNewProposedBlock(durationMs, block);
219
252
  this.log.debug(`Added block ${block.number} to store`);
220
253
  resolve();
221
254
  } catch (err: any) {
255
+ if (err instanceof BlockAlreadyCheckpointedError) {
256
+ this.log.debug(`Proposed block ${block.number} matches already checkpointed block, ignoring late proposal`);
257
+ resolve();
258
+ continue;
259
+ }
222
260
  this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
223
261
  reject(err);
224
262
  }
@@ -310,21 +348,57 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
310
348
  return Promise.resolve(this.synchronizer.getL1Timestamp());
311
349
  }
312
350
 
313
- public getL2SlotNumber(): Promise<SlotNumber | undefined> {
351
+ public async getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
352
+ // The synced L2 slot is the latest slot for which we have all L1 data,
353
+ // either because we have seen all L1 blocks for that slot, or because
354
+ // we have seen the corresponding checkpoint.
355
+
356
+ let slotFromL1Sync: SlotNumber | undefined;
314
357
  const l1Timestamp = this.synchronizer.getL1Timestamp();
315
- return Promise.resolve(l1Timestamp === undefined ? undefined : getSlotAtTimestamp(l1Timestamp, this.l1Constants));
358
+ if (l1Timestamp !== undefined) {
359
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
360
+ if (Number(nextL1BlockSlot) > 0) {
361
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
362
+ }
363
+ }
364
+
365
+ let slotFromCheckpoint: SlotNumber | undefined;
366
+ const latestCheckpointNumber = await this.store.getSynchedCheckpointNumber();
367
+ if (latestCheckpointNumber > 0) {
368
+ const checkpointData = await this.store.getCheckpointData(latestCheckpointNumber);
369
+ if (checkpointData) {
370
+ slotFromCheckpoint = checkpointData.header.slotNumber;
371
+ }
372
+ }
373
+
374
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
375
+ return undefined;
376
+ }
377
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
316
378
  }
317
379
 
318
- public getL2EpochNumber(): Promise<EpochNumber | undefined> {
319
- const l1Timestamp = this.synchronizer.getL1Timestamp();
320
- return Promise.resolve(
321
- l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(l1Timestamp, this.l1Constants),
322
- );
380
+ public async getSyncedL2EpochNumber(): Promise<EpochNumber | undefined> {
381
+ const syncedSlot = await this.getSyncedL2SlotNumber();
382
+ if (syncedSlot === undefined) {
383
+ return undefined;
384
+ }
385
+ // An epoch is fully synced when all its slots are synced.
386
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
387
+ // Otherwise, only the previous epoch is fully synced.
388
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
389
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
390
+ if (syncedSlot >= endSlot) {
391
+ return epoch;
392
+ }
393
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
323
394
  }
324
395
 
325
396
  public async isEpochComplete(epochNumber: EpochNumber): Promise<boolean> {
326
- // The epoch is complete if the current L2 block is the last one in the epoch (or later)
327
- const header = await this.getBlockHeader('latest');
397
+ // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
398
+ // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
399
+ // prematurely when proposed blocks have been pushed to the archiver but not yet checkpointed on L1.
400
+ const checkpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
401
+ const header = checkpointedBlockNumber > 0 ? await this.getBlockHeader(checkpointedBlockNumber) : undefined;
328
402
  const slot = header ? header.globalVariables.slotNumber : undefined;
329
403
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
330
404
  if (slot && slot >= endSlot) {
@@ -355,8 +429,8 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
355
429
  return this.initialSyncComplete;
356
430
  }
357
431
 
358
- public unwindCheckpoints(from: CheckpointNumber, checkpointsToUnwind: number): Promise<boolean> {
359
- return this.updater.unwindCheckpoints(from, checkpointsToUnwind);
432
+ public removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
433
+ return this.updater.removeCheckpointsAfter(checkpointNumber);
360
434
  }
361
435
 
362
436
  /** Used by TXE to add checkpoints directly without syncing from L1. */
@@ -364,125 +438,15 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
364
438
  checkpoints: PublishedCheckpoint[],
365
439
  pendingChainValidationStatus?: ValidateCheckpointResult,
366
440
  ): Promise<boolean> {
367
- await this.updater.setNewCheckpointData(checkpoints, pendingChainValidationStatus);
441
+ await this.updater.addCheckpoints(checkpoints, pendingChainValidationStatus);
368
442
  return true;
369
443
  }
370
444
 
371
- public async getL2Tips(): Promise<L2Tips> {
372
- const [latestBlockNumber, provenBlockNumber, checkpointedBlockNumber] = await Promise.all([
373
- this.getBlockNumber(),
374
- this.getProvenBlockNumber(),
375
- this.getCheckpointedBlockNumber(),
376
- ] as const);
377
-
378
- // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
379
- // We just force it 2 epochs worth of proven data for now.
380
- // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
381
- const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1Constants.epochDuration * 2, 0));
382
-
383
- const beforeInitialblockNumber = BlockNumber(INITIAL_L2_BLOCK_NUM - 1);
384
-
385
- // Get the latest block header and checkpointed blocks for proven, finalised and checkpointed blocks
386
- const [latestBlockHeader, provenCheckpointedBlock, finalizedCheckpointedBlock, checkpointedBlock] =
387
- await Promise.all([
388
- latestBlockNumber > beforeInitialblockNumber ? this.getBlockHeader(latestBlockNumber) : undefined,
389
- provenBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(provenBlockNumber) : undefined,
390
- finalizedBlockNumber > beforeInitialblockNumber ? this.getCheckpointedBlock(finalizedBlockNumber) : undefined,
391
- checkpointedBlockNumber > beforeInitialblockNumber
392
- ? this.getCheckpointedBlock(checkpointedBlockNumber)
393
- : undefined,
394
- ] as const);
395
-
396
- if (latestBlockNumber > beforeInitialblockNumber && !latestBlockHeader) {
397
- throw new Error(`Failed to retrieve latest block header for block ${latestBlockNumber}`);
398
- }
399
-
400
- // Checkpointed blocks must exist for proven, finalized and checkpointed tips if they are beyond the initial block number.
401
- if (checkpointedBlockNumber > beforeInitialblockNumber && !checkpointedBlock?.block.header) {
402
- throw new Error(
403
- `Failed to retrieve checkpointed block header for block ${checkpointedBlockNumber} (latest block is ${latestBlockNumber})`,
404
- );
405
- }
406
-
407
- if (provenBlockNumber > beforeInitialblockNumber && !provenCheckpointedBlock?.block.header) {
408
- throw new Error(
409
- `Failed to retrieve proven checkpointed for block ${provenBlockNumber} (latest block is ${latestBlockNumber})`,
410
- );
411
- }
412
-
413
- if (finalizedBlockNumber > beforeInitialblockNumber && !finalizedCheckpointedBlock?.block.header) {
414
- throw new Error(
415
- `Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`,
416
- );
417
- }
418
-
419
- const latestBlockHeaderHash = (await latestBlockHeader?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
420
- const provenBlockHeaderHash = (await provenCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
421
- const finalizedBlockHeaderHash =
422
- (await finalizedCheckpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
423
- const checkpointedBlockHeaderHash = (await checkpointedBlock?.block.header?.hash()) ?? GENESIS_BLOCK_HEADER_HASH;
424
-
425
- // Now attempt to retrieve checkpoints for proven, finalised and checkpointed blocks
426
- const [[provenBlockCheckpoint], [finalizedBlockCheckpoint], [checkpointedBlockCheckpoint]] = await Promise.all([
427
- provenCheckpointedBlock !== undefined
428
- ? await this.getPublishedCheckpoints(provenCheckpointedBlock?.checkpointNumber, 1)
429
- : [undefined],
430
- finalizedCheckpointedBlock !== undefined
431
- ? await this.getPublishedCheckpoints(finalizedCheckpointedBlock?.checkpointNumber, 1)
432
- : [undefined],
433
- checkpointedBlock !== undefined
434
- ? await this.getPublishedCheckpoints(checkpointedBlock?.checkpointNumber, 1)
435
- : [undefined],
436
- ]);
437
-
438
- const initialcheckpointId: CheckpointId = {
439
- number: CheckpointNumber.ZERO,
440
- hash: GENESIS_CHECKPOINT_HEADER_HASH.toString(),
441
- };
442
-
443
- const makeCheckpointId = (checkpoint: PublishedCheckpoint | undefined) => {
444
- if (checkpoint === undefined) {
445
- return initialcheckpointId;
446
- }
447
- return {
448
- number: checkpoint.checkpoint.number,
449
- hash: checkpoint.checkpoint.hash().toString(),
450
- };
451
- };
452
-
453
- const l2Tips: L2Tips = {
454
- proposed: {
455
- number: latestBlockNumber,
456
- hash: latestBlockHeaderHash.toString(),
457
- },
458
- proven: {
459
- block: {
460
- number: provenBlockNumber,
461
- hash: provenBlockHeaderHash.toString(),
462
- },
463
- checkpoint: makeCheckpointId(provenBlockCheckpoint),
464
- },
465
- finalized: {
466
- block: {
467
- number: finalizedBlockNumber,
468
- hash: finalizedBlockHeaderHash.toString(),
469
- },
470
- checkpoint: makeCheckpointId(finalizedBlockCheckpoint),
471
- },
472
- checkpointed: {
473
- block: {
474
- number: checkpointedBlockNumber,
475
- hash: checkpointedBlockHeaderHash.toString(),
476
- },
477
- checkpoint: makeCheckpointId(checkpointedBlockCheckpoint),
478
- },
479
- };
480
-
481
- return l2Tips;
445
+ public getL2Tips(): Promise<L2Tips> {
446
+ return this.l2TipsCache.getL2Tips();
482
447
  }
483
448
 
484
449
  public async rollbackTo(targetL2BlockNumber: BlockNumber): Promise<void> {
485
- // TODO(pw/mbps): This still assumes 1 block per checkpoint
486
450
  const currentBlocks = await this.getL2Tips();
487
451
  const currentL2Block = currentBlocks.proposed.number;
488
452
  const currentProvenBlock = currentBlocks.proven.block.number;
@@ -490,13 +454,29 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
490
454
  if (targetL2BlockNumber >= currentL2Block) {
491
455
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
492
456
  }
493
- const blocksToUnwind = currentL2Block - targetL2BlockNumber;
494
457
  const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
495
458
  if (!targetL2Block) {
496
459
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
497
460
  }
461
+ const targetCheckpointNumber = targetL2Block.checkpointNumber;
462
+
463
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
464
+ const checkpointData = await this.store.getCheckpointData(targetCheckpointNumber);
465
+ if (checkpointData) {
466
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
467
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
468
+ const previousCheckpointBoundary =
469
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
470
+ throw new Error(
471
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
472
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
473
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
474
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
475
+ );
476
+ }
477
+ }
478
+
498
479
  const targetL1BlockNumber = targetL2Block.l1.blockNumber;
499
- const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
500
480
  const targetL1Block = await this.publicClient.getBlock({
501
481
  blockNumber: targetL1BlockNumber,
502
482
  includeTransactions: false,
@@ -505,21 +485,26 @@ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Tra
505
485
  throw new Error(`Missing L1 block ${targetL1BlockNumber}`);
506
486
  }
507
487
  const targetL1BlockHash = Buffer32.fromString(targetL1Block.hash);
508
- this.log.info(`Unwinding ${blocksToUnwind} checkpoints from L2 block ${currentL2Block}`);
509
- await this.updater.unwindCheckpoints(CheckpointNumber(currentL2Block), blocksToUnwind);
510
- this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
488
+ this.log.info(
489
+ `Removing checkpoints after checkpoint ${targetCheckpointNumber} (target block ${targetL2BlockNumber})`,
490
+ );
491
+ await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
492
+ this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
511
493
  await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
512
494
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
513
495
  await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
514
- await this.store.setMessageSynchedL1Block({ l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash });
496
+ await this.store.setMessageSyncState(
497
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
498
+ undefined,
499
+ );
515
500
  if (targetL2BlockNumber < currentProvenBlock) {
516
- this.log.info(`Clearing proven L2 block number`);
517
- await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
501
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
502
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
503
+ }
504
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
505
+ if (targetL2BlockNumber < currentFinalizedBlock) {
506
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
507
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
518
508
  }
519
- // TODO(palla/reorg): Set the finalized block when we add support for it.
520
- // if (targetL2BlockNumber < currentFinalizedBlock) {
521
- // this.log.info(`Clearing finalized L2 block number`);
522
- // await this.store.setFinalizedL2BlockNumber(0);
523
- // }
524
509
  }
525
510
  }
package/src/config.ts CHANGED
@@ -8,7 +8,12 @@ import {
8
8
  getConfigFromMappings,
9
9
  numberConfigHelper,
10
10
  } from '@aztec/foundation/config';
11
- import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
11
+ import {
12
+ type ChainConfig,
13
+ type PipelineConfig,
14
+ chainConfigMappings,
15
+ pipelineConfigMappings,
16
+ } from '@aztec/stdlib/config';
12
17
  import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
13
18
 
14
19
  /**
@@ -21,11 +26,13 @@ import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
21
26
  export type ArchiverConfig = ArchiverSpecificConfig &
22
27
  L1ReaderConfig &
23
28
  L1ContractsConfig &
29
+ PipelineConfig & // required to pass through to epoch cache
24
30
  BlobClientConfig &
25
31
  ChainConfig;
26
32
 
27
33
  export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
28
34
  ...blobClientConfigMapping,
35
+ ...pipelineConfigMappings,
29
36
  archiverPollingIntervalMS: {
30
37
  env: 'ARCHIVER_POLLING_INTERVAL_MS',
31
38
  description: 'The polling interval in ms for retrieving new L2 blocks and encrypted logs.',
@@ -43,7 +50,7 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
43
50
  },
44
51
  archiverStoreMapSizeKb: {
45
52
  env: 'ARCHIVER_STORE_MAP_SIZE_KB',
46
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
53
+ parseEnv: (val: string) => +val,
47
54
  description: 'The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKb.',
48
55
  },
49
56
  skipValidateCheckpointAttestations: {