@aztec/archiver 0.0.1-commit.9b94fc1 → 0.0.1-commit.c7c42ec

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 (123) hide show
  1. package/dest/archiver/archiver.d.ts +96 -79
  2. package/dest/archiver/archiver.d.ts.map +1 -1
  3. package/dest/archiver/archiver.js +451 -214
  4. package/dest/archiver/archiver_store.d.ts +100 -47
  5. package/dest/archiver/archiver_store.d.ts.map +1 -1
  6. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  8. package/dest/archiver/archiver_store_test_suite.js +1867 -386
  9. package/dest/archiver/config.d.ts +5 -4
  10. package/dest/archiver/config.d.ts.map +1 -1
  11. package/dest/archiver/config.js +10 -3
  12. package/dest/archiver/errors.d.ts +25 -1
  13. package/dest/archiver/errors.d.ts.map +1 -1
  14. package/dest/archiver/errors.js +37 -0
  15. package/dest/archiver/index.d.ts +2 -2
  16. package/dest/archiver/index.d.ts.map +1 -1
  17. package/dest/archiver/instrumentation.d.ts +3 -1
  18. package/dest/archiver/instrumentation.d.ts.map +1 -1
  19. package/dest/archiver/instrumentation.js +11 -0
  20. package/dest/archiver/kv_archiver_store/block_store.d.ts +51 -18
  21. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  22. package/dest/archiver/kv_archiver_store/block_store.js +324 -87
  23. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  24. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  25. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  26. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  27. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  28. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +46 -56
  29. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  30. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +65 -48
  31. package/dest/archiver/kv_archiver_store/log_store.d.ts +12 -16
  32. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  33. package/dest/archiver/kv_archiver_store/log_store.js +149 -84
  34. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  35. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  36. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  37. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  38. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  39. package/dest/archiver/l1/bin/retrieve-calldata.js +149 -0
  40. package/dest/archiver/l1/calldata_retriever.d.ts +112 -0
  41. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  42. package/dest/archiver/l1/calldata_retriever.js +471 -0
  43. package/dest/archiver/l1/data_retrieval.d.ts +90 -0
  44. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  45. package/dest/archiver/{data_retrieval.js → l1/data_retrieval.js} +52 -107
  46. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  47. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  48. package/dest/archiver/l1/debug_tx.js +73 -0
  49. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  50. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  51. package/dest/archiver/l1/spire_proposer.js +157 -0
  52. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  53. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  54. package/dest/archiver/l1/trace_tx.js +91 -0
  55. package/dest/archiver/l1/types.d.ts +12 -0
  56. package/dest/archiver/l1/types.d.ts.map +1 -0
  57. package/dest/archiver/l1/types.js +3 -0
  58. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  59. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  60. package/dest/archiver/l1/validate_trace.js +150 -0
  61. package/dest/archiver/structs/inbox_message.d.ts +4 -4
  62. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  63. package/dest/archiver/structs/inbox_message.js +6 -5
  64. package/dest/archiver/structs/published.d.ts +1 -2
  65. package/dest/archiver/structs/published.d.ts.map +1 -1
  66. package/dest/factory.d.ts +2 -2
  67. package/dest/factory.d.ts.map +1 -1
  68. package/dest/factory.js +4 -3
  69. package/dest/index.d.ts +2 -2
  70. package/dest/index.d.ts.map +1 -1
  71. package/dest/index.js +1 -1
  72. package/dest/test/mock_archiver.d.ts +16 -8
  73. package/dest/test/mock_archiver.d.ts.map +1 -1
  74. package/dest/test/mock_archiver.js +19 -14
  75. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  76. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  77. package/dest/test/mock_l1_to_l2_message_source.js +10 -9
  78. package/dest/test/mock_l2_block_source.d.ts +18 -7
  79. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  80. package/dest/test/mock_l2_block_source.js +37 -23
  81. package/dest/test/mock_structs.d.ts +3 -2
  82. package/dest/test/mock_structs.d.ts.map +1 -1
  83. package/dest/test/mock_structs.js +9 -8
  84. package/package.json +17 -16
  85. package/src/archiver/archiver.ts +595 -296
  86. package/src/archiver/archiver_store.ts +113 -46
  87. package/src/archiver/archiver_store_test_suite.ts +1932 -353
  88. package/src/archiver/config.ts +15 -10
  89. package/src/archiver/errors.ts +64 -0
  90. package/src/archiver/index.ts +1 -1
  91. package/src/archiver/instrumentation.ts +14 -0
  92. package/src/archiver/kv_archiver_store/block_store.ts +442 -101
  93. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  94. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  95. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +87 -71
  96. package/src/archiver/kv_archiver_store/log_store.ts +209 -99
  97. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  98. package/src/archiver/l1/README.md +98 -0
  99. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  100. package/src/archiver/l1/calldata_retriever.ts +641 -0
  101. package/src/archiver/{data_retrieval.ts → l1/data_retrieval.ts} +101 -165
  102. package/src/archiver/l1/debug_tx.ts +99 -0
  103. package/src/archiver/l1/spire_proposer.ts +160 -0
  104. package/src/archiver/l1/trace_tx.ts +128 -0
  105. package/src/archiver/l1/types.ts +13 -0
  106. package/src/archiver/l1/validate_trace.ts +211 -0
  107. package/src/archiver/structs/inbox_message.ts +8 -8
  108. package/src/archiver/structs/published.ts +0 -1
  109. package/src/factory.ts +4 -3
  110. package/src/index.ts +1 -1
  111. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  112. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  113. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  114. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  115. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  116. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  117. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  118. package/src/test/mock_archiver.ts +22 -16
  119. package/src/test/mock_l1_to_l2_message_source.ts +10 -9
  120. package/src/test/mock_l2_block_source.ts +45 -25
  121. package/src/test/mock_structs.ts +10 -9
  122. package/dest/archiver/data_retrieval.d.ts +0 -79
  123. package/dest/archiver/data_retrieval.d.ts.map +0 -1
@@ -4,36 +4,44 @@ function _ts_decorate(decorators, target, key, desc) {
4
4
  else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  }
7
+ import { GENESIS_BLOCK_HEADER_HASH } from '@aztec/constants';
7
8
  import { EpochCache } from '@aztec/epoch-cache';
8
- import { BlockTagTooOldError, InboxContract, RollupContract, createEthereumChain } from '@aztec/ethereum';
9
+ import { createEthereumChain } from '@aztec/ethereum/chain';
10
+ import { BlockTagTooOldError, InboxContract, RollupContract } from '@aztec/ethereum/contracts';
9
11
  import { maxBigint } from '@aztec/foundation/bigint';
12
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
10
13
  import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
11
14
  import { merge, pick } from '@aztec/foundation/collection';
12
- import { Fr } from '@aztec/foundation/fields';
15
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
16
  import { createLogger } from '@aztec/foundation/log';
14
17
  import { promiseWithResolvers } from '@aztec/foundation/promise';
15
18
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
16
19
  import { count } from '@aztec/foundation/string';
17
20
  import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
21
+ import { isDefined } from '@aztec/foundation/types';
18
22
  import { ContractClassPublishedEvent, PrivateFunctionBroadcastedEvent, UtilityFunctionBroadcastedEvent } from '@aztec/protocol-contracts/class-registry';
19
23
  import { ContractInstancePublishedEvent, ContractInstanceUpdatedEvent } from '@aztec/protocol-contracts/instance-registry';
20
- import { L2Block, L2BlockSourceEvents, PublishedL2Block } from '@aztec/stdlib/block';
24
+ import { CommitteeAttestation, L2Block, L2BlockSourceEvents, PublishedL2Block } from '@aztec/stdlib/block';
25
+ import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
21
26
  import { computePublicBytecodeCommitment, isValidPrivateFunctionMembershipProof, isValidUtilityFunctionMembershipProof } from '@aztec/stdlib/contract';
22
27
  import { getEpochAtSlot, getEpochNumberAtTimestamp, getSlotAtTimestamp, getSlotRangeForEpoch, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
28
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
23
29
  import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
24
30
  import { EventEmitter } from 'events';
25
31
  import groupBy from 'lodash.groupby';
26
32
  import { createPublicClient, fallback, http } from 'viem';
27
- import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from './data_retrieval.js';
28
- import { InitialBlockNumberNotSequentialError, NoBlobBodiesFoundError } from './errors.js';
33
+ import { InitialCheckpointNumberNotSequentialError, NoBlobBodiesFoundError } from './errors.js';
29
34
  import { ArchiverInstrumentation } from './instrumentation.js';
35
+ import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from './l1/data_retrieval.js';
36
+ import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
30
37
  import { validateCheckpointAttestations } from './validation.js';
31
38
  function mapArchiverConfig(config) {
32
39
  return {
33
40
  pollingIntervalMs: config.archiverPollingIntervalMS,
34
41
  batchSize: config.archiverBatchSize,
35
42
  skipValidateBlockAttestations: config.skipValidateBlockAttestations,
36
- maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds
43
+ maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds,
44
+ ethereumAllowNoDebugHosts: config.ethereumAllowNoDebugHosts
37
45
  };
38
46
  }
39
47
  /**
@@ -42,10 +50,11 @@ function mapArchiverConfig(config) {
42
50
  * concern themselves with it.
43
51
  */ export class Archiver extends EventEmitter {
44
52
  publicClient;
53
+ debugClient;
45
54
  l1Addresses;
46
55
  dataStore;
47
56
  config;
48
- blobSinkClient;
57
+ blobClient;
49
58
  epochCache;
50
59
  dateProvider;
51
60
  instrumentation;
@@ -59,18 +68,20 @@ function mapArchiverConfig(config) {
59
68
  l1Timestamp;
60
69
  initialSyncComplete;
61
70
  initialSyncPromise;
71
+ /** Queue of blocks to be added to the store, processed by the sync loop. */ blockQueue;
62
72
  tracer;
63
73
  /**
64
74
  * Creates a new instance of the Archiver.
65
75
  * @param publicClient - A client for interacting with the Ethereum node.
76
+ * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
66
77
  * @param rollupAddress - Ethereum address of the rollup contract.
67
78
  * @param inboxAddress - Ethereum address of the inbox contract.
68
79
  * @param registryAddress - Ethereum address of the registry contract.
69
80
  * @param pollingIntervalMs - The interval for polling for L1 logs (in milliseconds).
70
81
  * @param store - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
71
82
  * @param log - A logger.
72
- */ constructor(publicClient, l1Addresses, dataStore, config, blobSinkClient, epochCache, dateProvider, instrumentation, l1constants, log = createLogger('archiver')){
73
- super(), this.publicClient = publicClient, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobSinkClient = blobSinkClient, this.epochCache = epochCache, this.dateProvider = dateProvider, this.instrumentation = instrumentation, this.l1constants = l1constants, this.log = log, this.initialSyncComplete = false;
83
+ */ constructor(publicClient, debugClient, l1Addresses, dataStore, config, blobClient, epochCache, dateProvider, instrumentation, l1constants, log = createLogger('archiver')){
84
+ super(), this.publicClient = publicClient, this.debugClient = debugClient, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobClient = blobClient, this.epochCache = epochCache, this.dateProvider = dateProvider, this.instrumentation = instrumentation, this.l1constants = l1constants, this.log = log, this.initialSyncComplete = false, this.blockQueue = [];
74
85
  this.tracer = instrumentation.tracer;
75
86
  this.store = new ArchiverStoreHelper(dataStore);
76
87
  this.rollup = new RollupContract(publicClient, l1Addresses.rollupAddress);
@@ -90,15 +101,27 @@ function mapArchiverConfig(config) {
90
101
  const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
91
102
  const publicClient = createPublicClient({
92
103
  chain: chain.chainInfo,
93
- transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
104
+ transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
105
+ batch: false
106
+ }))),
107
+ pollingInterval: config.viemPollingIntervalMS
108
+ });
109
+ // Create debug client using debug RPC URLs if available, otherwise fall back to regular RPC URLs
110
+ const debugRpcUrls = config.l1DebugRpcUrls.length > 0 ? config.l1DebugRpcUrls : config.l1RpcUrls;
111
+ const debugClient = createPublicClient({
112
+ chain: chain.chainInfo,
113
+ transport: fallback(debugRpcUrls.map((url)=>http(url, {
114
+ batch: false
115
+ }))),
94
116
  pollingInterval: config.viemPollingIntervalMS
95
117
  });
96
118
  const rollup = new RollupContract(publicClient, config.l1Contracts.rollupAddress);
97
- const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, genesisArchiveRoot] = await Promise.all([
119
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, genesisArchiveRoot, slashingProposerAddress] = await Promise.all([
98
120
  rollup.getL1StartBlock(),
99
121
  rollup.getL1GenesisTime(),
100
122
  rollup.getProofSubmissionEpochs(),
101
- rollup.getGenesisArchiveTreeRoot()
123
+ rollup.getGenesisArchiveTreeRoot(),
124
+ rollup.getSlashingProposerAddress()
102
125
  ]);
103
126
  const l1StartBlockHash = await publicClient.getBlock({
104
127
  blockNumber: l1StartBlock,
@@ -118,11 +141,15 @@ function mapArchiverConfig(config) {
118
141
  const opts = merge({
119
142
  pollingIntervalMs: 10_000,
120
143
  batchSize: 100,
121
- maxAllowedEthClientDriftSeconds: 300
144
+ maxAllowedEthClientDriftSeconds: 300,
145
+ ethereumAllowNoDebugHosts: false
122
146
  }, mapArchiverConfig(config));
123
147
  const epochCache = deps.epochCache ?? await EpochCache.create(config.l1Contracts.rollupAddress, config, deps);
124
148
  const telemetry = deps.telemetry ?? getTelemetryClient();
125
- const archiver = new Archiver(publicClient, config.l1Contracts, archiverStore, opts, deps.blobSinkClient, epochCache, deps.dateProvider ?? new DateProvider(), await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
149
+ const archiver = new Archiver(publicClient, debugClient, {
150
+ ...config.l1Contracts,
151
+ slashingProposerAddress
152
+ }, archiverStore, opts, deps.blobClient, epochCache, deps.dateProvider ?? new DateProvider(), await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
126
153
  await archiver.start(blockUntilSynced);
127
154
  return archiver;
128
155
  }
@@ -136,16 +163,17 @@ function mapArchiverConfig(config) {
136
163
  if (this.runningPromise.isRunning()) {
137
164
  throw new Error('Archiver is already running');
138
165
  }
139
- await this.blobSinkClient.testSources();
166
+ await this.blobClient.testSources();
140
167
  await this.testEthereumNodeSynced();
168
+ await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
141
169
  // Log initial state for the archiver
142
170
  const { l1StartBlock } = this.l1constants;
143
171
  const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
144
- const currentL2Block = await this.getBlockNumber();
145
- this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo} and L2 block ${currentL2Block}`, {
172
+ const currentL2Checkpoint = await this.getSynchedCheckpointNumber();
173
+ this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`, {
146
174
  blocksSynchedTo,
147
175
  messagesSynchedTo,
148
- currentL2Block
176
+ currentL2Checkpoint
149
177
  });
150
178
  // Start sync loop, and return the wait for initial sync if we are asked to block until synced
151
179
  this.runningPromise.start();
@@ -156,6 +184,51 @@ function mapArchiverConfig(config) {
156
184
  syncImmediate() {
157
185
  return this.runningPromise.trigger();
158
186
  }
187
+ /**
188
+ * Queues a block to be added to the archiver store and triggers processing.
189
+ * The block will be processed by the sync loop.
190
+ * Implements the L2BlockSink interface.
191
+ * @param block - The L2 block to add.
192
+ * @returns A promise that resolves when the block has been added to the store, or rejects on error.
193
+ */ addBlock(block) {
194
+ return new Promise((resolve, reject)=>{
195
+ this.blockQueue.push({
196
+ block,
197
+ resolve,
198
+ reject
199
+ });
200
+ this.log.debug(`Queued block ${block.number} for processing`);
201
+ // Trigger an immediate sync, but don't wait for it - the promise resolves when the block is processed
202
+ this.syncImmediate().catch((err)=>{
203
+ this.log.error(`Sync immediate call failed: ${err}`);
204
+ });
205
+ });
206
+ }
207
+ /**
208
+ * Processes all queued blocks, adding them to the store.
209
+ * Called at the beginning of each sync iteration.
210
+ * Blocks are processed in the order they were queued.
211
+ */ async processQueuedBlocks() {
212
+ if (this.blockQueue.length === 0) {
213
+ return;
214
+ }
215
+ // Take all blocks from the queue
216
+ const queuedItems = this.blockQueue.splice(0, this.blockQueue.length);
217
+ this.log.debug(`Processing ${queuedItems.length} queued block(s)`);
218
+ // Process each block individually to properly resolve/reject each promise
219
+ for (const { block, resolve, reject } of queuedItems){
220
+ try {
221
+ await this.store.addBlocks([
222
+ block
223
+ ]);
224
+ this.log.debug(`Added block ${block.number} to store`);
225
+ resolve();
226
+ } catch (err) {
227
+ this.log.error(`Failed to add block ${block.number} to store: ${err.message}`);
228
+ reject(err);
229
+ }
230
+ }
231
+ }
159
232
  waitForInitialSync() {
160
233
  return this.initialSyncPromise.promise;
161
234
  }
@@ -172,9 +245,7 @@ function mapArchiverConfig(config) {
172
245
  throw new Error(`Ethereum node is out of sync (last block synced ${number} at ${l1Timestamp} vs current time ${currentTime})`);
173
246
  }
174
247
  }
175
- /**
176
- * Fetches logs from L1 contracts and processes them.
177
- */ async sync() {
248
+ async syncFromL1() {
178
249
  /**
179
250
  * We keep track of three "pointers" to L1 blocks:
180
251
  * 1. the last L1 block that published an L2 block
@@ -248,7 +319,7 @@ function mapArchiverConfig(config) {
248
319
  // past it, since otherwise we'll keep downloading it and reprocessing it on every iteration until
249
320
  // we get a valid checkpoint to advance the syncpoint.
250
321
  if (!rollupStatus.validationResult?.valid && rollupStatus.lastL1BlockWithCheckpoint !== undefined) {
251
- await this.store.setBlockSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
322
+ await this.store.setCheckpointSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
252
323
  }
253
324
  // And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
254
325
  // We only do this if rollup cant prune on the next submission. Otherwise we will end up
@@ -277,6 +348,14 @@ function mapArchiverConfig(config) {
277
348
  this.initialSyncPromise.resolve();
278
349
  }
279
350
  }
351
+ /**
352
+ * Fetches logs from L1 contracts and processes them.
353
+ */ async sync() {
354
+ // Process any queued blocks first, before doing L1 sync
355
+ await this.processQueuedBlocks();
356
+ // Now perform L1 sync
357
+ await this.syncFromL1();
358
+ }
280
359
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
281
360
  const time = (currentL1Timestamp ?? 0n) + BigInt(this.l1constants.ethereumSlotDuration);
282
361
  const result = await this.rollup.canPruneAtTime(time, {
@@ -297,20 +376,27 @@ function mapArchiverConfig(config) {
297
376
  const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
298
377
  if (canPrune) {
299
378
  const timer = new Timer();
300
- const pruneFrom = provenCheckpointNumber + 1;
301
- const header = await this.getCheckpointHeader(Number(pruneFrom));
379
+ const pruneFrom = CheckpointNumber(provenCheckpointNumber + 1);
380
+ const header = await this.getCheckpointHeader(pruneFrom);
302
381
  if (header === undefined) {
303
382
  throw new Error(`Missing checkpoint header ${pruneFrom}`);
304
383
  }
305
384
  const pruneFromSlotNumber = header.slotNumber;
306
385
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1constants);
307
386
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
308
- const checkpoints = await this.getCheckpoints(Number(provenCheckpointNumber) + 1, Number(checkpointsToUnwind));
387
+ const checkpointPromises = Array.from({
388
+ length: checkpointsToUnwind
389
+ }).fill(0).map((_, i)=>this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
390
+ const checkpoints = await Promise.all(checkpointPromises);
391
+ const blockPromises = await Promise.all(checkpoints.filter(isDefined).map((cp)=>this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))));
392
+ const newBlocks = blockPromises.filter(isDefined).flat();
393
+ // TODO(pw/mbps): Don't convert to legacy blocks here
394
+ const blocks = (await Promise.all(newBlocks.map((x)=>this.getBlock(x.number)))).filter(isDefined);
309
395
  // Emit an event for listening services to react to the chain prune
310
396
  this.emit(L2BlockSourceEvents.L2PruneDetected, {
311
397
  type: L2BlockSourceEvents.L2PruneDetected,
312
398
  epochNumber: pruneFromEpochNumber,
313
- blocks: checkpoints.flatMap((c)=>L2Block.fromCheckpoint(c))
399
+ blocks
314
400
  });
315
401
  this.log.debug(`L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`);
316
402
  await this.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
@@ -406,7 +492,7 @@ function mapArchiverConfig(config) {
406
492
  }while (searchEndBlock < currentL1BlockNumber)
407
493
  // Log stats for messages retrieved (if any).
408
494
  if (messageCount > 0) {
409
- this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for L2 block ${lastMessage?.l2BlockNumber}`, {
495
+ this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
410
496
  lastMessage,
411
497
  messageCount
412
498
  });
@@ -486,11 +572,11 @@ function mapArchiverConfig(config) {
486
572
  async handleCheckpoints(blocksSynchedTo, currentL1BlockNumber) {
487
573
  const localPendingCheckpointNumber = await this.getSynchedCheckpointNumber();
488
574
  const initialValidationResult = await this.store.getPendingChainValidationStatus();
489
- const [rollupProvenCheckpointNumber, provenArchive, rollupPendingCheckpointNumber, pendingArchive, archiveForLocalPendingCheckpointNumber] = await this.rollup.status(BigInt(localPendingCheckpointNumber), {
575
+ const [rollupProvenCheckpointNumber, provenArchive, rollupPendingCheckpointNumber, pendingArchive, archiveForLocalPendingCheckpointNumber] = await this.rollup.status(localPendingCheckpointNumber, {
490
576
  blockNumber: currentL1BlockNumber
491
577
  });
492
- const provenCheckpointNumber = Number(rollupProvenCheckpointNumber);
493
- const pendingCheckpointNumber = Number(rollupPendingCheckpointNumber);
578
+ const provenCheckpointNumber = CheckpointNumber.fromBigInt(rollupProvenCheckpointNumber);
579
+ const pendingCheckpointNumber = CheckpointNumber.fromBigInt(rollupPendingCheckpointNumber);
494
580
  const rollupStatus = {
495
581
  provenCheckpointNumber,
496
582
  provenArchive,
@@ -518,15 +604,14 @@ function mapArchiverConfig(config) {
518
604
  });
519
605
  }
520
606
  }
521
- const localCheckpointForDestinationProvenCheckpointNumber = await this.getCheckpoint(provenCheckpointNumber);
607
+ const localCheckpointForDestinationProvenCheckpointNumber = await this.store.getCheckpointData(provenCheckpointNumber);
522
608
  // Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
523
609
  // synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
524
610
  const synched = await this.getSynchedCheckpointNumber();
525
- if (localCheckpointForDestinationProvenCheckpointNumber && synched < localCheckpointForDestinationProvenCheckpointNumber.number) {
526
- this.log.error(`Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.number} > ${synched}`);
611
+ if (localCheckpointForDestinationProvenCheckpointNumber && synched < localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber) {
612
+ this.log.error(`Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber} > ${synched}`);
527
613
  }
528
614
  this.log.trace(`Local checkpoint for remote proven checkpoint ${provenCheckpointNumber} is ${localCheckpointForDestinationProvenCheckpointNumber?.archive.root.toString() ?? 'undefined'}`);
529
- const lastProvenBlockNumber = await this.getLastBlockNumberInCheckpoint(provenCheckpointNumber);
530
615
  if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive === localCheckpointForDestinationProvenCheckpointNumber.archive.root.toString()) {
531
616
  const localProvenCheckpointNumber = await this.getProvenCheckpointNumber();
532
617
  if (localProvenCheckpointNumber !== provenCheckpointNumber) {
@@ -536,23 +621,24 @@ function mapArchiverConfig(config) {
536
621
  });
537
622
  const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
538
623
  const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1constants);
624
+ const lastBlockNumberInCheckpoint = localCheckpointForDestinationProvenCheckpointNumber.startBlock + localCheckpointForDestinationProvenCheckpointNumber.numBlocks - 1;
539
625
  this.emit(L2BlockSourceEvents.L2BlockProven, {
540
626
  type: L2BlockSourceEvents.L2BlockProven,
541
- blockNumber: BigInt(lastProvenBlockNumber),
627
+ blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
542
628
  slotNumber: provenSlotNumber,
543
629
  epochNumber: provenEpochNumber
544
630
  });
631
+ this.instrumentation.updateLastProvenBlock(lastBlockNumberInCheckpoint);
545
632
  } else {
546
633
  this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
547
634
  }
548
635
  }
549
- this.instrumentation.updateLastProvenBlock(lastProvenBlockNumber);
550
636
  };
551
637
  // This is an edge case that we only hit if there are no proposed checkpoints.
552
638
  // If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
553
639
  const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
554
640
  if (noCheckpoints) {
555
- await this.store.setBlockSynchedL1BlockNumber(currentL1BlockNumber);
641
+ await this.store.setCheckpointSynchedL1BlockNumber(currentL1BlockNumber);
556
642
  this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`);
557
643
  return rollupStatus;
558
644
  }
@@ -560,7 +646,7 @@ function mapArchiverConfig(config) {
560
646
  // Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
561
647
  // are any state that could be impacted by it. If we have no checkpoints, there is no impact.
562
648
  if (localPendingCheckpointNumber > 0) {
563
- const localPendingCheckpoint = await this.getCheckpoint(localPendingCheckpointNumber);
649
+ const localPendingCheckpoint = await this.store.getCheckpointData(localPendingCheckpointNumber);
564
650
  if (localPendingCheckpoint === undefined) {
565
651
  throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
566
652
  }
@@ -591,12 +677,12 @@ function mapArchiverConfig(config) {
591
677
  });
592
678
  let tipAfterUnwind = localPendingCheckpointNumber;
593
679
  while(true){
594
- const candidateCheckpoint = await this.getCheckpoint(tipAfterUnwind);
680
+ const candidateCheckpoint = await this.store.getCheckpointData(tipAfterUnwind);
595
681
  if (candidateCheckpoint === undefined) {
596
682
  break;
597
683
  }
598
- const archiveAtContract = await this.rollup.archiveAt(BigInt(candidateCheckpoint.number));
599
- this.log.trace(`Checking local checkpoint ${candidateCheckpoint.number} with archive ${candidateCheckpoint.archive.root}`, {
684
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
685
+ this.log.trace(`Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`, {
600
686
  archiveAtContract,
601
687
  archiveLocal: candidateCheckpoint.archive.root.toString()
602
688
  });
@@ -619,8 +705,8 @@ function mapArchiverConfig(config) {
619
705
  do {
620
706
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
621
707
  this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
622
- // TODO(md): Retrieve from blob sink then from consensus client, then from peers
623
- const retrievedCheckpoints = await retrieveCheckpointsFromRollup(this.rollup.getContract(), this.publicClient, this.blobSinkClient, searchStartBlock, searchEndBlock, this.log);
708
+ // TODO(md): Retrieve from blob client then from consensus client, then from peers
709
+ const retrievedCheckpoints = await retrieveCheckpointsFromRollup(this.rollup.getContract(), this.publicClient, this.debugClient, this.blobClient, searchStartBlock, searchEndBlock, this.l1Addresses, this.instrumentation, this.log, !this.initialSyncComplete);
624
710
  if (retrievedCheckpoints.length === 0) {
625
711
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
626
712
  // See further details in earlier comments.
@@ -659,6 +745,22 @@ function mapArchiverConfig(config) {
659
745
  });
660
746
  continue;
661
747
  }
748
+ // Check the inHash of the checkpoint against the l1->l2 messages.
749
+ // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
750
+ // checkpoints we just retrieved.
751
+ const l1ToL2Messages = await this.getL1ToL2Messages(published.checkpoint.number);
752
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
753
+ const publishedInHash = published.checkpoint.header.contentCommitment.inHash;
754
+ if (!computedInHash.equals(publishedInHash)) {
755
+ this.log.fatal(`Mismatch inHash for checkpoint ${published.checkpoint.number}`, {
756
+ checkpointHash: published.checkpoint.hash(),
757
+ l1BlockNumber: published.l1.blockNumber,
758
+ computedInHash,
759
+ publishedInHash
760
+ });
761
+ // Throwing an error since this is most likely caused by a bug.
762
+ throw new Error(`Mismatch inHash for checkpoint ${published.checkpoint.number}. Expected ${computedInHash} but got ${publishedInHash}`);
763
+ }
662
764
  validCheckpoints.push(published);
663
765
  this.log.debug(`Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`, {
664
766
  checkpointHash: published.checkpoint.hash(),
@@ -672,15 +774,14 @@ function mapArchiverConfig(config) {
672
774
  const [processDuration] = await elapsed(()=>this.addCheckpoints(validCheckpoints, updatedValidationResult));
673
775
  this.instrumentation.processNewBlocks(processDuration / validCheckpoints.length, validCheckpoints.flatMap((c)=>c.checkpoint.blocks));
674
776
  } catch (err) {
675
- if (err instanceof InitialBlockNumberNotSequentialError) {
676
- const { previousBlockNumber, newBlockNumber } = err;
677
- const previousBlock = previousBlockNumber ? await this.store.getPublishedBlock(previousBlockNumber) : undefined;
678
- const updatedL1SyncPoint = previousBlock?.l1.blockNumber ?? this.l1constants.l1StartBlock;
777
+ if (err instanceof InitialCheckpointNumberNotSequentialError) {
778
+ const { previousCheckpointNumber, newCheckpointNumber } = err;
779
+ const previousCheckpoint = previousCheckpointNumber ? await this.store.getCheckpointData(CheckpointNumber(previousCheckpointNumber)) : undefined;
780
+ const updatedL1SyncPoint = previousCheckpoint?.l1.blockNumber ?? this.l1constants.l1StartBlock;
679
781
  await this.store.setBlockSynchedL1BlockNumber(updatedL1SyncPoint);
680
- this.log.warn(`Attempting to insert block ${newBlockNumber} with previous block ${previousBlockNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`, {
681
- previousBlockNumber,
682
- previousBlockHash: await previousBlock?.block.hash(),
683
- newBlockNumber,
782
+ this.log.warn(`Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`, {
783
+ previousCheckpointNumber,
784
+ newCheckpointNumber,
684
785
  updatedL1SyncPoint
685
786
  });
686
787
  }
@@ -698,7 +799,7 @@ function mapArchiverConfig(config) {
698
799
  });
699
800
  }
700
801
  lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
701
- lastL1BlockWithCheckpoint = publishedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
802
+ lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
702
803
  }while (searchEndBlock < currentL1BlockNumber)
703
804
  // Important that we update AFTER inserting the blocks.
704
805
  await updateProvenCheckpoint();
@@ -719,9 +820,16 @@ function mapArchiverConfig(config) {
719
820
  // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
720
821
  // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
721
822
  // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
722
- const latestLocalCheckpoint = lastRetrievedCheckpoint ?? (latestLocalCheckpointNumber > 0 ? await this.getPublishedCheckpoints(latestLocalCheckpointNumber, 1).then(([c])=>c) : undefined);
723
- const targetL1BlockNumber = latestLocalCheckpoint?.l1.blockNumber ?? maxBigint(currentL1BlockNumber - 64n, 0n);
724
- const latestLocalCheckpointArchive = latestLocalCheckpoint?.checkpoint.archive.root.toString();
823
+ let latestLocalCheckpointArchive = undefined;
824
+ let targetL1BlockNumber = maxBigint(currentL1BlockNumber - 64n, 0n);
825
+ if (lastRetrievedCheckpoint) {
826
+ latestLocalCheckpointArchive = lastRetrievedCheckpoint.checkpoint.archive.root.toString();
827
+ targetL1BlockNumber = lastRetrievedCheckpoint.l1.blockNumber;
828
+ } else if (latestLocalCheckpointNumber > 0) {
829
+ const checkpoint = await this.store.getRangeOfCheckpoints(latestLocalCheckpointNumber, 1).then(([c])=>c);
830
+ latestLocalCheckpointArchive = checkpoint.archive.root.toString();
831
+ targetL1BlockNumber = checkpoint.l1.blockNumber;
832
+ }
725
833
  this.log.warn(`Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
726
834
  latestLocalCheckpointNumber,
727
835
  latestLocalCheckpointArchive,
@@ -785,31 +893,44 @@ function mapArchiverConfig(config) {
785
893
  async getBlocksForEpoch(epochNumber) {
786
894
  const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
787
895
  const blocks = [];
788
- // Walk the list of blocks backwards and filter by slots matching the requested epoch.
789
- // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
790
- let block = await this.getBlock(await this.store.getSynchedL2BlockNumber());
791
- const slot = (b)=>b.header.globalVariables.slotNumber;
792
- while(block && slot(block) >= start){
793
- if (slot(block) <= end) {
794
- blocks.push(block);
896
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
897
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
898
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
899
+ const slot = (b)=>b.header.slotNumber;
900
+ while(checkpoint && slot(checkpoint) >= start){
901
+ if (slot(checkpoint) <= end) {
902
+ // push the blocks on backwards
903
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
904
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
905
+ const block = await this.getBlock(BlockNumber(i));
906
+ if (block) {
907
+ blocks.push(block);
908
+ }
909
+ }
795
910
  }
796
- block = await this.getBlock(block.number - 1);
911
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
797
912
  }
798
913
  return blocks.reverse();
799
914
  }
800
915
  async getBlockHeadersForEpoch(epochNumber) {
801
916
  const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
802
917
  const blocks = [];
803
- // Walk the list of blocks backwards and filter by slots matching the requested epoch.
804
- // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
805
- let number = await this.store.getSynchedL2BlockNumber();
806
- let header = await this.getBlockHeader(number);
807
- const slot = (b)=>b.globalVariables.slotNumber;
808
- while(header && slot(header) >= start){
809
- if (slot(header) <= end) {
810
- blocks.push(header);
918
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
919
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
920
+ let checkpoint = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
921
+ const slot = (b)=>b.header.slotNumber;
922
+ while(checkpoint && slot(checkpoint) >= start){
923
+ if (slot(checkpoint) <= end) {
924
+ // push the blocks on backwards
925
+ const endBlock = checkpoint.startBlock + checkpoint.numBlocks - 1;
926
+ for(let i = endBlock; i >= checkpoint.startBlock; i--){
927
+ const block = await this.getBlockHeader(BlockNumber(i));
928
+ if (block) {
929
+ blocks.push(block);
930
+ }
931
+ }
811
932
  }
812
- header = await this.getBlockHeader(--number);
933
+ checkpoint = await this.store.getCheckpointData(CheckpointNumber(checkpoint.checkpointNumber - 1));
813
934
  }
814
935
  return blocks.reverse();
815
936
  }
@@ -840,24 +961,6 @@ function mapArchiverConfig(config) {
840
961
  /** Returns whether the archiver has completed an initial sync run successfully. */ isInitialSyncComplete() {
841
962
  return this.initialSyncComplete;
842
963
  }
843
- async getPublishedCheckpoints(from, limit, proven) {
844
- const blocks = await this.getPublishedBlocks(from, limit, proven);
845
- return blocks.map((b)=>b.toPublishedCheckpoint());
846
- }
847
- async getCheckpoints(from, limit, proven) {
848
- const published = await this.getPublishedCheckpoints(from, limit, proven);
849
- return published.map((p)=>p.checkpoint);
850
- }
851
- async getCheckpoint(number) {
852
- if (number < 0) {
853
- number = await this.getSynchedCheckpointNumber();
854
- }
855
- if (number === 0) {
856
- return undefined;
857
- }
858
- const published = await this.getPublishedCheckpoints(number, 1);
859
- return published[0]?.checkpoint;
860
- }
861
964
  async getCheckpointHeader(number) {
862
965
  if (number === 'latest') {
863
966
  number = await this.getSynchedCheckpointNumber();
@@ -865,53 +968,36 @@ function mapArchiverConfig(config) {
865
968
  if (number === 0) {
866
969
  return undefined;
867
970
  }
868
- const checkpoint = await this.getCheckpoint(number);
869
- return checkpoint?.header;
971
+ const checkpoint = await this.store.getCheckpointData(number);
972
+ if (!checkpoint) {
973
+ return undefined;
974
+ }
975
+ return checkpoint.header;
870
976
  }
871
977
  getCheckpointNumber() {
872
978
  return this.getSynchedCheckpointNumber();
873
979
  }
874
980
  getSynchedCheckpointNumber() {
875
- // TODO: Checkpoint number will no longer be the same as the block number once we support multiple blocks per checkpoint.
876
- return this.store.getSynchedL2BlockNumber();
981
+ return this.store.getSynchedCheckpointNumber();
877
982
  }
878
983
  getProvenCheckpointNumber() {
879
- // TODO: Proven checkpoint number will no longer be the same as the proven block number once we support multiple blocks per checkpoint.
880
- return this.store.getProvenL2BlockNumber();
984
+ return this.store.getProvenCheckpointNumber();
881
985
  }
882
986
  setProvenCheckpointNumber(checkpointNumber) {
883
- // TODO: Proven checkpoint number will no longer be the same as the proven block number once we support multiple blocks per checkpoint.
884
- return this.store.setProvenL2BlockNumber(checkpointNumber);
987
+ return this.store.setProvenCheckpointNumber(checkpointNumber);
885
988
  }
886
989
  unwindCheckpoints(from, checkpointsToUnwind) {
887
- // TODO: This only works if we have one block per checkpoint.
888
- return this.store.unwindBlocks(from, checkpointsToUnwind);
990
+ return this.store.unwindCheckpoints(from, checkpointsToUnwind);
889
991
  }
890
- getLastBlockNumberInCheckpoint(checkpointNumber) {
891
- // TODO: Checkpoint number will no longer be the same as the block number once we support multiple blocks per checkpoint.
892
- return Promise.resolve(checkpointNumber);
992
+ async getLastBlockNumberInCheckpoint(checkpointNumber) {
993
+ const checkpointData = await this.store.getCheckpointData(checkpointNumber);
994
+ if (!checkpointData) {
995
+ return undefined;
996
+ }
997
+ return BlockNumber(checkpointData.startBlock + checkpointData.numBlocks - 1);
893
998
  }
894
999
  addCheckpoints(checkpoints, pendingChainValidationStatus) {
895
- return this.store.addBlocks(checkpoints.map((p)=>PublishedL2Block.fromPublishedCheckpoint(p)), pendingChainValidationStatus);
896
- }
897
- /**
898
- * Gets up to `limit` amount of L2 blocks starting from `from`.
899
- * @param from - Number of the first block to return (inclusive).
900
- * @param limit - The number of blocks to return.
901
- * @param proven - If true, only return blocks that have been proven.
902
- * @returns The requested L2 blocks.
903
- */ getBlocks(from, limit, proven) {
904
- return this.getPublishedBlocks(from, limit, proven).then((blocks)=>blocks.map((b)=>b.block));
905
- }
906
- /** Equivalent to getBlocks but includes publish data. */ async getPublishedBlocks(from, limit, proven) {
907
- const limitWithProven = proven ? Math.min(limit, Math.max(await this.store.getProvenL2BlockNumber() - from + 1, 0)) : limit;
908
- return limitWithProven === 0 ? [] : await this.store.getPublishedBlocks(from, limitWithProven);
909
- }
910
- getPublishedBlockByHash(blockHash) {
911
- return this.store.getPublishedBlockByHash(blockHash);
912
- }
913
- getPublishedBlockByArchive(archive) {
914
- return this.store.getPublishedBlockByArchive(archive);
1000
+ return this.store.addCheckpoints(checkpoints, pendingChainValidationStatus);
915
1001
  }
916
1002
  getBlockHeaderByHash(blockHash) {
917
1003
  return this.store.getBlockHeaderByHash(blockHash);
@@ -923,7 +1009,7 @@ function mapArchiverConfig(config) {
923
1009
  * Gets an l2 block.
924
1010
  * @param number - The block number to return.
925
1011
  * @returns The requested L2 block.
926
- */ async getBlock(number) {
1012
+ */ async getL2BlockNew(number) {
927
1013
  // If the number provided is -ve, then return the latest block.
928
1014
  if (number < 0) {
929
1015
  number = await this.store.getSynchedL2BlockNumber();
@@ -931,8 +1017,8 @@ function mapArchiverConfig(config) {
931
1017
  if (number === 0) {
932
1018
  return undefined;
933
1019
  }
934
- const publishedBlock = await this.store.getPublishedBlock(number);
935
- return publishedBlock?.block;
1020
+ const publishedBlock = await this.store.store.getBlock(number);
1021
+ return publishedBlock;
936
1022
  }
937
1023
  async getBlockHeader(number) {
938
1024
  if (number === 'latest') {
@@ -944,27 +1030,29 @@ function mapArchiverConfig(config) {
944
1030
  const headers = await this.store.getBlockHeaders(number, 1);
945
1031
  return headers.length === 0 ? undefined : headers[0];
946
1032
  }
1033
+ getCheckpointedBlock(number) {
1034
+ return this.store.getCheckpointedBlock(number);
1035
+ }
1036
+ getCheckpointedBlockByHash(blockHash) {
1037
+ return this.store.getCheckpointedBlockByHash(blockHash);
1038
+ }
1039
+ getProvenBlockNumber() {
1040
+ return this.store.getProvenBlockNumber();
1041
+ }
1042
+ getCheckpointedBlockByArchive(archive) {
1043
+ return this.store.getCheckpointedBlockByArchive(archive);
1044
+ }
947
1045
  getTxEffect(txHash) {
948
1046
  return this.store.getTxEffect(txHash);
949
1047
  }
950
1048
  getSettledTxReceipt(txHash) {
951
1049
  return this.store.getSettledTxReceipt(txHash);
952
1050
  }
953
- /**
954
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
955
- * @param from - The block number from which to begin retrieving logs.
956
- * @param limit - The maximum number of blocks to retrieve logs from.
957
- * @returns An array of private logs from the specified range of blocks.
958
- */ getPrivateLogs(from, limit) {
959
- return this.store.getPrivateLogs(from, limit);
1051
+ getPrivateLogsByTags(tags) {
1052
+ return this.store.getPrivateLogsByTags(tags);
960
1053
  }
961
- /**
962
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
963
- * @param tags - The tags to filter the logs by.
964
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
965
- * that tag.
966
- */ getLogsByTags(tags) {
967
- return this.store.getLogsByTags(tags);
1054
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
1055
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags);
968
1056
  }
969
1057
  /**
970
1058
  * Gets public logs based on the provided filter.
@@ -982,15 +1070,10 @@ function mapArchiverConfig(config) {
982
1070
  }
983
1071
  /**
984
1072
  * Gets the number of the latest L2 block processed by the block source implementation.
1073
+ * This includes both checkpointed and uncheckpointed blocks.
985
1074
  * @returns The number of the latest L2 block processed by the block source implementation.
986
1075
  */ getBlockNumber() {
987
- return this.store.getSynchedL2BlockNumber();
988
- }
989
- getProvenBlockNumber() {
990
- return this.store.getProvenL2BlockNumber();
991
- }
992
- /** Forcefully updates the last proven block number. Use for testing. */ setProvenBlockNumber(blockNumber) {
993
- return this.store.setProvenL2BlockNumber(blockNumber);
1076
+ return this.store.getLatestBlockNumber();
994
1077
  }
995
1078
  getContractClass(id) {
996
1079
  return this.store.getContractClass(id);
@@ -1010,11 +1093,11 @@ function mapArchiverConfig(config) {
1010
1093
  return this.store.getContractInstance(address, timestamp);
1011
1094
  }
1012
1095
  /**
1013
- * Gets L1 to L2 message (to be) included in a given block.
1014
- * @param blockNumber - L2 block number to get messages for.
1096
+ * Gets L1 to L2 message (to be) included in a given checkpoint.
1097
+ * @param checkpointNumber - Checkpoint number to get messages for.
1015
1098
  * @returns The L1 to L2 messages/leaves of the messages subtree (throws if not found).
1016
- */ getL1ToL2Messages(blockNumber) {
1017
- return this.store.getL1ToL2Messages(blockNumber);
1099
+ */ getL1ToL2Messages(checkpointNumber) {
1100
+ return this.store.getL1ToL2Messages(checkpointNumber);
1018
1101
  }
1019
1102
  /**
1020
1103
  * Gets the L1 to L2 message index in the L1 to L2 message tree.
@@ -1048,7 +1131,7 @@ function mapArchiverConfig(config) {
1048
1131
  // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
1049
1132
  // We just force it 2 epochs worth of proven data for now.
1050
1133
  // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
1051
- const finalizedBlockNumber = Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0);
1134
+ const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0));
1052
1135
  const [latestBlockHeader, provenBlockHeader, finalizedBlockHeader] = await Promise.all([
1053
1136
  latestBlockNumber > 0 ? this.getBlockHeader(latestBlockNumber) : undefined,
1054
1137
  provenBlockNumber > 0 ? this.getBlockHeader(provenBlockNumber) : undefined,
@@ -1063,43 +1146,44 @@ function mapArchiverConfig(config) {
1063
1146
  if (finalizedBlockNumber > 0 && !finalizedBlockHeader) {
1064
1147
  throw new Error(`Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`);
1065
1148
  }
1066
- const latestBlockHeaderHash = await latestBlockHeader?.hash();
1067
- const provenBlockHeaderHash = await provenBlockHeader?.hash();
1068
- const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash();
1149
+ const latestBlockHeaderHash = await latestBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1150
+ const provenBlockHeaderHash = await provenBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1151
+ const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1069
1152
  return {
1070
1153
  latest: {
1071
1154
  number: latestBlockNumber,
1072
- hash: latestBlockHeaderHash?.toString()
1155
+ hash: latestBlockHeaderHash.toString()
1073
1156
  },
1074
1157
  proven: {
1075
1158
  number: provenBlockNumber,
1076
- hash: provenBlockHeaderHash?.toString()
1159
+ hash: provenBlockHeaderHash.toString()
1077
1160
  },
1078
1161
  finalized: {
1079
1162
  number: finalizedBlockNumber,
1080
- hash: finalizedBlockHeaderHash?.toString()
1163
+ hash: finalizedBlockHeaderHash.toString()
1081
1164
  }
1082
1165
  };
1083
1166
  }
1084
1167
  async rollbackTo(targetL2BlockNumber) {
1168
+ // TODO(pw/mbps): This still assumes 1 block per checkpoint
1085
1169
  const currentBlocks = await this.getL2Tips();
1086
1170
  const currentL2Block = currentBlocks.latest.number;
1087
1171
  const currentProvenBlock = currentBlocks.proven.number;
1088
- // const currentFinalizedBlock = currentBlocks.finalized.number;
1089
1172
  if (targetL2BlockNumber >= currentL2Block) {
1090
1173
  throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
1091
1174
  }
1092
1175
  const blocksToUnwind = currentL2Block - targetL2BlockNumber;
1093
- const targetL2Block = await this.store.getPublishedBlock(targetL2BlockNumber);
1176
+ const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
1094
1177
  if (!targetL2Block) {
1095
1178
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
1096
1179
  }
1097
1180
  const targetL1BlockNumber = targetL2Block.l1.blockNumber;
1181
+ const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
1098
1182
  const targetL1BlockHash = await this.getL1BlockHash(targetL1BlockNumber);
1099
- this.log.info(`Unwinding ${blocksToUnwind} blocks from L2 block ${currentL2Block}`);
1100
- await this.store.unwindBlocks(currentL2Block, blocksToUnwind);
1101
- this.log.info(`Unwinding L1 to L2 messages to ${targetL2BlockNumber}`);
1102
- await this.store.rollbackL1ToL2MessagesToL2Block(targetL2BlockNumber);
1183
+ this.log.info(`Unwinding ${blocksToUnwind} checkpoints from L2 block ${currentL2Block}`);
1184
+ await this.store.unwindCheckpoints(CheckpointNumber(currentL2Block), blocksToUnwind);
1185
+ this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
1186
+ await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
1103
1187
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
1104
1188
  await this.store.setBlockSynchedL1BlockNumber(targetL1BlockNumber);
1105
1189
  await this.store.setMessageSynchedL1Block({
@@ -1108,7 +1192,7 @@ function mapArchiverConfig(config) {
1108
1192
  });
1109
1193
  if (targetL2BlockNumber < currentProvenBlock) {
1110
1194
  this.log.info(`Clearing proven L2 block number`);
1111
- await this.store.setProvenL2BlockNumber(0);
1195
+ await this.store.setProvenCheckpointNumber(CheckpointNumber.ZERO);
1112
1196
  }
1113
1197
  // TODO(palla/reorg): Set the finalized block when we add support for it.
1114
1198
  // if (targetL2BlockNumber < currentFinalizedBlock) {
@@ -1116,6 +1200,103 @@ function mapArchiverConfig(config) {
1116
1200
  // await this.store.setFinalizedL2BlockNumber(0);
1117
1201
  // }
1118
1202
  }
1203
+ async getPublishedCheckpoints(checkpointNumber, limit) {
1204
+ const checkpoints = await this.store.getRangeOfCheckpoints(checkpointNumber, limit);
1205
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
1206
+ const fullCheckpoints = [];
1207
+ for(let i = 0; i < checkpoints.length; i++){
1208
+ const blocksForCheckpoint = blocks[i];
1209
+ const checkpoint = checkpoints[i];
1210
+ const fullCheckpoint = new Checkpoint(checkpoint.archive, checkpoint.header, blocksForCheckpoint, checkpoint.checkpointNumber);
1211
+ const publishedCheckpoint = new PublishedCheckpoint(fullCheckpoint, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1212
+ fullCheckpoints.push(publishedCheckpoint);
1213
+ }
1214
+ return fullCheckpoints;
1215
+ }
1216
+ async getCheckpointsForEpoch(epochNumber) {
1217
+ const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
1218
+ const checkpoints = [];
1219
+ // Walk the list of checkpoints backwards and filter by slots matching the requested epoch.
1220
+ // We'll typically ask for checkpoints for a very recent epoch, so we shouldn't need an index here.
1221
+ let checkpointData = await this.store.getCheckpointData(await this.store.getSynchedCheckpointNumber());
1222
+ const slot = (b)=>b.header.slotNumber;
1223
+ while(checkpointData && slot(checkpointData) >= start){
1224
+ if (slot(checkpointData) <= end) {
1225
+ // push the checkpoints on backwards
1226
+ const [checkpoint] = await this.getPublishedCheckpoints(checkpointData.checkpointNumber, 1);
1227
+ checkpoints.push(checkpoint.checkpoint);
1228
+ }
1229
+ checkpointData = await this.store.getCheckpointData(CheckpointNumber(checkpointData.checkpointNumber - 1));
1230
+ }
1231
+ return checkpoints.reverse();
1232
+ }
1233
+ /* Legacy APIs */ async getPublishedBlockByHash(blockHash) {
1234
+ const checkpointedBlock = await this.store.getCheckpointedBlockByHash(blockHash);
1235
+ return this.buildOldBlockFromCheckpointedBlock(checkpointedBlock);
1236
+ }
1237
+ async getPublishedBlockByArchive(archive) {
1238
+ const checkpointedBlock = await this.store.getCheckpointedBlockByArchive(archive);
1239
+ return this.buildOldBlockFromCheckpointedBlock(checkpointedBlock);
1240
+ }
1241
+ /**
1242
+ * Gets up to `limit` amount of L2 blocks starting from `from`.
1243
+ * @param from - Number of the first block to return (inclusive).
1244
+ * @param limit - The number of blocks to return.
1245
+ * @param proven - If true, only return blocks that have been proven.
1246
+ * @returns The requested L2 blocks.
1247
+ */ async getBlocks(from, limit, proven) {
1248
+ const publishedBlocks = await this.getPublishedBlocks(from, limit, proven);
1249
+ return publishedBlocks.map((x)=>x.block);
1250
+ }
1251
+ async getPublishedBlocks(from, limit, proven) {
1252
+ const checkpoints = await this.store.getRangeOfCheckpoints(CheckpointNumber(from), limit);
1253
+ const provenCheckpointNumber = await this.getProvenCheckpointNumber();
1254
+ const blocks = (await Promise.all(checkpoints.map((ch)=>this.store.getBlocksForCheckpoint(ch.checkpointNumber)))).filter(isDefined);
1255
+ const olbBlocks = [];
1256
+ for(let i = 0; i < checkpoints.length; i++){
1257
+ const blockForCheckpoint = blocks[i][0];
1258
+ const checkpoint = checkpoints[i];
1259
+ if (checkpoint.checkpointNumber > provenCheckpointNumber && proven === true) {
1260
+ continue;
1261
+ }
1262
+ const oldCheckpoint = new Checkpoint(blockForCheckpoint.archive, checkpoint.header, [
1263
+ blockForCheckpoint
1264
+ ], checkpoint.checkpointNumber);
1265
+ const oldBlock = L2Block.fromCheckpoint(oldCheckpoint);
1266
+ const publishedBlock = new PublishedL2Block(oldBlock, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1267
+ olbBlocks.push(publishedBlock);
1268
+ }
1269
+ return olbBlocks;
1270
+ }
1271
+ async buildOldBlockFromCheckpointedBlock(checkpointedBlock) {
1272
+ if (!checkpointedBlock) {
1273
+ return undefined;
1274
+ }
1275
+ const checkpoint = await this.store.getCheckpointData(checkpointedBlock.checkpointNumber);
1276
+ if (!checkpoint) {
1277
+ return checkpoint;
1278
+ }
1279
+ const fullCheckpoint = new Checkpoint(checkpointedBlock?.block.archive, checkpoint?.header, [
1280
+ checkpointedBlock.block
1281
+ ], checkpoint.checkpointNumber);
1282
+ const oldBlock = L2Block.fromCheckpoint(fullCheckpoint);
1283
+ const published = new PublishedL2Block(oldBlock, checkpoint.l1, checkpoint.attestations.map((x)=>CommitteeAttestation.fromBuffer(x)));
1284
+ return published;
1285
+ }
1286
+ async getBlock(number) {
1287
+ // If the number provided is -ve, then return the latest block.
1288
+ if (number < 0) {
1289
+ number = await this.store.getSynchedL2BlockNumber();
1290
+ }
1291
+ if (number === 0) {
1292
+ return undefined;
1293
+ }
1294
+ const publishedBlocks = await this.getPublishedBlocks(number, 1);
1295
+ if (publishedBlocks.length === 0) {
1296
+ return undefined;
1297
+ }
1298
+ return publishedBlocks[0].block;
1299
+ }
1119
1300
  }
1120
1301
  _ts_decorate([
1121
1302
  trackSpan('Archiver.sync')
@@ -1237,6 +1418,18 @@ var Operation = /*#__PURE__*/ function(Operation) {
1237
1418
  }
1238
1419
  return true;
1239
1420
  }
1421
+ async addBlockDataToDB(block) {
1422
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1423
+ // ContractInstancePublished event logs are broadcast in privateLogs.
1424
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1425
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1426
+ return (await Promise.all([
1427
+ this.#updatePublishedContractClasses(contractClassLogs, block.number, 0),
1428
+ this.#updateDeployedContractInstances(privateLogs, block.number, 0),
1429
+ this.#updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, 0),
1430
+ this.#storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
1431
+ ])).every(Boolean);
1432
+ }
1240
1433
  addBlocks(blocks, pendingChainValidationStatus) {
1241
1434
  // Add the blocks to the store. Store will throw if the blocks are not in order, there are gaps,
1242
1435
  // or if the previous block is not in the store.
@@ -1246,34 +1439,51 @@ var Operation = /*#__PURE__*/ function(Operation) {
1246
1439
  // Update the pending chain validation status if provided
1247
1440
  pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
1248
1441
  // Add any logs emitted during the retrieved blocks
1249
- this.store.addLogs(blocks.map((block)=>block.block)),
1442
+ this.store.addLogs(blocks),
1443
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1444
+ ...blocks.map((block)=>{
1445
+ return this.addBlockDataToDB(block);
1446
+ })
1447
+ ]);
1448
+ return opResults.every(Boolean);
1449
+ });
1450
+ }
1451
+ addCheckpoints(checkpoints, pendingChainValidationStatus) {
1452
+ // Add the blocks to the store. Store will throw if the blocks are not in order, there are gaps,
1453
+ // or if the previous block is not in the store.
1454
+ return this.store.transactionAsync(async ()=>{
1455
+ await this.store.addCheckpoints(checkpoints);
1456
+ const allBlocks = checkpoints.flatMap((ch)=>ch.checkpoint.blocks);
1457
+ const opResults = await Promise.all([
1458
+ // Update the pending chain validation status if provided
1459
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
1460
+ // Add any logs emitted during the retrieved blocks
1461
+ this.store.addLogs(allBlocks),
1250
1462
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1251
- ...blocks.map(async (block)=>{
1252
- const contractClassLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1253
- // ContractInstancePublished event logs are broadcast in privateLogs.
1254
- const privateLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1255
- const publicLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1256
- return (await Promise.all([
1257
- this.#updatePublishedContractClasses(contractClassLogs, block.block.number, 0),
1258
- this.#updateDeployedContractInstances(privateLogs, block.block.number, 0),
1259
- this.#updateUpdatedContractInstances(publicLogs, block.block.header.globalVariables.timestamp, 0),
1260
- this.#storeBroadcastedIndividualFunctions(contractClassLogs, block.block.number)
1261
- ])).every(Boolean);
1463
+ ...allBlocks.map((block)=>{
1464
+ return this.addBlockDataToDB(block);
1262
1465
  })
1263
1466
  ]);
1264
1467
  return opResults.every(Boolean);
1265
1468
  });
1266
1469
  }
1267
- async unwindBlocks(from, blocksToUnwind) {
1268
- const last = await this.getSynchedL2BlockNumber();
1470
+ async unwindCheckpoints(from, checkpointsToUnwind) {
1471
+ if (checkpointsToUnwind <= 0) {
1472
+ throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
1473
+ }
1474
+ const last = await this.getSynchedCheckpointNumber();
1269
1475
  if (from != last) {
1270
- throw new Error(`Cannot unwind blocks from block ${from} when the last block is ${last}`);
1476
+ throw new Error(`Cannot unwind checkpoints from checkpoint ${from} when the last checkpoint is ${last}`);
1271
1477
  }
1272
- if (blocksToUnwind <= 0) {
1273
- throw new Error(`Cannot unwind ${blocksToUnwind} blocks`);
1478
+ const blocks = [];
1479
+ const lastCheckpointNumber = from + checkpointsToUnwind - 1;
1480
+ for(let checkpointNumber = from; checkpointNumber <= lastCheckpointNumber; checkpointNumber++){
1481
+ const blocksForCheckpoint = await this.store.getBlocksForCheckpoint(checkpointNumber);
1482
+ if (!blocksForCheckpoint) {
1483
+ continue;
1484
+ }
1485
+ blocks.push(...blocksForCheckpoint);
1274
1486
  }
1275
- // from - blocksToUnwind = the new head, so + 1 for what we need to remove
1276
- const blocks = await this.getPublishedBlocks(from - blocksToUnwind + 1, blocksToUnwind);
1277
1487
  const opResults = await Promise.all([
1278
1488
  // Prune rolls back to the last proven block, which is by definition valid
1279
1489
  this.store.setPendingChainValidationStatus({
@@ -1281,32 +1491,44 @@ var Operation = /*#__PURE__*/ function(Operation) {
1281
1491
  }),
1282
1492
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1283
1493
  ...blocks.map(async (block)=>{
1284
- const contractClassLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1494
+ const contractClassLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
1285
1495
  // ContractInstancePublished event logs are broadcast in privateLogs.
1286
- const privateLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1287
- const publicLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1496
+ const privateLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.privateLogs);
1497
+ const publicLogs = block.body.txEffects.flatMap((txEffect)=>txEffect.publicLogs);
1288
1498
  return (await Promise.all([
1289
- this.#updatePublishedContractClasses(contractClassLogs, block.block.number, 1),
1290
- this.#updateDeployedContractInstances(privateLogs, block.block.number, 1),
1291
- this.#updateUpdatedContractInstances(publicLogs, block.block.header.globalVariables.timestamp, 1)
1499
+ this.#updatePublishedContractClasses(contractClassLogs, block.number, 1),
1500
+ this.#updateDeployedContractInstances(privateLogs, block.number, 1),
1501
+ this.#updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, 1)
1292
1502
  ])).every(Boolean);
1293
1503
  }),
1294
- this.store.deleteLogs(blocks.map((b)=>b.block)),
1295
- this.store.unwindBlocks(from, blocksToUnwind)
1504
+ this.store.deleteLogs(blocks),
1505
+ this.store.unwindCheckpoints(from, checkpointsToUnwind)
1296
1506
  ]);
1297
1507
  return opResults.every(Boolean);
1298
1508
  }
1299
- getPublishedBlocks(from, limit) {
1300
- return this.store.getPublishedBlocks(from, limit);
1509
+ getCheckpointData(checkpointNumber) {
1510
+ return this.store.getCheckpointData(checkpointNumber);
1511
+ }
1512
+ getRangeOfCheckpoints(from, limit) {
1513
+ return this.store.getRangeOfCheckpoints(from, limit);
1514
+ }
1515
+ getCheckpointedL2BlockNumber() {
1516
+ return this.store.getCheckpointedL2BlockNumber();
1517
+ }
1518
+ getSynchedCheckpointNumber() {
1519
+ return this.store.getSynchedCheckpointNumber();
1520
+ }
1521
+ setCheckpointSynchedL1BlockNumber(l1BlockNumber) {
1522
+ return this.store.setCheckpointSynchedL1BlockNumber(l1BlockNumber);
1301
1523
  }
1302
- getPublishedBlock(number) {
1303
- return this.store.getPublishedBlock(number);
1524
+ getCheckpointedBlock(number) {
1525
+ return this.store.getCheckpointedBlock(number);
1304
1526
  }
1305
- getPublishedBlockByHash(blockHash) {
1306
- return this.store.getPublishedBlockByHash(blockHash);
1527
+ getCheckpointedBlockByHash(blockHash) {
1528
+ return this.store.getCheckpointedBlockByHash(blockHash);
1307
1529
  }
1308
- getPublishedBlockByArchive(archive) {
1309
- return this.store.getPublishedBlockByArchive(archive);
1530
+ getCheckpointedBlockByArchive(archive) {
1531
+ return this.store.getCheckpointedBlockByArchive(archive);
1310
1532
  }
1311
1533
  getBlockHeaders(from, limit) {
1312
1534
  return this.store.getBlockHeaders(from, limit);
@@ -1317,6 +1539,18 @@ var Operation = /*#__PURE__*/ function(Operation) {
1317
1539
  getBlockHeaderByArchive(archive) {
1318
1540
  return this.store.getBlockHeaderByArchive(archive);
1319
1541
  }
1542
+ getBlockByHash(blockHash) {
1543
+ return this.store.getBlockByHash(blockHash);
1544
+ }
1545
+ getBlockByArchive(archive) {
1546
+ return this.store.getBlockByArchive(archive);
1547
+ }
1548
+ getLatestBlockNumber() {
1549
+ return this.store.getLatestBlockNumber();
1550
+ }
1551
+ getBlocksForCheckpoint(checkpointNumber) {
1552
+ return this.store.getBlocksForCheckpoint(checkpointNumber);
1553
+ }
1320
1554
  getTxEffect(txHash) {
1321
1555
  return this.store.getTxEffect(txHash);
1322
1556
  }
@@ -1326,17 +1560,17 @@ var Operation = /*#__PURE__*/ function(Operation) {
1326
1560
  addL1ToL2Messages(messages) {
1327
1561
  return this.store.addL1ToL2Messages(messages);
1328
1562
  }
1329
- getL1ToL2Messages(blockNumber) {
1330
- return this.store.getL1ToL2Messages(blockNumber);
1563
+ getL1ToL2Messages(checkpointNumber) {
1564
+ return this.store.getL1ToL2Messages(checkpointNumber);
1331
1565
  }
1332
1566
  getL1ToL2MessageIndex(l1ToL2Message) {
1333
1567
  return this.store.getL1ToL2MessageIndex(l1ToL2Message);
1334
1568
  }
1335
- getPrivateLogs(from, limit) {
1336
- return this.store.getPrivateLogs(from, limit);
1569
+ getPrivateLogsByTags(tags) {
1570
+ return this.store.getPrivateLogsByTags(tags);
1337
1571
  }
1338
- getLogsByTags(tags, logsPerTag) {
1339
- return this.store.getLogsByTags(tags, logsPerTag);
1572
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
1573
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags);
1340
1574
  }
1341
1575
  getPublicLogs(filter) {
1342
1576
  return this.store.getPublicLogs(filter);
@@ -1345,16 +1579,19 @@ var Operation = /*#__PURE__*/ function(Operation) {
1345
1579
  return this.store.getContractClassLogs(filter);
1346
1580
  }
1347
1581
  getSynchedL2BlockNumber() {
1348
- return this.store.getSynchedL2BlockNumber();
1582
+ return this.store.getCheckpointedL2BlockNumber();
1349
1583
  }
1350
- getProvenL2BlockNumber() {
1351
- return this.store.getProvenL2BlockNumber();
1584
+ getProvenCheckpointNumber() {
1585
+ return this.store.getProvenCheckpointNumber();
1586
+ }
1587
+ getProvenBlockNumber() {
1588
+ return this.store.getProvenBlockNumber();
1352
1589
  }
1353
- setProvenL2BlockNumber(l2BlockNumber) {
1354
- return this.store.setProvenL2BlockNumber(l2BlockNumber);
1590
+ setProvenCheckpointNumber(checkpointNumber) {
1591
+ return this.store.setProvenCheckpointNumber(checkpointNumber);
1355
1592
  }
1356
1593
  setBlockSynchedL1BlockNumber(l1BlockNumber) {
1357
- return this.store.setBlockSynchedL1BlockNumber(l1BlockNumber);
1594
+ return this.store.setCheckpointSynchedL1BlockNumber(l1BlockNumber);
1358
1595
  }
1359
1596
  setMessageSynchedL1Block(l1Block) {
1360
1597
  return this.store.setMessageSynchedL1Block(l1Block);
@@ -1386,8 +1623,8 @@ var Operation = /*#__PURE__*/ function(Operation) {
1386
1623
  estimateSize() {
1387
1624
  return this.store.estimateSize();
1388
1625
  }
1389
- rollbackL1ToL2MessagesToL2Block(targetBlockNumber) {
1390
- return this.store.rollbackL1ToL2MessagesToL2Block(targetBlockNumber);
1626
+ rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber) {
1627
+ return this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
1391
1628
  }
1392
1629
  iterateL1ToL2Messages(range = {}) {
1393
1630
  return this.store.iterateL1ToL2Messages(range);