@aztec/archiver 3.0.0-canary.a9708bd → 3.0.0-devnet.2-patch.1

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 (127) hide show
  1. package/README.md +27 -6
  2. package/dest/archiver/archiver.d.ts +87 -64
  3. package/dest/archiver/archiver.d.ts.map +1 -1
  4. package/dest/archiver/archiver.js +463 -278
  5. package/dest/archiver/archiver_store.d.ts +46 -28
  6. package/dest/archiver/archiver_store.d.ts.map +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  8. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  9. package/dest/archiver/archiver_store_test_suite.js +316 -143
  10. package/dest/archiver/config.d.ts +6 -23
  11. package/dest/archiver/config.d.ts.map +1 -1
  12. package/dest/archiver/config.js +19 -12
  13. package/dest/archiver/errors.d.ts +1 -1
  14. package/dest/archiver/errors.d.ts.map +1 -1
  15. package/dest/archiver/index.d.ts +1 -1
  16. package/dest/archiver/instrumentation.d.ts +5 -3
  17. package/dest/archiver/instrumentation.d.ts.map +1 -1
  18. package/dest/archiver/instrumentation.js +14 -0
  19. package/dest/archiver/kv_archiver_store/block_store.d.ts +45 -9
  20. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  21. package/dest/archiver/kv_archiver_store/block_store.js +99 -12
  22. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  23. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  24. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  25. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  26. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  27. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +30 -30
  28. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  29. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +26 -15
  30. package/dest/archiver/kv_archiver_store/log_store.d.ts +3 -10
  31. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  32. package/dest/archiver/kv_archiver_store/log_store.js +4 -26
  33. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  34. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  35. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  36. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  37. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  38. package/dest/archiver/l1/bin/retrieve-calldata.js +147 -0
  39. package/dest/archiver/l1/calldata_retriever.d.ts +98 -0
  40. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  41. package/dest/archiver/l1/calldata_retriever.js +403 -0
  42. package/dest/archiver/l1/data_retrieval.d.ts +87 -0
  43. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  44. package/dest/archiver/{data_retrieval.js → l1/data_retrieval.js} +118 -154
  45. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  46. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  47. package/dest/archiver/l1/debug_tx.js +73 -0
  48. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  49. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  50. package/dest/archiver/l1/spire_proposer.js +157 -0
  51. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  52. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  53. package/dest/archiver/l1/trace_tx.js +91 -0
  54. package/dest/archiver/l1/types.d.ts +12 -0
  55. package/dest/archiver/l1/types.d.ts.map +1 -0
  56. package/dest/archiver/l1/types.js +3 -0
  57. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  58. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  59. package/dest/archiver/l1/validate_trace.js +150 -0
  60. package/dest/archiver/structs/data_retrieval.d.ts +1 -1
  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 +3 -2
  65. package/dest/archiver/structs/published.d.ts.map +1 -1
  66. package/dest/archiver/validation.d.ts +10 -4
  67. package/dest/archiver/validation.d.ts.map +1 -1
  68. package/dest/archiver/validation.js +66 -44
  69. package/dest/factory.d.ts +3 -11
  70. package/dest/factory.d.ts.map +1 -1
  71. package/dest/factory.js +5 -17
  72. package/dest/index.d.ts +2 -2
  73. package/dest/index.d.ts.map +1 -1
  74. package/dest/index.js +1 -1
  75. package/dest/rpc/index.d.ts +2 -2
  76. package/dest/test/index.d.ts +1 -1
  77. package/dest/test/mock_archiver.d.ts +16 -8
  78. package/dest/test/mock_archiver.d.ts.map +1 -1
  79. package/dest/test/mock_archiver.js +19 -14
  80. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  81. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  82. package/dest/test/mock_l1_to_l2_message_source.js +10 -9
  83. package/dest/test/mock_l2_block_source.d.ts +24 -20
  84. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  85. package/dest/test/mock_l2_block_source.js +79 -13
  86. package/dest/test/mock_structs.d.ts +3 -2
  87. package/dest/test/mock_structs.d.ts.map +1 -1
  88. package/dest/test/mock_structs.js +9 -8
  89. package/package.json +18 -17
  90. package/src/archiver/archiver.ts +610 -363
  91. package/src/archiver/archiver_store.ts +55 -28
  92. package/src/archiver/archiver_store_test_suite.ts +369 -143
  93. package/src/archiver/config.ts +26 -51
  94. package/src/archiver/instrumentation.ts +19 -2
  95. package/src/archiver/kv_archiver_store/block_store.ts +139 -21
  96. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  97. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  98. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +48 -33
  99. package/src/archiver/kv_archiver_store/log_store.ts +4 -30
  100. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  101. package/src/archiver/l1/README.md +98 -0
  102. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  103. package/src/archiver/l1/calldata_retriever.ts +531 -0
  104. package/src/archiver/{data_retrieval.ts → l1/data_retrieval.ts} +198 -242
  105. package/src/archiver/l1/debug_tx.ts +99 -0
  106. package/src/archiver/l1/spire_proposer.ts +160 -0
  107. package/src/archiver/l1/trace_tx.ts +128 -0
  108. package/src/archiver/l1/types.ts +13 -0
  109. package/src/archiver/l1/validate_trace.ts +211 -0
  110. package/src/archiver/structs/inbox_message.ts +8 -8
  111. package/src/archiver/structs/published.ts +2 -1
  112. package/src/archiver/validation.ts +86 -32
  113. package/src/factory.ts +6 -26
  114. package/src/index.ts +1 -1
  115. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  116. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  117. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  118. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  119. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  120. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  121. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  122. package/src/test/mock_archiver.ts +22 -16
  123. package/src/test/mock_l1_to_l2_message_source.ts +10 -9
  124. package/src/test/mock_l2_block_source.ts +110 -27
  125. package/src/test/mock_structs.ts +10 -9
  126. package/dest/archiver/data_retrieval.d.ts +0 -78
  127. package/dest/archiver/data_retrieval.d.ts.map +0 -1
@@ -4,72 +4,89 @@ 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
- import { pick } from '@aztec/foundation/collection';
12
- import { Fr } from '@aztec/foundation/fields';
14
+ import { merge, pick } from '@aztec/foundation/collection';
15
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
16
  import { createLogger } from '@aztec/foundation/log';
17
+ import { promiseWithResolvers } from '@aztec/foundation/promise';
14
18
  import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
15
- import { sleep } from '@aztec/foundation/sleep';
16
19
  import { count } from '@aztec/foundation/string';
17
- import { Timer, elapsed } from '@aztec/foundation/timer';
20
+ import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
18
21
  import { ContractClassPublishedEvent, PrivateFunctionBroadcastedEvent, UtilityFunctionBroadcastedEvent } from '@aztec/protocol-contracts/class-registry';
19
22
  import { ContractInstancePublishedEvent, ContractInstanceUpdatedEvent } from '@aztec/protocol-contracts/instance-registry';
20
- import { L2BlockSourceEvents } from '@aztec/stdlib/block';
23
+ import { L2Block, L2BlockSourceEvents, PublishedL2Block } from '@aztec/stdlib/block';
21
24
  import { computePublicBytecodeCommitment, isValidPrivateFunctionMembershipProof, isValidUtilityFunctionMembershipProof } from '@aztec/stdlib/contract';
22
25
  import { getEpochAtSlot, getEpochNumberAtTimestamp, getSlotAtTimestamp, getSlotRangeForEpoch, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
23
- import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
26
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
27
+ import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
24
28
  import { EventEmitter } from 'events';
25
29
  import groupBy from 'lodash.groupby';
26
30
  import { createPublicClient, fallback, http } from 'viem';
27
- import { retrieveBlocksFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedBlockToPublishedL2Block } from './data_retrieval.js';
28
31
  import { InitialBlockNumberNotSequentialError, NoBlobBodiesFoundError } from './errors.js';
29
32
  import { ArchiverInstrumentation } from './instrumentation.js';
30
- import { validateBlockAttestations } from './validation.js';
33
+ import { retrieveCheckpointsFromRollup, retrieveL1ToL2Message, retrieveL1ToL2Messages, retrievedToPublishedCheckpoint } from './l1/data_retrieval.js';
34
+ import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
35
+ import { validateCheckpointAttestations } from './validation.js';
36
+ function mapArchiverConfig(config) {
37
+ return {
38
+ pollingIntervalMs: config.archiverPollingIntervalMS,
39
+ batchSize: config.archiverBatchSize,
40
+ skipValidateBlockAttestations: config.skipValidateBlockAttestations,
41
+ maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds,
42
+ ethereumAllowNoDebugHosts: config.ethereumAllowNoDebugHosts
43
+ };
44
+ }
31
45
  /**
32
- * Pulls L2 blocks in a non-blocking manner and provides interface for their retrieval.
46
+ * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
33
47
  * Responsible for handling robust L1 polling so that other components do not need to
34
48
  * concern themselves with it.
35
49
  */ export class Archiver extends EventEmitter {
36
50
  publicClient;
51
+ debugClient;
37
52
  l1Addresses;
38
53
  dataStore;
39
54
  config;
40
55
  blobSinkClient;
41
56
  epochCache;
57
+ dateProvider;
42
58
  instrumentation;
43
59
  l1constants;
44
60
  log;
45
- /**
46
- * A promise in which we will be continually fetching new L2 blocks.
47
- */ runningPromise;
61
+ /** A loop in which we will be continually fetching new checkpoints. */ runningPromise;
48
62
  rollup;
49
63
  inbox;
50
64
  store;
51
65
  l1BlockNumber;
52
66
  l1Timestamp;
53
- pendingChainValidationStatus;
54
67
  initialSyncComplete;
68
+ initialSyncPromise;
55
69
  tracer;
56
70
  /**
57
71
  * Creates a new instance of the Archiver.
58
72
  * @param publicClient - A client for interacting with the Ethereum node.
73
+ * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
59
74
  * @param rollupAddress - Ethereum address of the rollup contract.
60
75
  * @param inboxAddress - Ethereum address of the inbox contract.
61
76
  * @param registryAddress - Ethereum address of the registry contract.
62
77
  * @param pollingIntervalMs - The interval for polling for L1 logs (in milliseconds).
63
78
  * @param store - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
64
79
  * @param log - A logger.
65
- */ constructor(publicClient, l1Addresses, dataStore, config, blobSinkClient, epochCache, instrumentation, l1constants, log = createLogger('archiver')){
66
- super(), this.publicClient = publicClient, this.l1Addresses = l1Addresses, this.dataStore = dataStore, this.config = config, this.blobSinkClient = blobSinkClient, this.epochCache = epochCache, this.instrumentation = instrumentation, this.l1constants = l1constants, this.log = log, this.pendingChainValidationStatus = {
67
- valid: true
68
- }, this.initialSyncComplete = false;
80
+ */ constructor(publicClient, debugClient, l1Addresses, dataStore, config, blobSinkClient, epochCache, dateProvider, instrumentation, l1constants, log = createLogger('archiver')){
81
+ super(), this.publicClient = publicClient, this.debugClient = debugClient, 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;
69
82
  this.tracer = instrumentation.tracer;
70
83
  this.store = new ArchiverStoreHelper(dataStore);
71
84
  this.rollup = new RollupContract(publicClient, l1Addresses.rollupAddress);
72
85
  this.inbox = new InboxContract(publicClient, l1Addresses.inboxAddress);
86
+ this.initialSyncPromise = promiseWithResolvers();
87
+ // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
88
+ // are done as fast as possible. This then gets updated once the initial sync completes.
89
+ this.runningPromise = new RunningPromise(()=>this.sync(), this.log, this.config.pollingIntervalMs / 10, makeLoggingErrorHandler(this.log, NoBlobBodiesFoundError, BlockTagTooOldError));
73
90
  }
74
91
  /**
75
92
  * Creates a new instance of the Archiver and blocks until it syncs from chain.
@@ -84,11 +101,20 @@ import { validateBlockAttestations } from './validation.js';
84
101
  transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
85
102
  pollingInterval: config.viemPollingIntervalMS
86
103
  });
104
+ // Create debug client using debug RPC URLs if available, otherwise fall back to regular RPC URLs
105
+ const debugRpcUrls = config.l1DebugRpcUrls.length > 0 ? config.l1DebugRpcUrls : config.l1RpcUrls;
106
+ const debugClient = createPublicClient({
107
+ chain: chain.chainInfo,
108
+ transport: fallback(debugRpcUrls.map((url)=>http(url))),
109
+ pollingInterval: config.viemPollingIntervalMS
110
+ });
87
111
  const rollup = new RollupContract(publicClient, config.l1Contracts.rollupAddress);
88
- const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs] = await Promise.all([
112
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, genesisArchiveRoot, slashingProposerAddress] = await Promise.all([
89
113
  rollup.getL1StartBlock(),
90
114
  rollup.getL1GenesisTime(),
91
- rollup.getProofSubmissionEpochs()
115
+ rollup.getProofSubmissionEpochs(),
116
+ rollup.getGenesisArchiveTreeRoot(),
117
+ rollup.getSlashingProposerAddress()
92
118
  ]);
93
119
  const l1StartBlockHash = await publicClient.getBlock({
94
120
  blockNumber: l1StartBlock,
@@ -102,61 +128,74 @@ import { validateBlockAttestations } from './validation.js';
102
128
  epochDuration,
103
129
  slotDuration,
104
130
  ethereumSlotDuration,
105
- proofSubmissionEpochs: Number(proofSubmissionEpochs)
106
- };
107
- const opts = {
108
- pollingIntervalMs: config.archiverPollingIntervalMS ?? 10_000,
109
- batchSize: config.archiverBatchSize ?? 100
131
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
132
+ genesisArchiveRoot: Fr.fromHexString(genesisArchiveRoot)
110
133
  };
134
+ const opts = merge({
135
+ pollingIntervalMs: 10_000,
136
+ batchSize: 100,
137
+ maxAllowedEthClientDriftSeconds: 300,
138
+ ethereumAllowNoDebugHosts: false
139
+ }, mapArchiverConfig(config));
111
140
  const epochCache = deps.epochCache ?? await EpochCache.create(config.l1Contracts.rollupAddress, config, deps);
112
141
  const telemetry = deps.telemetry ?? getTelemetryClient();
113
- const archiver = new Archiver(publicClient, config.l1Contracts, archiverStore, opts, deps.blobSinkClient, epochCache, await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
142
+ const archiver = new Archiver(publicClient, debugClient, {
143
+ ...config.l1Contracts,
144
+ slashingProposerAddress
145
+ }, archiverStore, opts, deps.blobSinkClient, epochCache, deps.dateProvider ?? new DateProvider(), await ArchiverInstrumentation.new(telemetry, ()=>archiverStore.estimateSize()), l1Constants);
114
146
  await archiver.start(blockUntilSynced);
115
147
  return archiver;
116
148
  }
149
+ /** Updates archiver config */ updateConfig(newConfig) {
150
+ this.config = merge(this.config, mapArchiverConfig(newConfig));
151
+ }
117
152
  /**
118
153
  * Starts sync process.
119
154
  * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
120
155
  */ async start(blockUntilSynced) {
121
- if (this.runningPromise) {
156
+ if (this.runningPromise.isRunning()) {
122
157
  throw new Error('Archiver is already running');
123
158
  }
124
159
  await this.blobSinkClient.testSources();
160
+ await this.testEthereumNodeSynced();
161
+ await validateAndLogTraceAvailability(this.debugClient, this.config.ethereumAllowNoDebugHosts ?? false);
162
+ // Log initial state for the archiver
163
+ const { l1StartBlock } = this.l1constants;
164
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
165
+ const currentL2Block = await this.getBlockNumber();
166
+ this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo} and L2 block ${currentL2Block}`, {
167
+ blocksSynchedTo,
168
+ messagesSynchedTo,
169
+ currentL2Block
170
+ });
171
+ // Start sync loop, and return the wait for initial sync if we are asked to block until synced
172
+ this.runningPromise.start();
125
173
  if (blockUntilSynced) {
126
- while(!await this.syncSafe(true)){
127
- this.log.info(`Retrying initial archiver sync in ${this.config.pollingIntervalMs}ms`);
128
- await sleep(this.config.pollingIntervalMs);
129
- }
174
+ return this.waitForInitialSync();
130
175
  }
131
- this.runningPromise = new RunningPromise(()=>this.sync(false), this.log, this.config.pollingIntervalMs, makeLoggingErrorHandler(this.log, // Ignored errors will not log to the console
132
- // We ignore NoBlobBodiesFound as the message may not have been passed to the blob sink yet
133
- NoBlobBodiesFoundError));
134
- this.runningPromise.start();
135
176
  }
136
177
  syncImmediate() {
137
- if (!this.runningPromise) {
138
- throw new Error('Archiver is not running');
139
- }
140
178
  return this.runningPromise.trigger();
141
179
  }
142
- async syncSafe(initialRun) {
143
- try {
144
- await this.sync(initialRun);
145
- return true;
146
- } catch (error) {
147
- if (error instanceof NoBlobBodiesFoundError) {
148
- this.log.error(`Error syncing archiver: ${error.message}`);
149
- } else if (error instanceof BlockTagTooOldError) {
150
- this.log.warn(`Re-running archiver sync: ${error.message}`);
151
- } else {
152
- this.log.error('Error during archiver sync', error);
153
- }
154
- return false;
180
+ waitForInitialSync() {
181
+ return this.initialSyncPromise.promise;
182
+ }
183
+ /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */ async testEthereumNodeSynced() {
184
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
185
+ if (maxAllowedDelay === 0) {
186
+ return;
187
+ }
188
+ const { number, timestamp: l1Timestamp } = await this.publicClient.getBlock({
189
+ includeTransactions: false
190
+ });
191
+ const currentTime = BigInt(this.dateProvider.nowInSeconds());
192
+ if (currentTime - l1Timestamp > BigInt(maxAllowedDelay)) {
193
+ throw new Error(`Ethereum node is out of sync (last block synced ${number} at ${l1Timestamp} vs current time ${currentTime})`);
155
194
  }
156
195
  }
157
196
  /**
158
197
  * Fetches logs from L1 contracts and processes them.
159
- */ async sync(initialRun) {
198
+ */ async sync() {
160
199
  /**
161
200
  * We keep track of three "pointers" to L1 blocks:
162
201
  * 1. the last L1 block that published an L2 block
@@ -166,8 +205,6 @@ import { validateBlockAttestations } from './validation.js';
166
205
  * We do this to deal with L1 data providers that are eventually consistent (e.g. Infura).
167
206
  * We guard against seeing block X with no data at one point, and later, the provider processes the block and it has data.
168
207
  * The archiver will stay back, until there's data on L1 that will move the pointers forward.
169
- *
170
- * This code does not handle reorgs.
171
208
  */ const { l1StartBlock, l1StartBlockHash } = this.l1constants;
172
209
  const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = {
173
210
  l1BlockNumber: l1StartBlock,
@@ -178,12 +215,12 @@ import { validateBlockAttestations } from './validation.js';
178
215
  });
179
216
  const currentL1BlockNumber = currentL1Block.number;
180
217
  const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
181
- if (initialRun) {
182
- this.log.info(`Starting archiver sync to rollup contract ${this.l1Addresses.rollupAddress.toString()} from L1 block ${blocksSynchedTo}` + ` to current L1 block ${currentL1BlockNumber} with hash ${currentL1BlockHash.toString()}`, {
183
- blocksSynchedTo,
184
- messagesSynchedTo
185
- });
186
- }
218
+ this.log.trace(`Starting new archiver sync iteration`, {
219
+ blocksSynchedTo,
220
+ messagesSynchedTo,
221
+ currentL1BlockNumber,
222
+ currentL1BlockHash
223
+ });
187
224
  // ********** Ensuring Consistency of data pulled from L1 **********
188
225
  /**
189
226
  * There are a number of calls in this sync operation to L1 for retrieving
@@ -206,28 +243,40 @@ import { validateBlockAttestations } from './validation.js';
206
243
  const currentL1Timestamp = !this.l1Timestamp || !this.l1BlockNumber || this.l1BlockNumber !== currentL1BlockNumber ? (await this.publicClient.getBlock({
207
244
  blockNumber: currentL1BlockNumber
208
245
  })).timestamp : this.l1Timestamp;
209
- // ********** Events that are processed per L2 block **********
246
+ // Warn if the latest L1 block timestamp is too old
247
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
248
+ const now = this.dateProvider.nowInSeconds();
249
+ if (maxAllowedDelay > 0 && Number(currentL1Timestamp) <= now - maxAllowedDelay) {
250
+ this.log.warn(`Latest L1 block ${currentL1BlockNumber} timestamp ${currentL1Timestamp} is too old. Make sure your Ethereum node is synced.`, {
251
+ currentL1BlockNumber,
252
+ currentL1Timestamp,
253
+ now,
254
+ maxAllowedDelay
255
+ });
256
+ }
257
+ // ********** Events that are processed per checkpoint **********
210
258
  if (currentL1BlockNumber > blocksSynchedTo) {
211
- // First we retrieve new L2 blocks
212
- const rollupStatus = await this.handleL2blocks(blocksSynchedTo, currentL1BlockNumber);
259
+ // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
260
+ // pending chain validation status, proven checkpoint number, and synched L1 block number.
261
+ const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber);
213
262
  // Then we prune the current epoch if it'd reorg on next submission.
214
- // Note that we don't do this before retrieving L2 blocks because we may need to retrieve
215
- // blocks from more than 2 epochs ago, so we want to make sure we have the latest view of
263
+ // Note that we don't do this before retrieving checkpoints because we may need to retrieve
264
+ // checkpoints from more than 2 epochs ago, so we want to make sure we have the latest view of
216
265
  // the chain locally before we start unwinding stuff. This can be optimized by figuring out
217
- // up to which point we're pruning, and then requesting L2 blocks up to that point only.
218
- const { rollupCanPrune } = await this.handleEpochPrune(rollupStatus.provenBlockNumber, currentL1BlockNumber, currentL1Timestamp);
219
- // Update the pending chain validation status with the last block validation result.
220
- // Again, we only update if validation status changed, so in a sequence of invalid blocks
221
- // we keep track of the first invalid block so we can invalidate that one if needed.
222
- if (rollupStatus.validationResult && rollupStatus.validationResult?.valid !== this.pendingChainValidationStatus.valid) {
223
- this.pendingChainValidationStatus = rollupStatus.validationResult;
266
+ // up to which point we're pruning, and then requesting checkpoints up to that point only.
267
+ const { rollupCanPrune } = await this.handleEpochPrune(rollupStatus.provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp);
268
+ // If the last checkpoint we processed had an invalid attestation, we manually advance the L1 syncpoint
269
+ // past it, since otherwise we'll keep downloading it and reprocessing it on every iteration until
270
+ // we get a valid checkpoint to advance the syncpoint.
271
+ if (!rollupStatus.validationResult?.valid && rollupStatus.lastL1BlockWithCheckpoint !== undefined) {
272
+ await this.store.setBlockSynchedL1BlockNumber(rollupStatus.lastL1BlockWithCheckpoint);
224
273
  }
225
- // And lastly we check if we are missing any L2 blocks behind us due to a possible L1 reorg.
274
+ // And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
226
275
  // We only do this if rollup cant prune on the next submission. Otherwise we will end up
227
- // re-syncing the blocks we have just unwound above. We also dont do this if the last block is invalid,
276
+ // re-syncing the checkpoints we have just unwound above. We also dont do this if the last checkpoint is invalid,
228
277
  // since the archiver will rightfully refuse to sync up to it.
229
- if (!rollupCanPrune && this.pendingChainValidationStatus.valid) {
230
- await this.checkForNewBlocksBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
278
+ if (!rollupCanPrune && rollupStatus.validationResult?.valid) {
279
+ await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
231
280
  }
232
281
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
233
282
  }
@@ -236,13 +285,17 @@ import { validateBlockAttestations } from './validation.js';
236
285
  // but the corresponding blocks have not been processed (see #12631).
237
286
  this.l1Timestamp = currentL1Timestamp;
238
287
  this.l1BlockNumber = currentL1BlockNumber;
239
- this.initialSyncComplete = true;
240
- if (initialRun) {
241
- this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete.`, {
288
+ // We resolve the initial sync only once we've caught up with the latest L1 block number (with 1 block grace)
289
+ // so if the initial sync took too long, we still go for another iteration.
290
+ if (!this.initialSyncComplete && currentL1BlockNumber + 1n >= await this.publicClient.getBlockNumber()) {
291
+ this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
242
292
  l1BlockNumber: currentL1BlockNumber,
243
293
  syncPoint: await this.store.getSynchPoint(),
244
294
  ...await this.getL2Tips()
245
295
  });
296
+ this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
297
+ this.initialSyncComplete = true;
298
+ this.initialSyncPromise.resolve();
246
299
  }
247
300
  }
248
301
  /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */ async canPrune(currentL1BlockNumber, currentL1Timestamp) {
@@ -259,30 +312,30 @@ import { validateBlockAttestations } from './validation.js';
259
312
  }
260
313
  return result;
261
314
  }
262
- /** Checks if there'd be a reorg for the next block submission and start pruning now. */ async handleEpochPrune(provenBlockNumber, currentL1BlockNumber, currentL1Timestamp) {
315
+ /** Checks if there'd be a reorg for the next checkpoint submission and start pruning now. */ async handleEpochPrune(provenCheckpointNumber, currentL1BlockNumber, currentL1Timestamp) {
263
316
  const rollupCanPrune = await this.canPrune(currentL1BlockNumber, currentL1Timestamp);
264
- const localPendingBlockNumber = await this.getBlockNumber();
265
- const canPrune = localPendingBlockNumber > provenBlockNumber && rollupCanPrune;
317
+ const localPendingCheckpointNumber = await this.getSynchedCheckpointNumber();
318
+ const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
266
319
  if (canPrune) {
267
320
  const timer = new Timer();
268
- const pruneFrom = provenBlockNumber + 1;
269
- const header = await this.getBlockHeader(Number(pruneFrom));
321
+ const pruneFrom = CheckpointNumber(provenCheckpointNumber + 1);
322
+ const header = await this.getCheckpointHeader(pruneFrom);
270
323
  if (header === undefined) {
271
- throw new Error(`Missing block header ${pruneFrom}`);
324
+ throw new Error(`Missing checkpoint header ${pruneFrom}`);
272
325
  }
273
- const pruneFromSlotNumber = header.globalVariables.slotNumber.toBigInt();
326
+ const pruneFromSlotNumber = header.slotNumber;
274
327
  const pruneFromEpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1constants);
275
- const blocksToUnwind = localPendingBlockNumber - provenBlockNumber;
276
- const blocks = await this.getBlocks(Number(provenBlockNumber) + 1, Number(blocksToUnwind));
328
+ const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
329
+ const checkpoints = await this.getCheckpoints(pruneFrom, checkpointsToUnwind);
277
330
  // Emit an event for listening services to react to the chain prune
278
331
  this.emit(L2BlockSourceEvents.L2PruneDetected, {
279
332
  type: L2BlockSourceEvents.L2PruneDetected,
280
333
  epochNumber: pruneFromEpochNumber,
281
- blocks
334
+ blocks: checkpoints.flatMap((c)=>L2Block.fromCheckpoint(c))
282
335
  });
283
- this.log.debug(`L2 prune from ${provenBlockNumber + 1} to ${localPendingBlockNumber} will occur on next block submission.`);
284
- await this.store.unwindBlocks(Number(localPendingBlockNumber), Number(blocksToUnwind));
285
- this.log.warn(`Unwound ${count(blocksToUnwind, 'block')} from L2 block ${localPendingBlockNumber} ` + `to ${provenBlockNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest block is ${await this.getBlockNumber()}.`);
336
+ this.log.debug(`L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`);
337
+ await this.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
338
+ this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `to ${provenCheckpointNumber} due to predicted reorg at L1 block ${currentL1BlockNumber}. ` + `Updated latest checkpoint is ${await this.getSynchedCheckpointNumber()}.`);
286
339
  this.instrumentation.processPrune(timer.ms());
287
340
  // TODO(palla/reorg): Do we need to set the block synched L1 block number here?
288
341
  // Seems like the next iteration should handle this.
@@ -325,7 +378,7 @@ import { validateBlockAttestations } from './validation.js';
325
378
  });
326
379
  // Compare message count and rolling hash. If they match, no need to retrieve anything.
327
380
  if (remoteMessagesState.totalMessagesInserted === localMessagesInserted && remoteMessagesState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)) {
328
- this.log.debug(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
381
+ this.log.trace(`No L1 to L2 messages to query between L1 blocks ${messagesSyncPoint.l1BlockNumber} and ${currentL1BlockNumber}.`);
329
382
  return;
330
383
  }
331
384
  // Check if our syncpoint is still valid. If not, there was an L1 reorg and we need to re-retrieve messages.
@@ -374,7 +427,7 @@ import { validateBlockAttestations } from './validation.js';
374
427
  }while (searchEndBlock < currentL1BlockNumber)
375
428
  // Log stats for messages retrieved (if any).
376
429
  if (messageCount > 0) {
377
- this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for L2 block ${lastMessage?.l2BlockNumber}`, {
430
+ this.log.info(`Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`, {
378
431
  lastMessage,
379
432
  messageCount
380
433
  });
@@ -451,156 +504,173 @@ import { validateBlockAttestations } from './validation.js';
451
504
  }
452
505
  return Buffer32.fromString(block.hash);
453
506
  }
454
- async handleL2blocks(blocksSynchedTo, currentL1BlockNumber) {
455
- const localPendingBlockNumber = await this.getBlockNumber();
456
- const [provenBlockNumber, provenArchive, pendingBlockNumber, pendingArchive, archiveForLocalPendingBlockNumber] = await this.rollup.status(BigInt(localPendingBlockNumber), {
507
+ async handleCheckpoints(blocksSynchedTo, currentL1BlockNumber) {
508
+ const localPendingCheckpointNumber = await this.getSynchedCheckpointNumber();
509
+ const initialValidationResult = await this.store.getPendingChainValidationStatus();
510
+ const [rollupProvenCheckpointNumber, provenArchive, rollupPendingCheckpointNumber, pendingArchive, archiveForLocalPendingCheckpointNumber] = await this.rollup.status(localPendingCheckpointNumber, {
457
511
  blockNumber: currentL1BlockNumber
458
512
  });
513
+ const provenCheckpointNumber = CheckpointNumber.fromBigInt(rollupProvenCheckpointNumber);
514
+ const pendingCheckpointNumber = CheckpointNumber.fromBigInt(rollupPendingCheckpointNumber);
459
515
  const rollupStatus = {
460
- provenBlockNumber: Number(provenBlockNumber),
516
+ provenCheckpointNumber,
461
517
  provenArchive,
462
- pendingBlockNumber: Number(pendingBlockNumber),
518
+ pendingCheckpointNumber,
463
519
  pendingArchive,
464
- validationResult: undefined
520
+ validationResult: initialValidationResult
465
521
  };
466
522
  this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
467
- localPendingBlockNumber,
523
+ localPendingCheckpointNumber,
468
524
  blocksSynchedTo,
469
525
  currentL1BlockNumber,
470
- archiveForLocalPendingBlockNumber,
526
+ archiveForLocalPendingCheckpointNumber,
471
527
  ...rollupStatus
472
528
  });
473
- const updateProvenBlock = async ()=>{
474
- // Annoying edge case: if proven block is moved back to 0 due to a reorg at the beginning of the chain,
475
- // we need to set it to zero. This is an edge case because we dont have a block zero (initial block is one),
476
- // so localBlockForDestinationProvenBlockNumber would not be found below.
477
- if (provenBlockNumber === 0n) {
478
- const localProvenBlockNumber = await this.store.getProvenL2BlockNumber();
479
- if (localProvenBlockNumber !== Number(provenBlockNumber)) {
480
- await this.store.setProvenL2BlockNumber(Number(provenBlockNumber));
481
- this.log.info(`Rolled back proven chain to block ${provenBlockNumber}`, {
482
- provenBlockNumber
529
+ const updateProvenCheckpoint = async ()=>{
530
+ // Annoying edge case: if proven checkpoint is moved back to 0 due to a reorg at the beginning of the chain,
531
+ // we need to set it to zero. This is an edge case because we dont have a checkpoint zero (initial checkpoint is one),
532
+ // so localCheckpointForDestinationProvenCheckpointNumber would not be found below.
533
+ if (provenCheckpointNumber === 0) {
534
+ const localProvenCheckpointNumber = await this.getProvenCheckpointNumber();
535
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
536
+ await this.setProvenCheckpointNumber(provenCheckpointNumber);
537
+ this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, {
538
+ provenCheckpointNumber
483
539
  });
484
540
  }
485
541
  }
486
- const localBlockForDestinationProvenBlockNumber = await this.getBlock(Number(provenBlockNumber));
487
- // Sanity check. I've hit what seems to be a state where the proven block is set to a value greater than the latest
488
- // synched block when requesting L2Tips from the archiver. This is the only place where the proven block is set.
489
- const synched = await this.store.getSynchedL2BlockNumber();
490
- if (localBlockForDestinationProvenBlockNumber && synched < localBlockForDestinationProvenBlockNumber?.number) {
491
- this.log.error(`Hit local block greater than last synched block: ${localBlockForDestinationProvenBlockNumber.number} > ${synched}`);
542
+ const localCheckpointForDestinationProvenCheckpointNumber = await this.getCheckpoint(provenCheckpointNumber);
543
+ // Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
544
+ // synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
545
+ const synched = await this.getSynchedCheckpointNumber();
546
+ if (localCheckpointForDestinationProvenCheckpointNumber && synched < localCheckpointForDestinationProvenCheckpointNumber.number) {
547
+ this.log.error(`Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.number} > ${synched}`);
492
548
  }
493
- this.log.trace(`Local block for remote proven block ${provenBlockNumber} is ${localBlockForDestinationProvenBlockNumber?.archive.root.toString() ?? 'undefined'}`);
494
- if (localBlockForDestinationProvenBlockNumber && provenArchive === localBlockForDestinationProvenBlockNumber.archive.root.toString()) {
495
- const localProvenBlockNumber = await this.store.getProvenL2BlockNumber();
496
- if (localProvenBlockNumber !== Number(provenBlockNumber)) {
497
- await this.store.setProvenL2BlockNumber(Number(provenBlockNumber));
498
- this.log.info(`Updated proven chain to block ${provenBlockNumber}`, {
499
- provenBlockNumber
549
+ this.log.trace(`Local checkpoint for remote proven checkpoint ${provenCheckpointNumber} is ${localCheckpointForDestinationProvenCheckpointNumber?.archive.root.toString() ?? 'undefined'}`);
550
+ const lastProvenBlockNumber = await this.getLastBlockNumberInCheckpoint(provenCheckpointNumber);
551
+ if (localCheckpointForDestinationProvenCheckpointNumber && provenArchive === localCheckpointForDestinationProvenCheckpointNumber.archive.root.toString()) {
552
+ const localProvenCheckpointNumber = await this.getProvenCheckpointNumber();
553
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
554
+ await this.setProvenCheckpointNumber(provenCheckpointNumber);
555
+ this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, {
556
+ provenCheckpointNumber
500
557
  });
501
- const provenSlotNumber = localBlockForDestinationProvenBlockNumber.header.globalVariables.slotNumber.toBigInt();
558
+ const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
502
559
  const provenEpochNumber = getEpochAtSlot(provenSlotNumber, this.l1constants);
503
560
  this.emit(L2BlockSourceEvents.L2BlockProven, {
504
561
  type: L2BlockSourceEvents.L2BlockProven,
505
- blockNumber: provenBlockNumber,
562
+ blockNumber: lastProvenBlockNumber,
506
563
  slotNumber: provenSlotNumber,
507
564
  epochNumber: provenEpochNumber
508
565
  });
509
566
  } else {
510
- this.log.trace(`Proven block ${provenBlockNumber} already stored.`);
567
+ this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
511
568
  }
512
569
  }
513
- this.instrumentation.updateLastProvenBlock(Number(provenBlockNumber));
570
+ this.instrumentation.updateLastProvenBlock(lastProvenBlockNumber);
514
571
  };
515
- // This is an edge case that we only hit if there are no proposed blocks.
516
- // If we have 0 blocks locally and there are no blocks onchain there is nothing to do.
517
- const noBlocks = localPendingBlockNumber === 0 && pendingBlockNumber === 0n;
518
- if (noBlocks) {
572
+ // This is an edge case that we only hit if there are no proposed checkpoints.
573
+ // If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
574
+ const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
575
+ if (noCheckpoints) {
519
576
  await this.store.setBlockSynchedL1BlockNumber(currentL1BlockNumber);
520
- this.log.debug(`No blocks to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no blocks on chain`);
577
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`);
521
578
  return rollupStatus;
522
579
  }
523
- await updateProvenBlock();
580
+ await updateProvenCheckpoint();
524
581
  // Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
525
- // are any state that could be impacted by it. If we have no blocks, there is no impact.
526
- if (localPendingBlockNumber > 0) {
527
- const localPendingBlock = await this.getBlock(localPendingBlockNumber);
528
- if (localPendingBlock === undefined) {
529
- throw new Error(`Missing block ${localPendingBlockNumber}`);
582
+ // are any state that could be impacted by it. If we have no checkpoints, there is no impact.
583
+ if (localPendingCheckpointNumber > 0) {
584
+ const localPendingCheckpoint = await this.getCheckpoint(localPendingCheckpointNumber);
585
+ if (localPendingCheckpoint === undefined) {
586
+ throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
530
587
  }
531
- const localPendingArchiveRoot = localPendingBlock.archive.root.toString();
532
- const noBlockSinceLast = localPendingBlock && pendingArchive === localPendingArchiveRoot;
533
- if (noBlockSinceLast) {
588
+ const localPendingArchiveRoot = localPendingCheckpoint.archive.root.toString();
589
+ const noCheckpointSinceLast = localPendingCheckpoint && pendingArchive === localPendingArchiveRoot;
590
+ if (noCheckpointSinceLast) {
534
591
  // We believe the following line causes a problem when we encounter L1 re-orgs.
535
592
  // Basically, by setting the synched L1 block number here, we are saying that we have
536
- // processed all blocks up to the current L1 block number and we will not attempt to retrieve logs from
593
+ // processed all checkpoints up to the current L1 block number and we will not attempt to retrieve logs from
537
594
  // this block again (or any blocks before).
538
- // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing blocks
595
+ // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing checkpoints.
539
596
  // We must only set this block number based on actually retrieved logs.
540
597
  // TODO(#8621): Tackle this properly when we handle L1 Re-orgs.
541
598
  // await this.store.setBlockSynchedL1BlockNumber(currentL1BlockNumber);
542
- this.log.debug(`No blocks to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
599
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
543
600
  return rollupStatus;
544
601
  }
545
- const localPendingBlockInChain = archiveForLocalPendingBlockNumber === localPendingArchiveRoot;
546
- if (!localPendingBlockInChain) {
547
- // If our local pending block tip is not in the chain on L1 a "prune" must have happened
602
+ const localPendingCheckpointInChain = archiveForLocalPendingCheckpointNumber === localPendingArchiveRoot;
603
+ if (!localPendingCheckpointInChain) {
604
+ // If our local pending checkpoint tip is not in the chain on L1 a "prune" must have happened
548
605
  // or the L1 have reorged.
549
606
  // In any case, we have to figure out how far into the past the action will take us.
550
- // For simplicity here, we will simply rewind until we end in a block that is also on the chain on L1.
551
- this.log.debug(`L2 prune has been detected due to local pending block ${localPendingBlockNumber} not in chain`, {
552
- localPendingBlockNumber,
607
+ // For simplicity here, we will simply rewind until we end in a checkpoint that is also on the chain on L1.
608
+ this.log.debug(`L2 prune has been detected due to local pending checkpoint ${localPendingCheckpointNumber} not in chain`, {
609
+ localPendingCheckpointNumber,
553
610
  localPendingArchiveRoot,
554
- archiveForLocalPendingBlockNumber
611
+ archiveForLocalPendingCheckpointNumber
555
612
  });
556
- let tipAfterUnwind = localPendingBlockNumber;
613
+ let tipAfterUnwind = localPendingCheckpointNumber;
557
614
  while(true){
558
- const candidateBlock = await this.getBlock(Number(tipAfterUnwind));
559
- if (candidateBlock === undefined) {
615
+ const candidateCheckpoint = await this.getCheckpoint(tipAfterUnwind);
616
+ if (candidateCheckpoint === undefined) {
560
617
  break;
561
618
  }
562
- const archiveAtContract = await this.rollup.archiveAt(BigInt(candidateBlock.number));
563
- if (archiveAtContract === candidateBlock.archive.root.toString()) {
619
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.number);
620
+ this.log.trace(`Checking local checkpoint ${candidateCheckpoint.number} with archive ${candidateCheckpoint.archive.root}`, {
621
+ archiveAtContract,
622
+ archiveLocal: candidateCheckpoint.archive.root.toString()
623
+ });
624
+ if (archiveAtContract === candidateCheckpoint.archive.root.toString()) {
564
625
  break;
565
626
  }
566
627
  tipAfterUnwind--;
567
628
  }
568
- const blocksToUnwind = localPendingBlockNumber - tipAfterUnwind;
569
- await this.store.unwindBlocks(Number(localPendingBlockNumber), Number(blocksToUnwind));
570
- this.log.warn(`Unwound ${count(blocksToUnwind, 'block')} from L2 block ${localPendingBlockNumber} ` + `due to mismatched block hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest block is ${await this.getBlockNumber()}.`);
629
+ const checkpointsToUnwind = localPendingCheckpointNumber - tipAfterUnwind;
630
+ await this.unwindCheckpoints(localPendingCheckpointNumber, checkpointsToUnwind);
631
+ this.log.warn(`Unwound ${count(checkpointsToUnwind, 'checkpoint')} from checkpoint ${localPendingCheckpointNumber} ` + `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` + `Updated L2 latest checkpoint is ${await this.getSynchedCheckpointNumber()}.`);
571
632
  }
572
633
  }
573
- // Retrieve L2 blocks in batches. Each batch is estimated to accommodate up to L2 'blockBatchSize' blocks,
634
+ // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
574
635
  // computed using the L2 block time vs the L1 block time.
575
636
  let searchStartBlock = blocksSynchedTo;
576
637
  let searchEndBlock = blocksSynchedTo;
577
- let lastRetrievedBlock;
638
+ let lastRetrievedCheckpoint;
639
+ let lastL1BlockWithCheckpoint = undefined;
578
640
  do {
579
641
  [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
580
- this.log.trace(`Retrieving L2 blocks from L1 block ${searchStartBlock} to ${searchEndBlock}`);
642
+ this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
581
643
  // TODO(md): Retrieve from blob sink then from consensus client, then from peers
582
- const retrievedBlocks = await retrieveBlocksFromRollup(this.rollup.getContract(), this.publicClient, this.blobSinkClient, searchStartBlock, searchEndBlock, this.log);
583
- if (retrievedBlocks.length === 0) {
644
+ const retrievedCheckpoints = await retrieveCheckpointsFromRollup(this.rollup.getContract(), this.publicClient, this.debugClient, this.blobSinkClient, searchStartBlock, searchEndBlock, this.l1Addresses, this.instrumentation, this.log);
645
+ if (retrievedCheckpoints.length === 0) {
584
646
  // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
585
647
  // See further details in earlier comments.
586
- this.log.trace(`Retrieved no new L2 blocks from L1 block ${searchStartBlock} to ${searchEndBlock}`);
648
+ this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
587
649
  continue;
588
650
  }
589
- const lastProcessedL1BlockNumber = retrievedBlocks[retrievedBlocks.length - 1].l1.blockNumber;
590
- this.log.debug(`Retrieved ${retrievedBlocks.length} new L2 blocks between L1 blocks ${searchStartBlock} and ${searchEndBlock} with last processed L1 block ${lastProcessedL1BlockNumber}.`);
591
- const publishedBlocks = retrievedBlocks.map((b)=>retrievedBlockToPublishedL2Block(b));
592
- const validBlocks = [];
593
- for (const block of publishedBlocks){
594
- const validationResult = await validateBlockAttestations(block, this.epochCache, this.l1constants, this.log);
595
- // Only update the validation result if it has changed, so we can keep track of the first invalid block
596
- // in case there is a sequence of more than one invalid block, as we need to invalidate the first one.
597
- if (rollupStatus.validationResult?.valid !== validationResult.valid) {
651
+ this.log.debug(`Retrieved ${retrievedCheckpoints.length} new checkpoints between L1 blocks ${searchStartBlock} and ${searchEndBlock}`, {
652
+ lastProcessedCheckpoint: retrievedCheckpoints[retrievedCheckpoints.length - 1].l1,
653
+ searchStartBlock,
654
+ searchEndBlock
655
+ });
656
+ const publishedCheckpoints = await Promise.all(retrievedCheckpoints.map((b)=>retrievedToPublishedCheckpoint(b)));
657
+ const validCheckpoints = [];
658
+ for (const published of publishedCheckpoints){
659
+ const validationResult = this.config.skipValidateBlockAttestations ? {
660
+ valid: true
661
+ } : await validateCheckpointAttestations(published, this.epochCache, this.l1constants, this.log);
662
+ // Only update the validation result if it has changed, so we can keep track of the first invalid checkpoint
663
+ // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
664
+ // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
665
+ // we need to update the validation result, since we need to be able to invalidate the new one.
666
+ // See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
667
+ if (rollupStatus.validationResult?.valid !== validationResult.valid || !rollupStatus.validationResult.valid && !validationResult.valid && rollupStatus.validationResult.block.blockNumber === validationResult.block.blockNumber) {
598
668
  rollupStatus.validationResult = validationResult;
599
669
  }
600
670
  if (!validationResult.valid) {
601
- this.log.warn(`Skipping block ${block.block.number} due to invalid attestations`, {
602
- blockHash: block.block.hash(),
603
- l1BlockNumber: block.l1.blockNumber,
671
+ this.log.warn(`Skipping checkpoint ${published.checkpoint.number} due to invalid attestations`, {
672
+ checkpointHash: published.checkpoint.hash(),
673
+ l1BlockNumber: published.l1.blockNumber,
604
674
  ...pick(validationResult, 'reason')
605
675
  });
606
676
  // Emit event for invalid block detection
@@ -610,21 +680,38 @@ import { validateBlockAttestations } from './validation.js';
610
680
  });
611
681
  continue;
612
682
  }
613
- validBlocks.push(block);
614
- this.log.debug(`Ingesting new L2 block ${block.block.number} with ${block.block.body.txEffects.length} txs`, {
615
- blockHash: block.block.hash(),
616
- l1BlockNumber: block.l1.blockNumber,
617
- ...block.block.header.globalVariables.toInspect(),
618
- ...block.block.getStats()
683
+ // Check the inHash of the checkpoint against the l1->l2 messages.
684
+ // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
685
+ // checkpoints we just retrieved.
686
+ const l1ToL2Messages = await this.getL1ToL2Messages(published.checkpoint.number);
687
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
688
+ const publishedInHash = published.checkpoint.header.contentCommitment.inHash;
689
+ if (!computedInHash.equals(publishedInHash)) {
690
+ this.log.fatal(`Mismatch inHash for checkpoint ${published.checkpoint.number}`, {
691
+ checkpointHash: published.checkpoint.hash(),
692
+ l1BlockNumber: published.l1.blockNumber,
693
+ computedInHash,
694
+ publishedInHash
695
+ });
696
+ // Throwing an error since this is most likely caused by a bug.
697
+ throw new Error(`Mismatch inHash for checkpoint ${published.checkpoint.number}. Expected ${computedInHash} but got ${publishedInHash}`);
698
+ }
699
+ validCheckpoints.push(published);
700
+ this.log.debug(`Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`, {
701
+ checkpointHash: published.checkpoint.hash(),
702
+ l1BlockNumber: published.l1.blockNumber,
703
+ ...published.checkpoint.header.toInspect(),
704
+ blocks: published.checkpoint.blocks.map((b)=>b.getStats())
619
705
  });
620
706
  }
621
707
  try {
622
- const [processDuration] = await elapsed(()=>this.store.addBlocks(validBlocks));
623
- this.instrumentation.processNewBlocks(processDuration / validBlocks.length, validBlocks.map((b)=>b.block));
708
+ const updatedValidationResult = rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
709
+ const [processDuration] = await elapsed(()=>this.addCheckpoints(validCheckpoints, updatedValidationResult));
710
+ this.instrumentation.processNewBlocks(processDuration / validCheckpoints.length, validCheckpoints.flatMap((c)=>c.checkpoint.blocks));
624
711
  } catch (err) {
625
712
  if (err instanceof InitialBlockNumberNotSequentialError) {
626
713
  const { previousBlockNumber, newBlockNumber } = err;
627
- const previousBlock = previousBlockNumber ? await this.store.getPublishedBlock(previousBlockNumber) : undefined;
714
+ const previousBlock = previousBlockNumber ? await this.store.getPublishedBlock(BlockNumber(previousBlockNumber)) : undefined;
628
715
  const updatedL1SyncPoint = previousBlock?.l1.blockNumber ?? this.l1constants.l1StartBlock;
629
716
  await this.store.setBlockSynchedL1BlockNumber(updatedL1SyncPoint);
630
717
  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.`, {
@@ -636,58 +723,58 @@ import { validateBlockAttestations } from './validation.js';
636
723
  }
637
724
  throw err;
638
725
  }
639
- for (const block of validBlocks){
640
- this.log.info(`Downloaded L2 block ${block.block.number}`, {
641
- blockHash: await block.block.hash(),
642
- blockNumber: block.block.number,
643
- txCount: block.block.body.txEffects.length,
644
- globalVariables: block.block.header.globalVariables.toInspect(),
645
- archiveRoot: block.block.archive.root.toString(),
646
- archiveNextLeafIndex: block.block.archive.nextAvailableLeafIndex
726
+ for (const checkpoint of validCheckpoints){
727
+ this.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
728
+ checkpointHash: checkpoint.checkpoint.hash(),
729
+ checkpointNumber: checkpoint.checkpoint.number,
730
+ blockCount: checkpoint.checkpoint.blocks.length,
731
+ txCount: checkpoint.checkpoint.blocks.reduce((acc, b)=>acc + b.body.txEffects.length, 0),
732
+ header: checkpoint.checkpoint.header.toInspect(),
733
+ archiveRoot: checkpoint.checkpoint.archive.root.toString(),
734
+ archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex
647
735
  });
648
736
  }
649
- lastRetrievedBlock = validBlocks.at(-1) ?? lastRetrievedBlock;
737
+ lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
738
+ lastL1BlockWithCheckpoint = retrievedCheckpoints.at(-1)?.l1.blockNumber ?? lastL1BlockWithCheckpoint;
650
739
  }while (searchEndBlock < currentL1BlockNumber)
651
740
  // Important that we update AFTER inserting the blocks.
652
- await updateProvenBlock();
741
+ await updateProvenCheckpoint();
653
742
  return {
654
743
  ...rollupStatus,
655
- lastRetrievedBlock
744
+ lastRetrievedCheckpoint,
745
+ lastL1BlockWithCheckpoint
656
746
  };
657
747
  }
658
- async checkForNewBlocksBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
659
- const { lastRetrievedBlock, pendingBlockNumber } = status;
660
- // Compare the last L2 block we have (either retrieved in this round or loaded from store) with what the
748
+ async checkForNewCheckpointsBeforeL1SyncPoint(status, blocksSynchedTo, currentL1BlockNumber) {
749
+ const { lastRetrievedCheckpoint, pendingCheckpointNumber } = status;
750
+ // Compare the last checkpoint we have (either retrieved in this round or loaded from store) with what the
661
751
  // rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
662
- const latestLocalL2BlockNumber = lastRetrievedBlock?.block.number ?? await this.store.getSynchedL2BlockNumber();
663
- if (latestLocalL2BlockNumber < pendingBlockNumber) {
752
+ const latestLocalCheckpointNumber = lastRetrievedCheckpoint?.checkpoint.number ?? await this.getSynchedCheckpointNumber();
753
+ if (latestLocalCheckpointNumber < pendingCheckpointNumber) {
664
754
  // Here we have consumed all logs until the `currentL1Block` we pinned at the beginning of the archiver loop,
665
- // but still havent reached the pending block according to the call to the rollup contract.
666
- // We suspect an L1 reorg that added blocks *behind* us. If that is the case, it must have happened between the
667
- // last L2 block we saw and the current one, so we reset the last synched L1 block number. In the edge case we
668
- // don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
669
- const latestLocalL2Block = lastRetrievedBlock ?? (latestLocalL2BlockNumber > 0 ? await this.store.getPublishedBlocks(latestLocalL2BlockNumber, 1).then(([b])=>b) : undefined);
670
- const targetL1BlockNumber = latestLocalL2Block?.l1.blockNumber ?? maxBigint(currentL1BlockNumber - 64n, 0n);
671
- const latestLocalL2BlockArchive = latestLocalL2Block?.block.archive.root.toString();
672
- this.log.warn(`Failed to reach L2 block ${pendingBlockNumber} at ${currentL1BlockNumber} (latest is ${latestLocalL2BlockNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
673
- latestLocalL2BlockNumber,
674
- latestLocalL2BlockArchive,
755
+ // but still haven't reached the pending checkpoint according to the call to the rollup contract.
756
+ // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
757
+ // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
758
+ // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
759
+ const latestLocalCheckpoint = lastRetrievedCheckpoint ?? (latestLocalCheckpointNumber > 0 ? await this.getPublishedCheckpoints(latestLocalCheckpointNumber, 1).then(([c])=>c) : undefined);
760
+ const targetL1BlockNumber = latestLocalCheckpoint?.l1.blockNumber ?? maxBigint(currentL1BlockNumber - 64n, 0n);
761
+ const latestLocalCheckpointArchive = latestLocalCheckpoint?.checkpoint.archive.root.toString();
762
+ this.log.warn(`Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` + `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`, {
763
+ latestLocalCheckpointNumber,
764
+ latestLocalCheckpointArchive,
675
765
  blocksSynchedTo,
676
766
  currentL1BlockNumber,
677
767
  ...status
678
768
  });
679
769
  await this.store.setBlockSynchedL1BlockNumber(targetL1BlockNumber);
680
770
  } else {
681
- this.log.trace(`No new blocks behind L1 sync point to retrieve.`, {
682
- latestLocalL2BlockNumber,
683
- pendingBlockNumber
771
+ this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
772
+ latestLocalCheckpointNumber,
773
+ pendingCheckpointNumber
684
774
  });
685
775
  }
686
776
  }
687
777
  /** Resumes the archiver after a stop. */ resume() {
688
- if (!this.runningPromise) {
689
- throw new Error(`Archiver was never started`);
690
- }
691
778
  if (this.runningPromise.isRunning()) {
692
779
  this.log.warn(`Archiver already running`);
693
780
  }
@@ -699,7 +786,7 @@ import { validateBlockAttestations } from './validation.js';
699
786
  * @returns A promise signalling completion of the stop process.
700
787
  */ async stop() {
701
788
  this.log.debug('Stopping...');
702
- await this.runningPromise?.stop();
789
+ await this.runningPromise.stop();
703
790
  this.log.info('Stopped.');
704
791
  return Promise.resolve();
705
792
  }
@@ -709,6 +796,11 @@ import { validateBlockAttestations } from './validation.js';
709
796
  getL1Constants() {
710
797
  return Promise.resolve(this.l1constants);
711
798
  }
799
+ getGenesisValues() {
800
+ return Promise.resolve({
801
+ genesisArchiveRoot: this.l1constants.genesisArchiveRoot
802
+ });
803
+ }
712
804
  getRollupAddress() {
713
805
  return Promise.resolve(this.l1Addresses.rollupAddress);
714
806
  }
@@ -716,24 +808,16 @@ import { validateBlockAttestations } from './validation.js';
716
808
  return Promise.resolve(this.l1Addresses.registryAddress);
717
809
  }
718
810
  getL1BlockNumber() {
719
- const l1BlockNumber = this.l1BlockNumber;
720
- if (!l1BlockNumber) {
721
- throw new Error('L1 block number not yet available. Complete an initial sync first.');
722
- }
723
- return l1BlockNumber;
811
+ return this.l1BlockNumber;
724
812
  }
725
813
  getL1Timestamp() {
726
- const l1Timestamp = this.l1Timestamp;
727
- if (!l1Timestamp) {
728
- throw new Error('L1 timestamp not yet available. Complete an initial sync first.');
729
- }
730
- return Promise.resolve(l1Timestamp);
814
+ return Promise.resolve(this.l1Timestamp);
731
815
  }
732
- async getL2SlotNumber() {
733
- return getSlotAtTimestamp(await this.getL1Timestamp(), this.l1constants);
816
+ getL2SlotNumber() {
817
+ return Promise.resolve(this.l1Timestamp === undefined ? undefined : getSlotAtTimestamp(this.l1Timestamp, this.l1constants));
734
818
  }
735
- async getL2EpochNumber() {
736
- return getEpochNumberAtTimestamp(await this.getL1Timestamp(), this.l1constants);
819
+ getL2EpochNumber() {
820
+ return Promise.resolve(this.l1Timestamp === undefined ? undefined : getEpochNumberAtTimestamp(this.l1Timestamp, this.l1constants));
737
821
  }
738
822
  async getBlocksForEpoch(epochNumber) {
739
823
  const [start, end] = getSlotRangeForEpoch(epochNumber, this.l1constants);
@@ -741,12 +825,12 @@ import { validateBlockAttestations } from './validation.js';
741
825
  // Walk the list of blocks backwards and filter by slots matching the requested epoch.
742
826
  // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
743
827
  let block = await this.getBlock(await this.store.getSynchedL2BlockNumber());
744
- const slot = (b)=>b.header.globalVariables.slotNumber.toBigInt();
828
+ const slot = (b)=>b.header.globalVariables.slotNumber;
745
829
  while(block && slot(block) >= start){
746
830
  if (slot(block) <= end) {
747
831
  blocks.push(block);
748
832
  }
749
- block = await this.getBlock(block.number - 1);
833
+ block = await this.getBlock(BlockNumber(block.number - 1));
750
834
  }
751
835
  return blocks.reverse();
752
836
  }
@@ -757,19 +841,20 @@ import { validateBlockAttestations } from './validation.js';
757
841
  // We'll typically ask for blocks for a very recent epoch, so we shouldn't need an index here.
758
842
  let number = await this.store.getSynchedL2BlockNumber();
759
843
  let header = await this.getBlockHeader(number);
760
- const slot = (b)=>b.globalVariables.slotNumber.toBigInt();
844
+ const slot = (b)=>b.globalVariables.slotNumber;
761
845
  while(header && slot(header) >= start){
762
846
  if (slot(header) <= end) {
763
847
  blocks.push(header);
764
848
  }
765
- header = await this.getBlockHeader(--number);
849
+ number = BlockNumber(number - 1);
850
+ header = await this.getBlockHeader(number);
766
851
  }
767
852
  return blocks.reverse();
768
853
  }
769
854
  async isEpochComplete(epochNumber) {
770
855
  // The epoch is complete if the current L2 block is the last one in the epoch (or later)
771
856
  const header = await this.getBlockHeader('latest');
772
- const slot = header?.globalVariables.slotNumber.toBigInt();
857
+ const slot = header ? header.globalVariables.slotNumber : undefined;
773
858
  const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1constants);
774
859
  if (slot && slot >= endSlot) {
775
860
  return true;
@@ -793,6 +878,78 @@ import { validateBlockAttestations } from './validation.js';
793
878
  /** Returns whether the archiver has completed an initial sync run successfully. */ isInitialSyncComplete() {
794
879
  return this.initialSyncComplete;
795
880
  }
881
+ async getPublishedCheckpoints(from, limit, proven) {
882
+ // TODO: Implement this properly. This only works when we have one block per checkpoint.
883
+ const blocks = await this.getPublishedBlocks(BlockNumber(from), limit, proven);
884
+ return blocks.map((b)=>b.toPublishedCheckpoint());
885
+ }
886
+ async getCheckpointByArchive(archive) {
887
+ // TODO: Implement this properly. This only works when we have one block per checkpoint.
888
+ return (await this.getPublishedBlockByArchive(archive))?.block.toCheckpoint();
889
+ }
890
+ async getCheckpoints(from, limit, proven) {
891
+ const published = await this.getPublishedCheckpoints(from, limit, proven);
892
+ return published.map((p)=>p.checkpoint);
893
+ }
894
+ async getCheckpoint(number) {
895
+ if (number < 0) {
896
+ number = await this.getSynchedCheckpointNumber();
897
+ }
898
+ if (number === 0) {
899
+ return undefined;
900
+ }
901
+ const published = await this.getPublishedCheckpoints(number, 1);
902
+ return published[0]?.checkpoint;
903
+ }
904
+ async getCheckpointHeader(number) {
905
+ if (number === 'latest') {
906
+ number = await this.getSynchedCheckpointNumber();
907
+ }
908
+ if (number === 0) {
909
+ return undefined;
910
+ }
911
+ const checkpoint = await this.getCheckpoint(number);
912
+ return checkpoint?.header;
913
+ }
914
+ getCheckpointNumber() {
915
+ return this.getSynchedCheckpointNumber();
916
+ }
917
+ async getSynchedCheckpointNumber() {
918
+ // TODO: Create store and apis for checkpoints.
919
+ // Checkpoint number will no longer be the same as the block number once we support multiple blocks per checkpoint.
920
+ return CheckpointNumber(await this.store.getSynchedL2BlockNumber());
921
+ }
922
+ async getProvenCheckpointNumber() {
923
+ // TODO: Create store and apis for checkpoints.
924
+ // Proven checkpoint number will no longer be the same as the proven block number once we support multiple blocks per checkpoint.
925
+ return CheckpointNumber(await this.store.getProvenL2BlockNumber());
926
+ }
927
+ setProvenCheckpointNumber(checkpointNumber) {
928
+ // TODO: Create store and apis for checkpoints.
929
+ // Proven checkpoint number will no longer be the same as the proven block number once we support multiple blocks per checkpoint.
930
+ return this.store.setProvenL2BlockNumber(BlockNumber.fromCheckpointNumber(checkpointNumber));
931
+ }
932
+ unwindCheckpoints(from, checkpointsToUnwind) {
933
+ // TODO: Create store and apis for checkpoints.
934
+ // This only works when we have one block per checkpoint.
935
+ return this.store.unwindBlocks(BlockNumber.fromCheckpointNumber(from), checkpointsToUnwind);
936
+ }
937
+ getLastBlockNumberInCheckpoint(checkpointNumber) {
938
+ // TODO: Create store and apis for checkpoints.
939
+ // Checkpoint number will no longer be the same as the block number once we support multiple blocks per checkpoint.
940
+ return Promise.resolve(BlockNumber.fromCheckpointNumber(checkpointNumber));
941
+ }
942
+ addCheckpoints(checkpoints, pendingChainValidationStatus) {
943
+ // TODO: Create store and apis for checkpoints.
944
+ // This only works when we have one block per checkpoint.
945
+ return this.store.addBlocks(checkpoints.map((p)=>PublishedL2Block.fromPublishedCheckpoint(p)), pendingChainValidationStatus);
946
+ }
947
+ async getCheckpointsForEpoch(epochNumber) {
948
+ // TODO: Create store and apis for checkpoints.
949
+ // This only works when we have one block per checkpoint.
950
+ const blocks = await this.getBlocksForEpoch(epochNumber);
951
+ return blocks.map((b)=>b.toCheckpoint());
952
+ }
796
953
  /**
797
954
  * Gets up to `limit` amount of L2 blocks starting from `from`.
798
955
  * @param from - Number of the first block to return (inclusive).
@@ -806,6 +963,18 @@ import { validateBlockAttestations } from './validation.js';
806
963
  const limitWithProven = proven ? Math.min(limit, Math.max(await this.store.getProvenL2BlockNumber() - from + 1, 0)) : limit;
807
964
  return limitWithProven === 0 ? [] : await this.store.getPublishedBlocks(from, limitWithProven);
808
965
  }
966
+ getPublishedBlockByHash(blockHash) {
967
+ return this.store.getPublishedBlockByHash(blockHash);
968
+ }
969
+ getPublishedBlockByArchive(archive) {
970
+ return this.store.getPublishedBlockByArchive(archive);
971
+ }
972
+ getBlockHeaderByHash(blockHash) {
973
+ return this.store.getBlockHeaderByHash(blockHash);
974
+ }
975
+ getBlockHeaderByArchive(archive) {
976
+ return this.store.getBlockHeaderByArchive(archive);
977
+ }
809
978
  /**
810
979
  * Gets an l2 block.
811
980
  * @param number - The block number to return.
@@ -838,14 +1007,6 @@ import { validateBlockAttestations } from './validation.js';
838
1007
  return this.store.getSettledTxReceipt(txHash);
839
1008
  }
840
1009
  /**
841
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
842
- * @param from - The block number from which to begin retrieving logs.
843
- * @param limit - The maximum number of blocks to retrieve logs from.
844
- * @returns An array of private logs from the specified range of blocks.
845
- */ getPrivateLogs(from, limit) {
846
- return this.store.getPrivateLogs(from, limit);
847
- }
848
- /**
849
1010
  * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
850
1011
  * @param tags - The tags to filter the logs by.
851
1012
  * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
@@ -897,11 +1058,11 @@ import { validateBlockAttestations } from './validation.js';
897
1058
  return this.store.getContractInstance(address, timestamp);
898
1059
  }
899
1060
  /**
900
- * Gets L1 to L2 message (to be) included in a given block.
901
- * @param blockNumber - L2 block number to get messages for.
1061
+ * Gets L1 to L2 message (to be) included in a given checkpoint.
1062
+ * @param checkpointNumber - Checkpoint number to get messages for.
902
1063
  * @returns The L1 to L2 messages/leaves of the messages subtree (throws if not found).
903
- */ getL1ToL2Messages(blockNumber) {
904
- return this.store.getL1ToL2Messages(blockNumber);
1064
+ */ getL1ToL2Messages(checkpointNumber) {
1065
+ return this.store.getL1ToL2Messages(checkpointNumber);
905
1066
  }
906
1067
  /**
907
1068
  * Gets the L1 to L2 message index in the L1 to L2 message tree.
@@ -919,11 +1080,13 @@ import { validateBlockAttestations } from './validation.js';
919
1080
  getDebugFunctionName(address, selector) {
920
1081
  return this.store.getDebugFunctionName(address, selector);
921
1082
  }
922
- getPendingChainValidationStatus() {
923
- return Promise.resolve(this.pendingChainValidationStatus);
1083
+ async getPendingChainValidationStatus() {
1084
+ return await this.store.getPendingChainValidationStatus() ?? {
1085
+ valid: true
1086
+ };
924
1087
  }
925
1088
  isPendingChainInvalid() {
926
- return Promise.resolve(this.pendingChainValidationStatus.valid === false);
1089
+ return this.getPendingChainValidationStatus().then((status)=>!status.valid);
927
1090
  }
928
1091
  async getL2Tips() {
929
1092
  const [latestBlockNumber, provenBlockNumber] = await Promise.all([
@@ -933,7 +1096,7 @@ import { validateBlockAttestations } from './validation.js';
933
1096
  // TODO(#13569): Compute proper finalized block number based on L1 finalized block.
934
1097
  // We just force it 2 epochs worth of proven data for now.
935
1098
  // NOTE: update end-to-end/src/e2e_epochs/epochs_empty_blocks.test.ts as that uses finalized blocks in computations
936
- const finalizedBlockNumber = Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0);
1099
+ const finalizedBlockNumber = BlockNumber(Math.max(provenBlockNumber - this.l1constants.epochDuration * 2, 0));
937
1100
  const [latestBlockHeader, provenBlockHeader, finalizedBlockHeader] = await Promise.all([
938
1101
  latestBlockNumber > 0 ? this.getBlockHeader(latestBlockNumber) : undefined,
939
1102
  provenBlockNumber > 0 ? this.getBlockHeader(provenBlockNumber) : undefined,
@@ -948,21 +1111,21 @@ import { validateBlockAttestations } from './validation.js';
948
1111
  if (finalizedBlockNumber > 0 && !finalizedBlockHeader) {
949
1112
  throw new Error(`Failed to retrieve finalized block header for block ${finalizedBlockNumber} (latest block is ${latestBlockNumber})`);
950
1113
  }
951
- const latestBlockHeaderHash = await latestBlockHeader?.hash();
952
- const provenBlockHeaderHash = await provenBlockHeader?.hash();
953
- const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash();
1114
+ const latestBlockHeaderHash = await latestBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1115
+ const provenBlockHeaderHash = await provenBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
1116
+ const finalizedBlockHeaderHash = await finalizedBlockHeader?.hash() ?? GENESIS_BLOCK_HEADER_HASH;
954
1117
  return {
955
1118
  latest: {
956
1119
  number: latestBlockNumber,
957
- hash: latestBlockHeaderHash?.toString()
1120
+ hash: latestBlockHeaderHash.toString()
958
1121
  },
959
1122
  proven: {
960
1123
  number: provenBlockNumber,
961
- hash: provenBlockHeaderHash?.toString()
1124
+ hash: provenBlockHeaderHash.toString()
962
1125
  },
963
1126
  finalized: {
964
1127
  number: finalizedBlockNumber,
965
- hash: finalizedBlockHeaderHash?.toString()
1128
+ hash: finalizedBlockHeaderHash.toString()
966
1129
  }
967
1130
  };
968
1131
  }
@@ -980,11 +1143,12 @@ import { validateBlockAttestations } from './validation.js';
980
1143
  throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
981
1144
  }
982
1145
  const targetL1BlockNumber = targetL2Block.l1.blockNumber;
1146
+ const targetCheckpointNumber = CheckpointNumber.fromBlockNumber(targetL2BlockNumber);
983
1147
  const targetL1BlockHash = await this.getL1BlockHash(targetL1BlockNumber);
984
1148
  this.log.info(`Unwinding ${blocksToUnwind} blocks from L2 block ${currentL2Block}`);
985
- await this.store.unwindBlocks(currentL2Block, blocksToUnwind);
986
- this.log.info(`Unwinding L1 to L2 messages to ${targetL2BlockNumber}`);
987
- await this.store.rollbackL1ToL2MessagesToL2Block(targetL2BlockNumber);
1149
+ await this.store.unwindBlocks(BlockNumber(currentL2Block), blocksToUnwind);
1150
+ this.log.info(`Unwinding L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
1151
+ await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
988
1152
  this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
989
1153
  await this.store.setBlockSynchedL1BlockNumber(targetL1BlockNumber);
990
1154
  await this.store.setMessageSynchedL1Block({
@@ -993,7 +1157,7 @@ import { validateBlockAttestations } from './validation.js';
993
1157
  });
994
1158
  if (targetL2BlockNumber < currentProvenBlock) {
995
1159
  this.log.info(`Clearing proven L2 block number`);
996
- await this.store.setProvenL2BlockNumber(0);
1160
+ await this.store.setProvenL2BlockNumber(BlockNumber.ZERO);
997
1161
  }
998
1162
  // TODO(palla/reorg): Set the finalized block when we add support for it.
999
1163
  // if (targetL2BlockNumber < currentFinalizedBlock) {
@@ -1003,9 +1167,7 @@ import { validateBlockAttestations } from './validation.js';
1003
1167
  }
1004
1168
  }
1005
1169
  _ts_decorate([
1006
- trackSpan('Archiver.sync', (initialRun)=>({
1007
- [Attributes.INITIAL_SYNC]: initialRun
1008
- }))
1170
+ trackSpan('Archiver.sync')
1009
1171
  ], Archiver.prototype, "sync", null);
1010
1172
  var Operation = /*#__PURE__*/ function(Operation) {
1011
1173
  Operation[Operation["Store"] = 0] = "Store";
@@ -1124,12 +1286,15 @@ var Operation = /*#__PURE__*/ function(Operation) {
1124
1286
  }
1125
1287
  return true;
1126
1288
  }
1127
- addBlocks(blocks) {
1289
+ addBlocks(blocks, pendingChainValidationStatus) {
1128
1290
  // Add the blocks to the store. Store will throw if the blocks are not in order, there are gaps,
1129
1291
  // or if the previous block is not in the store.
1130
1292
  return this.store.transactionAsync(async ()=>{
1131
1293
  await this.store.addBlocks(blocks);
1132
1294
  const opResults = await Promise.all([
1295
+ // Update the pending chain validation status if provided
1296
+ pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
1297
+ // Add any logs emitted during the retrieved blocks
1133
1298
  this.store.addLogs(blocks.map((block)=>block.block)),
1134
1299
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1135
1300
  ...blocks.map(async (block)=>{
@@ -1157,8 +1322,12 @@ var Operation = /*#__PURE__*/ function(Operation) {
1157
1322
  throw new Error(`Cannot unwind ${blocksToUnwind} blocks`);
1158
1323
  }
1159
1324
  // from - blocksToUnwind = the new head, so + 1 for what we need to remove
1160
- const blocks = await this.getPublishedBlocks(from - blocksToUnwind + 1, blocksToUnwind);
1325
+ const blocks = await this.getPublishedBlocks(BlockNumber(from - blocksToUnwind + 1), blocksToUnwind);
1161
1326
  const opResults = await Promise.all([
1327
+ // Prune rolls back to the last proven block, which is by definition valid
1328
+ this.store.setPendingChainValidationStatus({
1329
+ valid: true
1330
+ }),
1162
1331
  // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
1163
1332
  ...blocks.map(async (block)=>{
1164
1333
  const contractClassLogs = block.block.body.txEffects.flatMap((txEffect)=>txEffect.contractClassLogs);
@@ -1182,9 +1351,21 @@ var Operation = /*#__PURE__*/ function(Operation) {
1182
1351
  getPublishedBlock(number) {
1183
1352
  return this.store.getPublishedBlock(number);
1184
1353
  }
1354
+ getPublishedBlockByHash(blockHash) {
1355
+ return this.store.getPublishedBlockByHash(blockHash);
1356
+ }
1357
+ getPublishedBlockByArchive(archive) {
1358
+ return this.store.getPublishedBlockByArchive(archive);
1359
+ }
1185
1360
  getBlockHeaders(from, limit) {
1186
1361
  return this.store.getBlockHeaders(from, limit);
1187
1362
  }
1363
+ getBlockHeaderByHash(blockHash) {
1364
+ return this.store.getBlockHeaderByHash(blockHash);
1365
+ }
1366
+ getBlockHeaderByArchive(archive) {
1367
+ return this.store.getBlockHeaderByArchive(archive);
1368
+ }
1188
1369
  getTxEffect(txHash) {
1189
1370
  return this.store.getTxEffect(txHash);
1190
1371
  }
@@ -1194,15 +1375,12 @@ var Operation = /*#__PURE__*/ function(Operation) {
1194
1375
  addL1ToL2Messages(messages) {
1195
1376
  return this.store.addL1ToL2Messages(messages);
1196
1377
  }
1197
- getL1ToL2Messages(blockNumber) {
1198
- return this.store.getL1ToL2Messages(blockNumber);
1378
+ getL1ToL2Messages(checkpointNumber) {
1379
+ return this.store.getL1ToL2Messages(checkpointNumber);
1199
1380
  }
1200
1381
  getL1ToL2MessageIndex(l1ToL2Message) {
1201
1382
  return this.store.getL1ToL2MessageIndex(l1ToL2Message);
1202
1383
  }
1203
- getPrivateLogs(from, limit) {
1204
- return this.store.getPrivateLogs(from, limit);
1205
- }
1206
1384
  getLogsByTags(tags, logsPerTag) {
1207
1385
  return this.store.getLogsByTags(tags, logsPerTag);
1208
1386
  }
@@ -1254,8 +1432,8 @@ var Operation = /*#__PURE__*/ function(Operation) {
1254
1432
  estimateSize() {
1255
1433
  return this.store.estimateSize();
1256
1434
  }
1257
- rollbackL1ToL2MessagesToL2Block(targetBlockNumber) {
1258
- return this.store.rollbackL1ToL2MessagesToL2Block(targetBlockNumber);
1435
+ rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber) {
1436
+ return this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
1259
1437
  }
1260
1438
  iterateL1ToL2Messages(range = {}) {
1261
1439
  return this.store.iterateL1ToL2Messages(range);
@@ -1266,4 +1444,11 @@ var Operation = /*#__PURE__*/ function(Operation) {
1266
1444
  getLastL1ToL2Message() {
1267
1445
  return this.store.getLastL1ToL2Message();
1268
1446
  }
1447
+ getPendingChainValidationStatus() {
1448
+ return this.store.getPendingChainValidationStatus();
1449
+ }
1450
+ setPendingChainValidationStatus(status) {
1451
+ this.#log.debug(`Setting pending chain validation status to valid ${status?.valid}`, status);
1452
+ return this.store.setPendingChainValidationStatus(status);
1453
+ }
1269
1454
  }