@aztec/archiver 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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 (232) hide show
  1. package/README.md +164 -22
  2. package/dest/archiver.d.ts +158 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +881 -0
  5. package/dest/config.d.ts +33 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +31 -14
  8. package/dest/errors.d.ts +87 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +129 -0
  11. package/dest/factory.d.ts +16 -10
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +112 -20
  14. package/dest/index.d.ts +19 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +17 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.d.ts +1 -1
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/{archiver/l1 → l1}/bin/retrieve-calldata.js +35 -32
  23. package/dest/l1/calldata_retriever.d.ts +136 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +412 -0
  26. package/dest/l1/data_retrieval.d.ts +97 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver/l1 → l1}/data_retrieval.js +65 -89
  29. package/dest/{archiver/l1 → l1}/debug_tx.d.ts +1 -1
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/{archiver/l1 → l1}/spire_proposer.d.ts +5 -5
  32. package/dest/l1/spire_proposer.d.ts.map +1 -0
  33. package/dest/{archiver/l1 → l1}/spire_proposer.js +9 -17
  34. package/dest/l1/trace_tx.d.ts +43 -0
  35. package/dest/l1/trace_tx.d.ts.map +1 -0
  36. package/dest/l1/types.d.ts +12 -0
  37. package/dest/l1/types.d.ts.map +1 -0
  38. package/dest/l1/validate_historical_logs.d.ts +23 -0
  39. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  40. package/dest/l1/validate_historical_logs.js +108 -0
  41. package/dest/{archiver/l1 → l1}/validate_trace.d.ts +6 -3
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/{archiver/l1 → l1}/validate_trace.js +13 -9
  44. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  45. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  46. package/dest/modules/contract_data_source_adapter.js +40 -0
  47. package/dest/modules/data_source_base.d.ts +113 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +351 -0
  50. package/dest/modules/data_store_updater.d.ts +105 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +392 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/{archiver → modules}/instrumentation.js +61 -19
  56. package/dest/modules/l1_synchronizer.d.ts +77 -0
  57. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  58. package/dest/modules/l1_synchronizer.js +1344 -0
  59. package/dest/modules/validation.d.ts +18 -0
  60. package/dest/modules/validation.d.ts.map +1 -0
  61. package/dest/{archiver → modules}/validation.js +12 -6
  62. package/dest/store/block_store.d.ts +300 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1219 -0
  65. package/dest/store/contract_class_store.d.ts +31 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +80 -0
  68. package/dest/store/contract_instance_store.d.ts +51 -0
  69. package/dest/store/contract_instance_store.d.ts.map +1 -0
  70. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +38 -3
  71. package/dest/store/data_stores.d.ts +68 -0
  72. package/dest/store/data_stores.d.ts.map +1 -0
  73. package/dest/store/data_stores.js +54 -0
  74. package/dest/store/function_names_cache.d.ts +17 -0
  75. package/dest/store/function_names_cache.d.ts.map +1 -0
  76. package/dest/store/function_names_cache.js +30 -0
  77. package/dest/store/l2_tips_cache.d.ts +25 -0
  78. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  79. package/dest/store/l2_tips_cache.js +26 -0
  80. package/dest/store/log_store.d.ts +59 -0
  81. package/dest/store/log_store.d.ts.map +1 -0
  82. package/dest/store/log_store.js +310 -0
  83. package/dest/store/log_store_codec.d.ts +70 -0
  84. package/dest/store/log_store_codec.d.ts.map +1 -0
  85. package/dest/store/log_store_codec.js +101 -0
  86. package/dest/store/message_store.d.ts +50 -0
  87. package/dest/store/message_store.d.ts.map +1 -0
  88. package/dest/{archiver/kv_archiver_store → store}/message_store.js +51 -9
  89. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  90. package/dest/structs/data_retrieval.d.ts.map +1 -0
  91. package/dest/structs/inbox_message.d.ts +15 -0
  92. package/dest/structs/inbox_message.d.ts.map +1 -0
  93. package/dest/{archiver/structs → structs}/published.d.ts +1 -1
  94. package/dest/structs/published.d.ts.map +1 -0
  95. package/dest/test/fake_l1_state.d.ts +214 -0
  96. package/dest/test/fake_l1_state.d.ts.map +1 -0
  97. package/dest/test/fake_l1_state.js +517 -0
  98. package/dest/test/index.d.ts +2 -1
  99. package/dest/test/index.d.ts.map +1 -1
  100. package/dest/test/index.js +4 -1
  101. package/dest/test/mock_archiver.d.ts +2 -2
  102. package/dest/test/mock_archiver.d.ts.map +1 -1
  103. package/dest/test/mock_archiver.js +3 -3
  104. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  105. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  106. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  107. package/dest/test/mock_l2_block_source.d.ts +65 -41
  108. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  109. package/dest/test/mock_l2_block_source.js +330 -151
  110. package/dest/test/mock_structs.d.ts +81 -3
  111. package/dest/test/mock_structs.d.ts.map +1 -1
  112. package/dest/test/mock_structs.js +152 -7
  113. package/dest/test/noop_l1_archiver.d.ts +29 -0
  114. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  115. package/dest/test/noop_l1_archiver.js +85 -0
  116. package/package.json +17 -18
  117. package/src/archiver.ts +681 -0
  118. package/src/{archiver/config.ts → config.ts} +43 -12
  119. package/src/errors.ts +203 -0
  120. package/src/factory.ts +175 -22
  121. package/src/index.ts +27 -3
  122. package/src/interfaces.ts +9 -0
  123. package/src/l1/README.md +55 -0
  124. package/src/{archiver/l1 → l1}/bin/retrieve-calldata.ts +45 -33
  125. package/src/l1/calldata_retriever.ts +522 -0
  126. package/src/{archiver/l1 → l1}/data_retrieval.ts +106 -134
  127. package/src/{archiver/l1 → l1}/spire_proposer.ts +7 -15
  128. package/src/l1/validate_historical_logs.ts +140 -0
  129. package/src/{archiver/l1 → l1}/validate_trace.ts +24 -6
  130. package/src/modules/contract_data_source_adapter.ts +55 -0
  131. package/src/modules/data_source_base.ts +493 -0
  132. package/src/modules/data_store_updater.ts +518 -0
  133. package/src/{archiver → modules}/instrumentation.ts +72 -20
  134. package/src/modules/l1_synchronizer.ts +1257 -0
  135. package/src/{archiver → modules}/validation.ts +15 -9
  136. package/src/store/block_store.ts +1590 -0
  137. package/src/store/contract_class_store.ts +108 -0
  138. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +52 -6
  139. package/src/store/data_stores.ts +104 -0
  140. package/src/store/function_names_cache.ts +37 -0
  141. package/src/store/l2_tips_cache.ts +35 -0
  142. package/src/store/log_store.ts +379 -0
  143. package/src/store/log_store_codec.ts +132 -0
  144. package/src/{archiver/kv_archiver_store → store}/message_store.ts +60 -10
  145. package/src/{archiver/structs → structs}/inbox_message.ts +1 -1
  146. package/src/test/fake_l1_state.ts +770 -0
  147. package/src/test/index.ts +4 -0
  148. package/src/test/mock_archiver.ts +4 -3
  149. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  150. package/src/test/mock_l2_block_source.ts +403 -171
  151. package/src/test/mock_structs.ts +283 -8
  152. package/src/test/noop_l1_archiver.ts +139 -0
  153. package/dest/archiver/archiver.d.ts +0 -307
  154. package/dest/archiver/archiver.d.ts.map +0 -1
  155. package/dest/archiver/archiver.js +0 -2102
  156. package/dest/archiver/archiver_store.d.ts +0 -315
  157. package/dest/archiver/archiver_store.d.ts.map +0 -1
  158. package/dest/archiver/archiver_store.js +0 -4
  159. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  160. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  162. package/dest/archiver/config.d.ts +0 -22
  163. package/dest/archiver/config.d.ts.map +0 -1
  164. package/dest/archiver/errors.d.ts +0 -36
  165. package/dest/archiver/errors.d.ts.map +0 -1
  166. package/dest/archiver/errors.js +0 -54
  167. package/dest/archiver/index.d.ts +0 -7
  168. package/dest/archiver/index.d.ts.map +0 -1
  169. package/dest/archiver/index.js +0 -4
  170. package/dest/archiver/instrumentation.d.ts +0 -37
  171. package/dest/archiver/instrumentation.d.ts.map +0 -1
  172. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -164
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  174. package/dest/archiver/kv_archiver_store/block_store.js +0 -626
  175. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  177. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  178. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  180. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -159
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -316
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -45
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  185. package/dest/archiver/kv_archiver_store/log_store.js +0 -401
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -40
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +0 -1
  189. package/dest/archiver/l1/calldata_retriever.d.ts +0 -112
  190. package/dest/archiver/l1/calldata_retriever.d.ts.map +0 -1
  191. package/dest/archiver/l1/calldata_retriever.js +0 -471
  192. package/dest/archiver/l1/data_retrieval.d.ts +0 -90
  193. package/dest/archiver/l1/data_retrieval.d.ts.map +0 -1
  194. package/dest/archiver/l1/debug_tx.d.ts.map +0 -1
  195. package/dest/archiver/l1/spire_proposer.d.ts.map +0 -1
  196. package/dest/archiver/l1/trace_tx.d.ts +0 -97
  197. package/dest/archiver/l1/trace_tx.d.ts.map +0 -1
  198. package/dest/archiver/l1/types.d.ts +0 -12
  199. package/dest/archiver/l1/types.d.ts.map +0 -1
  200. package/dest/archiver/l1/validate_trace.d.ts.map +0 -1
  201. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  202. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  203. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  204. package/dest/archiver/structs/published.d.ts.map +0 -1
  205. package/dest/archiver/validation.d.ts +0 -17
  206. package/dest/archiver/validation.d.ts.map +0 -1
  207. package/dest/rpc/index.d.ts +0 -9
  208. package/dest/rpc/index.d.ts.map +0 -1
  209. package/dest/rpc/index.js +0 -15
  210. package/src/archiver/archiver.ts +0 -2265
  211. package/src/archiver/archiver_store.ts +0 -380
  212. package/src/archiver/archiver_store_test_suite.ts +0 -2842
  213. package/src/archiver/errors.ts +0 -90
  214. package/src/archiver/index.ts +0 -6
  215. package/src/archiver/kv_archiver_store/block_store.ts +0 -850
  216. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  217. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -442
  218. package/src/archiver/kv_archiver_store/log_store.ts +0 -516
  219. package/src/archiver/l1/README.md +0 -98
  220. package/src/archiver/l1/calldata_retriever.ts +0 -641
  221. package/src/rpc/index.ts +0 -16
  222. /package/dest/{archiver/l1 → l1}/debug_tx.js +0 -0
  223. /package/dest/{archiver/l1 → l1}/trace_tx.js +0 -0
  224. /package/dest/{archiver/l1 → l1}/types.js +0 -0
  225. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  226. /package/dest/{archiver/structs → structs}/inbox_message.js +0 -0
  227. /package/dest/{archiver/structs → structs}/published.js +0 -0
  228. /package/src/{archiver/l1 → l1}/debug_tx.ts +0 -0
  229. /package/src/{archiver/l1 → l1}/trace_tx.ts +0 -0
  230. /package/src/{archiver/l1 → l1}/types.ts +0 -0
  231. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
  232. /package/src/{archiver/structs → structs}/published.ts +0 -0
@@ -0,0 +1,1257 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { EpochCache } from '@aztec/epoch-cache';
3
+ import { InboxContract, type InboxContractState, RollupContract } from '@aztec/ethereum/contracts';
4
+ import type { L1BlockId } from '@aztec/ethereum/l1-types';
5
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
6
+ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
7
+ import { asyncPool } from '@aztec/foundation/async-pool';
8
+ import { maxBigint } from '@aztec/foundation/bigint';
9
+ import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
10
+ import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
11
+ import { compactArray, partition, pick } from '@aztec/foundation/collection';
12
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
+ import { EthAddress } from '@aztec/foundation/eth-address';
14
+ import { type Logger, createLogger } from '@aztec/foundation/log';
15
+ import { retryTimes } from '@aztec/foundation/retry';
16
+ import { count } from '@aztec/foundation/string';
17
+ import { DateProvider, Timer, elapsed } from '@aztec/foundation/timer';
18
+ import { isDefined, isErrorClass } from '@aztec/foundation/types';
19
+ import { type ArchiverEmitter, L2BlockSourceEvents, type ValidateCheckpointResult } from '@aztec/stdlib/block';
20
+ import { Checkpoint, type CheckpointData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
21
+ import { type L1RollupConstants, getEpochAtSlot, getSlotAtNextL1Block } from '@aztec/stdlib/epoch-helpers';
22
+ import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
23
+ import type { CoordinationSignatureContext } from '@aztec/stdlib/p2p';
24
+ import { type Traceable, type Tracer, execInSpan, trackSpan } from '@aztec/telemetry-client';
25
+
26
+ import { InitialCheckpointNumberNotSequentialError } from '../errors.js';
27
+ import {
28
+ type RetrievedCheckpointFromCalldata,
29
+ getCheckpointBlobDataFromBlobs,
30
+ retrieveCheckpointCalldataFromRollup,
31
+ retrieveL1ToL2Message,
32
+ retrieveL1ToL2Messages,
33
+ retrievedToPublishedCheckpoint,
34
+ } from '../l1/data_retrieval.js';
35
+ import type { RejectedCheckpoint } from '../store/block_store.js';
36
+ import { type ArchiverDataStores, getArchiverSynchPoint } from '../store/data_stores.js';
37
+ import type { L2TipsCache } from '../store/l2_tips_cache.js';
38
+ import { MessageStoreError } from '../store/message_store.js';
39
+ import type { InboxMessage } from '../structs/inbox_message.js';
40
+ import { ArchiverDataStoreUpdater } from './data_store_updater.js';
41
+ import type { ArchiverInstrumentation } from './instrumentation.js';
42
+ import { validateCheckpointAttestations } from './validation.js';
43
+
44
+ type RollupStatus = {
45
+ provenCheckpointNumber: CheckpointNumber;
46
+ provenArchive: string;
47
+ pendingCheckpointNumber: CheckpointNumber;
48
+ pendingArchive: string;
49
+ validationResult: ValidateCheckpointResult | undefined;
50
+ /** Last valid checkpoint observed on L1 and synced on this iteration */
51
+ lastRetrievedCheckpoint?: PublishedCheckpoint;
52
+ /** Last checkpoint observed on L1 across both valid and rejected entries on this iteration */
53
+ lastSeenCheckpoint?: PublishedCheckpoint;
54
+ };
55
+
56
+ /**
57
+ * Handles L1 synchronization for the archiver.
58
+ * Responsible for fetching checkpoints, L1 to L2 messages, and handling L1 reorgs.
59
+ */
60
+ export class ArchiverL1Synchronizer implements Traceable {
61
+ private l1BlockNumber: bigint | undefined;
62
+ private l1BlockHash: Buffer32 | undefined;
63
+ private l1Timestamp: bigint | undefined;
64
+
65
+ private readonly updater: ArchiverDataStoreUpdater;
66
+ public readonly tracer: Tracer;
67
+
68
+ constructor(
69
+ private readonly publicClient: ViemPublicClient,
70
+ private readonly debugClient: ViemPublicDebugClient,
71
+ private readonly rollup: RollupContract,
72
+ private readonly inbox: InboxContract,
73
+ private readonly stores: ArchiverDataStores,
74
+ private config: {
75
+ batchSize: number;
76
+ skipValidateCheckpointAttestations?: boolean;
77
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
78
+ maxAllowedEthClientDriftSeconds: number;
79
+ },
80
+ private readonly blobClient: BlobClientInterface,
81
+ private readonly epochCache: EpochCache,
82
+ private readonly dateProvider: DateProvider,
83
+ private readonly instrumentation: ArchiverInstrumentation,
84
+ private readonly l1Constants: L1RollupConstants & {
85
+ l1StartBlockHash: Buffer32;
86
+ genesisArchiveRoot: Fr;
87
+ },
88
+ private readonly events: ArchiverEmitter,
89
+ tracer: Tracer,
90
+ l2TipsCache?: L2TipsCache,
91
+ private readonly log: Logger = createLogger('archiver:l1-sync'),
92
+ ) {
93
+ this.updater = new ArchiverDataStoreUpdater(this.stores, l2TipsCache, {
94
+ rollupManaLimit: l1Constants.rollupManaLimit,
95
+ });
96
+ this.tracer = tracer;
97
+ }
98
+
99
+ /** Sets new config */
100
+ public setConfig(newConfig: {
101
+ batchSize: number;
102
+ skipValidateCheckpointAttestations?: boolean;
103
+ skipPromoteProposedCheckpointDuringL1Sync?: boolean;
104
+ maxAllowedEthClientDriftSeconds: number;
105
+ }) {
106
+ this.config = newConfig;
107
+ }
108
+
109
+ /** Returns the last L1 block number that was synced. */
110
+ public getL1BlockNumber(): bigint | undefined {
111
+ return this.l1BlockNumber;
112
+ }
113
+
114
+ /** Returns the last L1 timestamp that was synced. */
115
+ public getL1Timestamp(): bigint | undefined {
116
+ return this.l1Timestamp;
117
+ }
118
+
119
+ private getSignatureContext(): CoordinationSignatureContext {
120
+ return {
121
+ chainId: this.publicClient.chain.id,
122
+ rollupAddress: EthAddress.fromString(this.rollup.address),
123
+ };
124
+ }
125
+
126
+ /** Checks that the ethereum node we are connected to has a latest timestamp no more than the allowed drift. Throw if not. */
127
+ public async testEthereumNodeSynced(): Promise<void> {
128
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
129
+ if (maxAllowedDelay === 0) {
130
+ return;
131
+ }
132
+ const { number, timestamp: l1Timestamp } = await this.publicClient.getBlock({ includeTransactions: false });
133
+ const currentTime = BigInt(this.dateProvider.nowInSeconds());
134
+ if (currentTime - l1Timestamp > BigInt(maxAllowedDelay)) {
135
+ throw new Error(
136
+ `Ethereum node is out of sync (last block synced ${number} at ${l1Timestamp} vs current time ${currentTime})`,
137
+ );
138
+ }
139
+ }
140
+
141
+ @trackSpan('Archiver.syncFromL1')
142
+ public async syncFromL1(initialSyncComplete: boolean): Promise<void> {
143
+ // In between the various calls to L1, the block number can move meaning some of the following
144
+ // calls will return data for blocks that were not present during earlier calls. To combat this
145
+ // we ensure that all data retrieval methods only retrieve data up to the currentBlockNumber
146
+ // captured at the top of this function.
147
+ const currentL1Block = await this.publicClient.getBlock({ includeTransactions: false });
148
+ const currentL1BlockNumber = currentL1Block.number;
149
+ const currentL1BlockHash = Buffer32.fromString(currentL1Block.hash);
150
+ const currentL1Timestamp = currentL1Block.timestamp;
151
+ const currentL1BlockData = { l1BlockNumber: currentL1BlockNumber, l1BlockHash: currentL1BlockHash };
152
+
153
+ if (this.l1BlockHash && currentL1BlockHash.equals(this.l1BlockHash)) {
154
+ this.log.trace(`No new L1 blocks since last sync at L1 block ${this.l1BlockNumber}`);
155
+ return;
156
+ }
157
+
158
+ // Log at error if the latest L1 block timestamp is too old
159
+ const maxAllowedDelay = this.config.maxAllowedEthClientDriftSeconds;
160
+ const now = this.dateProvider.nowInSeconds();
161
+ if (maxAllowedDelay > 0 && Number(currentL1Timestamp) <= now - maxAllowedDelay) {
162
+ this.log.error(
163
+ `Latest L1 block ${currentL1BlockNumber} timestamp ${currentL1Timestamp} is too old. Make sure your Ethereum node is synced.`,
164
+ { currentL1BlockNumber, currentL1Timestamp, now, maxAllowedDelay },
165
+ );
166
+ }
167
+
168
+ // Query finalized block on L1
169
+ const rawFinalizedL1Block = await getFinalizedL1Block(this.publicClient);
170
+ const finalizedL1Block: L1BlockId | undefined = rawFinalizedL1Block && {
171
+ l1BlockNumber: rawFinalizedL1Block.number,
172
+ l1BlockHash: Buffer32.fromString(rawFinalizedL1Block.hash),
173
+ };
174
+
175
+ // Load sync point for blocks defaulting to start block
176
+ const { blocksSynchedTo = this.l1Constants.l1StartBlock } = await getArchiverSynchPoint(this.stores);
177
+ this.log.debug(`Starting new archiver sync iteration`, { blocksSynchedTo, currentL1BlockData, finalizedL1Block });
178
+
179
+ // Sync L1 to L2 messages. We retry this a few times since there are error conditions that reset the sync point, requiring a new iteration.
180
+ // Note that we cannot just wait for the l1 synchronizer to loop again, since the synchronizer would report as synced up to the current L1
181
+ // block, when that wouldn't be the case, since L1 to L2 messages would need another iteration.
182
+ await retryTimes(
183
+ () => this.handleL1ToL2Messages(currentL1BlockData, finalizedL1Block),
184
+ 'Handling L1 to L2 messages',
185
+ 3,
186
+ 0.1,
187
+ );
188
+
189
+ if (currentL1BlockNumber > blocksSynchedTo) {
190
+ // First we retrieve new checkpoints and L2 blocks and store them in the DB. This will also update the
191
+ // pending chain validation status, proven checkpoint number, and synched L1 block number.
192
+ const rollupStatus = await this.handleCheckpoints(blocksSynchedTo, currentL1BlockNumber, initialSyncComplete);
193
+
194
+ // Then we try pruning uncheckpointed blocks if a new slot was mined without checkpoints
195
+ await this.pruneUncheckpointedBlocks(currentL1Timestamp);
196
+
197
+ // Then we prune the current epoch if it'd reorg on next submission.
198
+ // Note that we don't do this before retrieving checkpoints because we may need to retrieve
199
+ // checkpoints from more than 2 epochs ago, so we want to make sure we have the latest view of
200
+ // the chain locally before we start unwinding stuff. This can be optimized by figuring out
201
+ // up to which point we're pruning, and then requesting checkpoints up to that point only.
202
+ const { rollupCanPrune } = await this.handleEpochPrune(
203
+ rollupStatus.provenCheckpointNumber,
204
+ currentL1BlockNumber,
205
+ currentL1Timestamp,
206
+ );
207
+
208
+ // And lastly we check if we are missing any checkpoints behind us due to a possible L1 reorg.
209
+ // We only do this if rollup cant prune on the next submission. Otherwise we will end up
210
+ // re-syncing the checkpoints we have just unwound above.
211
+ if (!rollupCanPrune) {
212
+ await this.checkForNewCheckpointsBeforeL1SyncPoint(rollupStatus, blocksSynchedTo, currentL1BlockNumber);
213
+ }
214
+
215
+ this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
216
+ }
217
+
218
+ // Update the finalized L2 checkpoint based on L1 finality.
219
+ await this.updateFinalizedCheckpoint(finalizedL1Block);
220
+
221
+ // After syncing has completed, update the current l1 block number and timestamp,
222
+ // otherwise we risk announcing to the world that we've synced to a given point,
223
+ // but the corresponding blocks have not been processed (see #12631).
224
+ this.l1Timestamp = currentL1Timestamp;
225
+ this.l1BlockNumber = currentL1BlockNumber;
226
+ this.l1BlockHash = currentL1BlockHash;
227
+
228
+ const l1BlockNumberAtEnd = await this.publicClient.getBlockNumber();
229
+ this.log.debug(`Archiver sync iteration complete`, {
230
+ l1BlockNumberAtStart: currentL1BlockNumber,
231
+ l1TimestampAtStart: currentL1Timestamp,
232
+ l1BlockNumberAtEnd,
233
+ });
234
+ }
235
+
236
+ /** Updates the finalized checkpoint using the pre-fetched finalized L1 block from the current sync iteration. */
237
+ private async updateFinalizedCheckpoint(finalizedL1Block: L1BlockId | undefined): Promise<void> {
238
+ try {
239
+ if (!finalizedL1Block) {
240
+ this.log.trace(`Skipping finalized checkpoint update: L1 has no finalized block yet.`);
241
+ return;
242
+ }
243
+ const finalizedL1BlockNumber = finalizedL1Block.l1BlockNumber;
244
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
245
+ blockNumber: finalizedL1BlockNumber,
246
+ });
247
+ const localFinalizedCheckpointNumber = await this.stores.blocks.getFinalizedCheckpointNumber();
248
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
249
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
250
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
251
+ finalizedCheckpointNumber,
252
+ finalizedL1BlockNumber,
253
+ });
254
+ }
255
+ } catch (err: any) {
256
+ // The rollup contract may not exist at the finalized L1 block right after deployment.
257
+ if (!err?.message?.includes('returned no data')) {
258
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
259
+ }
260
+ }
261
+ }
262
+
263
+ /** Prune all proposed local blocks that should have been checkpointed by now. */
264
+ private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
265
+ const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
266
+ this.stores.blocks.getCheckpointedL2BlockNumber(),
267
+ this.stores.blocks.getLatestL2BlockNumber(),
268
+ ]);
269
+
270
+ // If there are no uncheckpointed blocks, we got nothing to do
271
+ if (lastProposedBlockNumber === lastCheckpointedBlockNumber) {
272
+ this.log.trace(`No uncheckpointed blocks to prune.`);
273
+ return;
274
+ }
275
+
276
+ // What's the slot at the next L1 block? All blocks for slots strictly before this one should've been checkpointed by now.
277
+ const slotAtNextL1Block = getSlotAtNextL1Block(currentL1Timestamp, this.l1Constants);
278
+ const firstUncheckpointedBlockNumber = BlockNumber(lastCheckpointedBlockNumber + 1);
279
+
280
+ // What's the slot of the first uncheckpointed block?
281
+ const firstUncheckpointedBlockData = await this.stores.blocks.getBlockData({
282
+ number: firstUncheckpointedBlockNumber,
283
+ });
284
+ const firstUncheckpointedBlockSlot = firstUncheckpointedBlockData?.header.getSlot();
285
+
286
+ if (firstUncheckpointedBlockSlot === undefined || firstUncheckpointedBlockSlot >= slotAtNextL1Block) {
287
+ return;
288
+ }
289
+
290
+ // Prune provisional blocks from slots that have ended without being checkpointed.
291
+ // This also clears any proposed checkpoint whose blocks are being pruned.
292
+ this.log.warn(
293
+ `Pruning blocks after block ${lastCheckpointedBlockNumber} due to slot ${firstUncheckpointedBlockSlot} not being checkpointed`,
294
+ { firstUncheckpointedBlockHeader: firstUncheckpointedBlockData?.header.toInspect(), slotAtNextL1Block },
295
+ );
296
+
297
+ const prunedBlocks = await this.updater.removeUncheckpointedBlocksAfter(lastCheckpointedBlockNumber);
298
+ if (prunedBlocks.length > 0) {
299
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
300
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
301
+ slotNumber: firstUncheckpointedBlockSlot,
302
+ blocks: prunedBlocks,
303
+ });
304
+ }
305
+ }
306
+
307
+ /** Queries the rollup contract on whether a prune can be executed on the immediate next L1 block. */
308
+ private async canPrune(currentL1BlockNumber: bigint, currentL1Timestamp: bigint): Promise<boolean> {
309
+ const time = (currentL1Timestamp ?? 0n) + BigInt(this.l1Constants.ethereumSlotDuration);
310
+ const result = await this.rollup.canPruneAtTime(time, { blockNumber: currentL1BlockNumber });
311
+ if (result) {
312
+ this.log.debug(`Rollup contract allows pruning at L1 block ${currentL1BlockNumber} time ${time}`, {
313
+ currentL1Timestamp,
314
+ pruneTime: time,
315
+ currentL1BlockNumber,
316
+ });
317
+ }
318
+ return result;
319
+ }
320
+
321
+ /** Checks if there'd be a reorg for the next checkpoint submission and start pruning now. */
322
+ @trackSpan('Archiver.handleEpochPrune')
323
+ private async handleEpochPrune(
324
+ provenCheckpointNumber: CheckpointNumber,
325
+ currentL1BlockNumber: bigint,
326
+ currentL1Timestamp: bigint,
327
+ ): Promise<{ rollupCanPrune: boolean }> {
328
+ const rollupCanPrune = await this.canPrune(currentL1BlockNumber, currentL1Timestamp);
329
+ const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
330
+ const canPrune = localPendingCheckpointNumber > provenCheckpointNumber && rollupCanPrune;
331
+
332
+ if (canPrune) {
333
+ const timer = new Timer();
334
+ const pruneFrom = CheckpointNumber(provenCheckpointNumber + 1);
335
+
336
+ const header = await this.getCheckpointHeader(pruneFrom);
337
+ if (header === undefined) {
338
+ throw new Error(`Missing checkpoint header ${pruneFrom}`);
339
+ }
340
+
341
+ const pruneFromSlotNumber = header.slotNumber;
342
+ const pruneFromEpochNumber: EpochNumber = getEpochAtSlot(pruneFromSlotNumber, this.l1Constants);
343
+
344
+ const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
345
+
346
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
347
+ // promises when the gap between local pending and proven checkpoint numbers is large.
348
+ const BATCH_SIZE = 10;
349
+ const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
350
+ const checkpoints = (
351
+ await asyncPool(BATCH_SIZE, indices, idx => this.stores.blocks.getCheckpointData(idx))
352
+ ).filter(isDefined);
353
+ const newBlocks = (
354
+ await asyncPool(BATCH_SIZE, checkpoints, cp =>
355
+ this.stores.blocks.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
356
+ )
357
+ )
358
+ .filter(isDefined)
359
+ .flat();
360
+
361
+ // Emit an event for listening services to react to the chain prune
362
+ this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
363
+ type: L2BlockSourceEvents.L2PruneUnproven,
364
+ epochNumber: pruneFromEpochNumber,
365
+ blocks: newBlocks,
366
+ });
367
+
368
+ this.log.debug(
369
+ `L2 prune from ${provenCheckpointNumber + 1} to ${localPendingCheckpointNumber} will occur on next checkpoint submission.`,
370
+ );
371
+ await this.updater.removeCheckpointsAfter(provenCheckpointNumber);
372
+ this.log.warn(
373
+ `Removed ${count(checkpointsToUnwind, 'checkpoint')} after checkpoint ${provenCheckpointNumber} ` +
374
+ `due to predicted reorg at L1 block ${currentL1BlockNumber}. ` +
375
+ `Updated latest checkpoint is ${await this.stores.blocks.getLatestCheckpointNumber()}.`,
376
+ );
377
+ this.instrumentation.processPrune(timer.ms());
378
+ // TODO(palla/reorg): Do we need to set the block synched L1 block number here?
379
+ // Seems like the next iteration should handle this.
380
+ // await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
381
+ }
382
+
383
+ return { rollupCanPrune };
384
+ }
385
+
386
+ private nextRange(end: bigint, limit: bigint): [bigint, bigint] {
387
+ const batchSize = (this.config.batchSize * this.l1Constants.slotDuration) / this.l1Constants.ethereumSlotDuration;
388
+ const nextStart = end + 1n;
389
+ const nextEnd = nextStart + BigInt(batchSize);
390
+ if (nextEnd > limit) {
391
+ return [nextStart, limit];
392
+ }
393
+ return [nextStart, nextEnd];
394
+ }
395
+
396
+ @trackSpan('Archiver.handleL1ToL2Messages')
397
+ private async handleL1ToL2Messages(
398
+ currentL1Block: L1BlockId,
399
+ finalizedL1Block: L1BlockId | undefined,
400
+ ): Promise<boolean> {
401
+ // Load the syncpoint, which may have been updated in a previous iteration
402
+ const {
403
+ messagesSynchedTo = {
404
+ l1BlockNumber: this.l1Constants.l1StartBlock,
405
+ l1BlockHash: this.l1Constants.l1StartBlockHash,
406
+ },
407
+ } = await getArchiverSynchPoint(this.stores);
408
+
409
+ // Nothing to do if L1 block number has not moved forward
410
+ const currentL1BlockNumber = currentL1Block.l1BlockNumber;
411
+ if (currentL1BlockNumber <= messagesSynchedTo.l1BlockNumber) {
412
+ return true;
413
+ }
414
+
415
+ // Compare local message store state with the remote. If they match, we just advance the match pointer.
416
+ const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
417
+ const localLastMessage = await this.stores.messages.getLastMessage();
418
+ if (await this.localStateMatches(localLastMessage, remoteMessagesState)) {
419
+ this.log.trace(`Local L1 to L2 messages are already in sync with remote at L1 block ${currentL1BlockNumber}`);
420
+ await this.stores.messages.setMessageSyncState(
421
+ currentL1Block,
422
+ remoteMessagesState.treeInProgress,
423
+ finalizedL1Block,
424
+ );
425
+ return true;
426
+ }
427
+
428
+ // If not, then we are out of sync. Most likely there are new messages on the inbox, so we try retrieving them.
429
+ // However, it could also be the case that there was an L1 reorg and our syncpoint is no longer valid.
430
+ // If that's the case, we'd get an exception out of the message store since the rolling hash of the first message
431
+ // we try to insert would not match the one in the db, in which case we rollback to the last common message with L1.
432
+ try {
433
+ await this.retrieveAndStoreMessages(messagesSynchedTo.l1BlockNumber, currentL1BlockNumber);
434
+ } catch (error) {
435
+ if (isErrorClass(error, MessageStoreError)) {
436
+ this.log.warn(
437
+ `Failed to store L1 to L2 messages retrieved from L1: ${error.message}. Rolling back syncpoint to retry.`,
438
+ { inboxMessage: error.inboxMessage },
439
+ );
440
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
441
+ return false;
442
+ }
443
+ throw error;
444
+ }
445
+
446
+ // Note that, if there are no new messages to insert, but there was an L1 reorg that pruned out last messages,
447
+ // we'd notice by comparing our local state with the remote one again, and seeing they don't match even after
448
+ // our sync attempt. In this case, we also rollback our syncpoint, and trigger a retry.
449
+ const localLastMessageAfterSync = await this.stores.messages.getLastMessage();
450
+ if (!(await this.localStateMatches(localLastMessageAfterSync, remoteMessagesState))) {
451
+ this.log.warn(
452
+ `Local L1 to L2 messages state does not match remote after sync attempt. Rolling back syncpoint to retry.`,
453
+ { localLastMessageAfterSync, remoteMessagesState },
454
+ );
455
+ await this.rollbackL1ToL2Messages(remoteMessagesState);
456
+ return false;
457
+ }
458
+
459
+ // Advance the syncpoint after a successful sync
460
+ await this.stores.messages.setMessageSyncState(
461
+ currentL1Block,
462
+ remoteMessagesState.treeInProgress,
463
+ finalizedL1Block,
464
+ );
465
+ return true;
466
+ }
467
+
468
+ /** Checks if the local rolling hash and message count matches the remote state */
469
+ private async localStateMatches(localLastMessage: InboxMessage | undefined, remoteState: InboxContractState) {
470
+ const localMessageCount = await this.stores.messages.getTotalL1ToL2MessageCount();
471
+ this.log.trace(`Comparing local and remote inbox state`, { localMessageCount, localLastMessage, remoteState });
472
+
473
+ return (
474
+ remoteState.totalMessagesInserted === localMessageCount &&
475
+ remoteState.messagesRollingHash.equals(localLastMessage?.rollingHash ?? Buffer16.ZERO)
476
+ );
477
+ }
478
+
479
+ /** Retrieves L1 to L2 messages from L1 in batches and stores them. */
480
+ private async retrieveAndStoreMessages(fromL1Block: bigint, toL1Block: bigint): Promise<void> {
481
+ let searchStartBlock: bigint = 0n;
482
+ let searchEndBlock: bigint = fromL1Block;
483
+
484
+ let lastMessage: InboxMessage | undefined;
485
+ let messageCount = 0;
486
+
487
+ do {
488
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, toL1Block);
489
+ this.log.trace(`Retrieving L1 to L2 messages in L1 blocks ${searchStartBlock}-${searchEndBlock}`);
490
+ const messages = await retrieveL1ToL2Messages(this.inbox, searchStartBlock, searchEndBlock);
491
+ const timer = new Timer();
492
+ await this.stores.messages.addL1ToL2Messages(messages);
493
+ const perMsg = timer.ms() / messages.length;
494
+ this.instrumentation.processNewMessages(messages.length, perMsg);
495
+ for (const msg of messages) {
496
+ this.log.debug(`Downloaded L1 to L2 message`, { ...msg, leaf: msg.leaf.toString() });
497
+ lastMessage = msg;
498
+ messageCount++;
499
+ }
500
+ } while (searchEndBlock < toL1Block);
501
+
502
+ if (messageCount > 0) {
503
+ this.log.info(
504
+ `Retrieved ${messageCount} new L1 to L2 messages up to message with index ${lastMessage?.index} for checkpoint ${lastMessage?.checkpointNumber}`,
505
+ { lastMessage, messageCount },
506
+ );
507
+ }
508
+ }
509
+
510
+ /**
511
+ * Rolls back local L1 to L2 messages to the last common message with L1, and updates the syncpoint to the L1 block of that message.
512
+ * If no common message is found, rolls back all messages and sets the syncpoint to the start block.
513
+ */
514
+ private async rollbackL1ToL2Messages(remoteMessagesState: InboxContractState): Promise<L1BlockId> {
515
+ const { treeInProgress: remoteTreeInProgress, messagesRollingHash: remoteRollingHash } = remoteMessagesState;
516
+
517
+ const messagesFinalizedL1Block = await this.stores.messages.getMessagesFinalizedL1Block();
518
+ const finalizedL1BlockNumber = messagesFinalizedL1Block?.l1BlockNumber;
519
+
520
+ // Slowly go back through our messages until we find the last common message. We could query the logs in
521
+ // batch as an optimization, but the depth of the reorg should not be deep, and this is a very rare case,
522
+ // so it's fine to query one log at a time.
523
+ let commonMsg: undefined | InboxMessage;
524
+ let messagesToDelete = 0;
525
+ this.log.verbose(`Searching most recent common L1 to L2 message`);
526
+ for await (const localMsg of this.stores.messages.iterateL1ToL2Messages({ reverse: true })) {
527
+ const logCtx = { remoteMsg: undefined as InboxMessage | undefined, localMsg, remoteMessagesState };
528
+
529
+ // First check if the local message rolling hash matches the current rolling hash of the inbox contract,
530
+ // which means we just need to rollback some local messages and we should be back in sync. This means there
531
+ // was an L1 reorg that removed some of the messages we had, but no new messages were added compared.
532
+ if (localMsg.rollingHash.equals(remoteRollingHash)) {
533
+ this.log.info(
534
+ `Found common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber} matching current remote state`,
535
+ logCtx,
536
+ );
537
+ commonMsg = localMsg;
538
+ break;
539
+ }
540
+
541
+ // Messages at or below the finalized L1 block cannot have been reorged — accept as common without querying L1.
542
+ if (finalizedL1BlockNumber !== undefined && localMsg.l1BlockNumber <= finalizedL1BlockNumber) {
543
+ this.log.info(`Found common L1 to L2 message at finalized L1 block ${localMsg.l1BlockNumber}`, logCtx);
544
+ commonMsg = localMsg;
545
+ break;
546
+ }
547
+
548
+ // If there's no match with the current remote state, check if the message exists on the inbox contract at all
549
+ // by looking at the inbox events. If the L1 reorg *added* new messages in addition to deleting existing ones,
550
+ // then the current remote state's rolling hash will not match anything we have locally, so we need to check existence
551
+ // of individual messages via logs. Note we use logs and not historical queries so we don't have to depend on
552
+ // an archival rpc node, since the message could be from a long time ago if we're catching up with syncing.
553
+ const remoteMsg = await retrieveL1ToL2Message(this.inbox, localMsg);
554
+ logCtx.remoteMsg = remoteMsg;
555
+ if (remoteMsg && remoteMsg.rollingHash.equals(localMsg.rollingHash)) {
556
+ this.log.info(
557
+ `Found most recent common L1 to L2 message at index ${localMsg.index} on L1 block ${localMsg.l1BlockNumber}`,
558
+ logCtx,
559
+ );
560
+ commonMsg = remoteMsg;
561
+ break;
562
+ } else if (remoteMsg) {
563
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} has different rolling hash`, logCtx);
564
+ messagesToDelete++;
565
+ } else {
566
+ this.log.debug(`Local L1 to L2 message with index ${localMsg.index} not found on L1`, logCtx);
567
+ messagesToDelete++;
568
+ }
569
+ }
570
+
571
+ // Delete everything after the common message we found, if anything needs to be deleted.
572
+ // Do not exit early if there are no messages to delete, we still want to update the syncpoint.
573
+ if (messagesToDelete > 0) {
574
+ const lastGoodIndex = commonMsg?.index;
575
+ this.log.warn(`Rolling back all local L1 to L2 messages after index ${lastGoodIndex ?? 'initial'}`);
576
+ await this.stores.messages.removeL1ToL2Messages(lastGoodIndex !== undefined ? lastGoodIndex + 1n : 0n);
577
+ }
578
+
579
+ // Update the syncpoint so the loop below reprocesses the changed messages. We go to the block before
580
+ // the last common one, so we force reprocessing it, in case new messages were added on that same L1 block
581
+ // after the last common message. Cap at the finalized L1 block: messages at or below finalized cannot
582
+ // have been reorged, so there is no need to walk back any further than that.
583
+ const syncPointL1BlockNumber = maxBigint(
584
+ ...compactArray([
585
+ commonMsg ? commonMsg.l1BlockNumber - 1n : undefined,
586
+ finalizedL1BlockNumber,
587
+ this.l1Constants.l1StartBlock,
588
+ ]),
589
+ );
590
+
591
+ const syncPointL1BlockHash =
592
+ syncPointL1BlockNumber === finalizedL1BlockNumber
593
+ ? messagesFinalizedL1Block!.l1BlockHash
594
+ : await this.getL1BlockHash(syncPointL1BlockNumber);
595
+
596
+ const messagesSyncPoint = { l1BlockNumber: syncPointL1BlockNumber, l1BlockHash: syncPointL1BlockHash };
597
+ await this.stores.messages.setMessageSyncState(messagesSyncPoint, remoteTreeInProgress);
598
+ this.log.verbose(`Updated messages syncpoint to L1 block ${messagesSyncPoint.l1BlockNumber}`, {
599
+ ...messagesSyncPoint,
600
+ remoteTreeInProgress,
601
+ });
602
+ return messagesSyncPoint;
603
+ }
604
+
605
+ private async getL1BlockHash(l1BlockNumber: bigint): Promise<Buffer32> {
606
+ const block = await this.publicClient.getBlock({ blockNumber: l1BlockNumber, includeTransactions: false });
607
+ if (!block) {
608
+ throw new Error(`Missing L1 block ${l1BlockNumber}`);
609
+ }
610
+ return Buffer32.fromString(block.hash);
611
+ }
612
+
613
+ @trackSpan('Archiver.handleCheckpoints')
614
+ private async handleCheckpoints(
615
+ blocksSynchedTo: bigint,
616
+ currentL1BlockNumber: bigint,
617
+ initialSyncComplete: boolean,
618
+ ): Promise<RollupStatus> {
619
+ const localPendingCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
620
+ const initialValidationResult: ValidateCheckpointResult | undefined =
621
+ await this.stores.blocks.getPendingChainValidationStatus();
622
+ const {
623
+ provenCheckpointNumber,
624
+ provenArchive,
625
+ pendingCheckpointNumber,
626
+ pendingArchive,
627
+ archiveOfMyCheckpoint: archiveForLocalPendingCheckpointNumber,
628
+ } = await execInSpan(this.tracer, 'Archiver.getRollupStatus', () =>
629
+ this.rollup.status(localPendingCheckpointNumber, { blockNumber: currentL1BlockNumber }),
630
+ );
631
+ const rollupStatus: RollupStatus = {
632
+ provenCheckpointNumber,
633
+ provenArchive: provenArchive.toString(),
634
+ pendingCheckpointNumber,
635
+ pendingArchive: pendingArchive.toString(),
636
+ validationResult: initialValidationResult,
637
+ };
638
+ this.log.trace(`Retrieved rollup status at current L1 block ${currentL1BlockNumber}.`, {
639
+ localPendingCheckpointNumber,
640
+ blocksSynchedTo,
641
+ currentL1BlockNumber,
642
+ archiveForLocalPendingCheckpointNumber,
643
+ ...rollupStatus,
644
+ });
645
+
646
+ const updateProvenCheckpoint = async () => {
647
+ // Annoying edge case: if proven checkpoint is moved back to 0 due to a reorg at the beginning of the chain,
648
+ // we need to set it to zero. This is an edge case because we dont have a checkpoint zero (initial checkpoint is one),
649
+ // so localCheckpointForDestinationProvenCheckpointNumber would not be found below.
650
+ if (provenCheckpointNumber === 0) {
651
+ const localProvenCheckpointNumber = await this.stores.blocks.getProvenCheckpointNumber();
652
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
653
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
654
+ this.log.info(`Rolled back proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
655
+ }
656
+ }
657
+
658
+ const localCheckpointForDestinationProvenCheckpointNumber =
659
+ await this.stores.blocks.getCheckpointData(provenCheckpointNumber);
660
+
661
+ // Sanity check. I've hit what seems to be a state where the proven checkpoint is set to a value greater than the latest
662
+ // synched checkpoint when requesting L2Tips from the archiver. This is the only place where the proven checkpoint is set.
663
+ const synched = await this.stores.blocks.getLatestCheckpointNumber();
664
+ if (
665
+ localCheckpointForDestinationProvenCheckpointNumber &&
666
+ synched < localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber
667
+ ) {
668
+ this.log.error(
669
+ `Hit local checkpoint greater than last synched checkpoint: ${localCheckpointForDestinationProvenCheckpointNumber.checkpointNumber} > ${synched}`,
670
+ );
671
+ }
672
+
673
+ this.log.trace(
674
+ `Local checkpoint for remote proven checkpoint ${provenCheckpointNumber} is ${
675
+ localCheckpointForDestinationProvenCheckpointNumber?.archive.root.toString() ?? 'undefined'
676
+ }`,
677
+ );
678
+
679
+ if (
680
+ localCheckpointForDestinationProvenCheckpointNumber &&
681
+ provenArchive.equals(localCheckpointForDestinationProvenCheckpointNumber.archive.root)
682
+ ) {
683
+ const localProvenCheckpointNumber = await this.stores.blocks.getProvenCheckpointNumber();
684
+ if (localProvenCheckpointNumber !== provenCheckpointNumber) {
685
+ await this.updater.setProvenCheckpointNumber(provenCheckpointNumber);
686
+ this.log.info(`Updated proven chain to checkpoint ${provenCheckpointNumber}`, { provenCheckpointNumber });
687
+ const provenSlotNumber = localCheckpointForDestinationProvenCheckpointNumber.header.slotNumber;
688
+ const provenEpochNumber: EpochNumber = getEpochAtSlot(provenSlotNumber, this.l1Constants);
689
+ const lastBlockNumberInCheckpoint =
690
+ localCheckpointForDestinationProvenCheckpointNumber.startBlock +
691
+ localCheckpointForDestinationProvenCheckpointNumber.blockCount -
692
+ 1;
693
+
694
+ this.events.emit(L2BlockSourceEvents.L2BlockProven, {
695
+ type: L2BlockSourceEvents.L2BlockProven,
696
+ blockNumber: BlockNumber(lastBlockNumberInCheckpoint),
697
+ slotNumber: provenSlotNumber,
698
+ epochNumber: provenEpochNumber,
699
+ });
700
+ this.instrumentation.updateLastProvenCheckpoint(localCheckpointForDestinationProvenCheckpointNumber);
701
+ } else {
702
+ this.log.trace(`Proven checkpoint ${provenCheckpointNumber} already stored.`);
703
+ }
704
+ }
705
+ };
706
+
707
+ // This is an edge case that we only hit if there are no proposed checkpoints.
708
+ // If we have 0 checkpoints locally and there are no checkpoints onchain there is nothing to do.
709
+ const noCheckpoints = localPendingCheckpointNumber === 0 && pendingCheckpointNumber === 0;
710
+ if (noCheckpoints) {
711
+ await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
712
+ this.log.debug(
713
+ `No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}, no checkpoints on chain`,
714
+ );
715
+ return rollupStatus;
716
+ }
717
+
718
+ await updateProvenCheckpoint();
719
+
720
+ // Related to the L2 reorgs of the pending chain. We are only interested in actually addressing a reorg if there
721
+ // are any state that could be impacted by it. If we have no checkpoints, there is no impact.
722
+ if (localPendingCheckpointNumber > 0) {
723
+ const localPendingCheckpoint = await this.stores.blocks.getCheckpointData(localPendingCheckpointNumber);
724
+ if (localPendingCheckpoint === undefined) {
725
+ throw new Error(`Missing checkpoint ${localPendingCheckpointNumber}`);
726
+ }
727
+
728
+ const localPendingArchiveRoot = localPendingCheckpoint.archive.root.toString();
729
+ const noCheckpointSinceLast = localPendingCheckpoint && pendingArchive.toString() === localPendingArchiveRoot;
730
+ if (noCheckpointSinceLast) {
731
+ // We believe the following line causes a problem when we encounter L1 re-orgs.
732
+ // Basically, by setting the synched L1 block number here, we are saying that we have
733
+ // processed all checkpoints up to the current L1 block number and we will not attempt to retrieve logs from
734
+ // this block again (or any blocks before).
735
+ // However, in the re-org scenario, our L1 node is temporarily lying to us and we end up potentially missing checkpoints.
736
+ // We must only set this block number based on actually retrieved logs.
737
+ // TODO(#8621): Tackle this properly when we handle L1 Re-orgs.
738
+ // await this.stores.blocks.setSynchedL1BlockNumber(currentL1BlockNumber);
739
+ this.log.debug(`No checkpoints to retrieve from ${blocksSynchedTo + 1n} to ${currentL1BlockNumber}`);
740
+ return rollupStatus;
741
+ }
742
+
743
+ const localPendingCheckpointInChain = archiveForLocalPendingCheckpointNumber.equals(
744
+ localPendingCheckpoint.archive.root,
745
+ );
746
+ if (!localPendingCheckpointInChain) {
747
+ // If our local pending checkpoint tip is not in the chain on L1 a "prune" must have happened
748
+ // or the L1 have reorged.
749
+ // In any case, we have to figure out how far into the past the action will take us.
750
+ // For simplicity here, we will simply rewind until we end in a checkpoint that is also on the chain on L1.
751
+ this.log.debug(
752
+ `L2 prune has been detected due to local pending checkpoint ${localPendingCheckpointNumber} not in chain`,
753
+ { localPendingCheckpointNumber, localPendingArchiveRoot, archiveForLocalPendingCheckpointNumber },
754
+ );
755
+
756
+ let tipAfterUnwind = localPendingCheckpointNumber;
757
+ while (true) {
758
+ const candidateCheckpoint = await this.stores.blocks.getCheckpointData(tipAfterUnwind);
759
+ if (candidateCheckpoint === undefined) {
760
+ break;
761
+ }
762
+
763
+ const archiveAtContract = await this.rollup.archiveAt(candidateCheckpoint.checkpointNumber);
764
+ this.log.trace(
765
+ `Checking local checkpoint ${candidateCheckpoint.checkpointNumber} with archive ${candidateCheckpoint.archive.root}`,
766
+ {
767
+ archiveAtContract,
768
+ archiveLocal: candidateCheckpoint.archive.root.toString(),
769
+ },
770
+ );
771
+ if (archiveAtContract.equals(candidateCheckpoint.archive.root)) {
772
+ break;
773
+ }
774
+ tipAfterUnwind--;
775
+ }
776
+
777
+ const checkpointsToRemove = localPendingCheckpointNumber - tipAfterUnwind;
778
+ await this.updater.removeCheckpointsAfter(CheckpointNumber(tipAfterUnwind));
779
+
780
+ this.log.warn(
781
+ `Removed ${count(checkpointsToRemove, 'checkpoint')} after checkpoint ${tipAfterUnwind} ` +
782
+ `due to mismatched checkpoint hashes at L1 block ${currentL1BlockNumber}. ` +
783
+ `Updated L2 latest checkpoint is ${await this.stores.blocks.getLatestCheckpointNumber()}.`,
784
+ );
785
+ }
786
+ }
787
+
788
+ // Retrieve checkpoints in batches. Each batch is estimated to accommodate up to 'blockBatchSize' L1 blocks,
789
+ // computed using the L2 block time vs the L1 block time.
790
+ let searchStartBlock: bigint = blocksSynchedTo;
791
+ let searchEndBlock: bigint = blocksSynchedTo;
792
+ let lastRetrievedCheckpoint: PublishedCheckpoint | undefined;
793
+ let lastSeenCheckpoint: PublishedCheckpoint | undefined;
794
+
795
+ do {
796
+ [searchStartBlock, searchEndBlock] = this.nextRange(searchEndBlock, currentL1BlockNumber);
797
+
798
+ this.log.trace(`Retrieving checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
799
+
800
+ // First fetch calldata only, no blobs yet, since we may be able to just get that data out of the proposed chain
801
+ const calldataCheckpoints = await execInSpan(this.tracer, 'Archiver.retrieveCheckpointCalldataFromRollup', () =>
802
+ retrieveCheckpointCalldataFromRollup(
803
+ this.rollup,
804
+ this.publicClient,
805
+ this.debugClient,
806
+ searchStartBlock, // TODO(palla/reorg): If the L2 reorg was due to an L1 reorg, we need to start search earlier
807
+ searchEndBlock,
808
+ this.instrumentation,
809
+ this.log,
810
+ ),
811
+ );
812
+
813
+ if (calldataCheckpoints.length === 0) {
814
+ // We are not calling `setBlockSynchedL1BlockNumber` because it may cause sync issues if based off infura.
815
+ // See further details in earlier comments.
816
+ this.log.trace(`Retrieved no new checkpoints from L1 block ${searchStartBlock} to ${searchEndBlock}`);
817
+ continue;
818
+ }
819
+
820
+ this.log.debug(
821
+ `Retrieved ${calldataCheckpoints.length} new checkpoint calldata between L1 blocks ${searchStartBlock} and ${searchEndBlock}`,
822
+ {
823
+ lastProcessedCheckpoint: calldataCheckpoints[calldataCheckpoints.length - 1].l1,
824
+ searchStartBlock,
825
+ searchEndBlock,
826
+ },
827
+ );
828
+
829
+ // Check if the last checkpoint matches a local pending entry (so we can skip blob fetch).
830
+ // We only check the last one; if it matches, the blob fetch is skipped for that entry.
831
+ // TODO(palla/pipelining): We may have more than a single checkpoint to promote
832
+ const lastCalldataCheckpoint = calldataCheckpoints[calldataCheckpoints.length - 1];
833
+ const promoteResult = await this.tryBuildPublishedCheckpointFromProposed(lastCalldataCheckpoint);
834
+ const checkpointToPromote = promoteResult && !('diverged' in promoteResult) ? promoteResult : undefined;
835
+ const evictProposedFrom =
836
+ promoteResult && 'diverged' in promoteResult ? promoteResult.fromCheckpointNumber : undefined;
837
+
838
+ // Then fetch blobs in parallel and build the full published checkpoints
839
+ const toFetchBlobs = checkpointToPromote ? calldataCheckpoints.slice(0, -1) : calldataCheckpoints;
840
+ const blobFetched = await asyncPool(10, toFetchBlobs, async checkpoint =>
841
+ retrievedToPublishedCheckpoint({
842
+ ...checkpoint,
843
+ checkpointBlobData: await getCheckpointBlobDataFromBlobs(
844
+ this.blobClient,
845
+ checkpoint.l1.blockHash,
846
+ checkpoint.blobHashes,
847
+ checkpoint.checkpointNumber,
848
+ this.log,
849
+ !initialSyncComplete,
850
+ checkpoint.parentBeaconBlockRoot,
851
+ checkpoint.l1.timestamp,
852
+ ),
853
+ }),
854
+ );
855
+
856
+ // And add the promoted checkpoint to the list of all checkpoints
857
+ const publishedCheckpoints = checkpointToPromote ? [...blobFetched, checkpointToPromote] : blobFetched;
858
+ const validCheckpoints: PublishedCheckpoint[] = [];
859
+
860
+ // Now loop through all checkpoints and validate their attestations
861
+ for (const published of publishedCheckpoints) {
862
+ // Check the attestations uploaded by the publisher to L1 are correct
863
+ // Rollup contract does not validate attestations to save on gas, so this
864
+ // falls on the nodes to verify offchain and skip those checkpoints.
865
+ const validationResult = this.config.skipValidateCheckpointAttestations
866
+ ? { valid: true as const }
867
+ : await validateCheckpointAttestations(
868
+ published,
869
+ this.epochCache,
870
+ this.l1Constants,
871
+ this.getSignatureContext(),
872
+ this.log,
873
+ );
874
+
875
+ // Also skip the checkpoint if it builds on a previously-rejected ancestor. Without
876
+ // this, addCheckpoints would throw InitialCheckpointNumberNotSequentialError when the
877
+ // ancestor was skipped earlier (e.g. due to invalid attestations), the catch handler
878
+ // would roll back the L1 sync point, and the next iteration would re-fetch and re-throw.
879
+ const rejectedAncestor = await this.stores.blocks.getRejectedCheckpointByArchiveRoot(
880
+ published.checkpoint.header.lastArchiveRoot,
881
+ );
882
+
883
+ // Update the validation result if it has changed, so we can keep track of the first invalid checkpoint
884
+ // in case there is a sequence of more than one invalid checkpoint, as we need to invalidate the first one.
885
+ // There is an exception though: if a checkpoint is invalidated and replaced with another invalid checkpoint,
886
+ // we need to update the validation result, since we need to be able to invalidate the new one.
887
+ // See test 'chain progresses if an invalid checkpoint is invalidated with an invalid one' for more info.
888
+ // Do not update the validation result if there is a rejected ancestor, since in that case we want to keep the
889
+ // original invalidation, as the new checkpoint is extending from a previous invalid one.
890
+ const validStatusChanged = rollupStatus.validationResult?.valid !== validationResult.valid;
891
+ const invalidStatusWithSameCheckpointNumber =
892
+ !validationResult.valid &&
893
+ rollupStatus.validationResult &&
894
+ !rollupStatus.validationResult.valid &&
895
+ rollupStatus.validationResult.checkpoint.checkpointNumber === validationResult.checkpoint.checkpointNumber;
896
+
897
+ if (!rejectedAncestor && (validStatusChanged || invalidStatusWithSameCheckpointNumber)) {
898
+ rollupStatus.validationResult = validationResult;
899
+ }
900
+
901
+ if (!validationResult.valid) {
902
+ this.log.warn(`Skipping checkpoint ${published.checkpoint.number} due to invalid attestations`, {
903
+ checkpointHash: published.checkpoint.hash(),
904
+ l1BlockNumber: published.l1.blockNumber,
905
+ ...pick(validationResult, 'reason'),
906
+ });
907
+
908
+ // Emit event for invalid checkpoint detection
909
+ this.events.emit(L2BlockSourceEvents.InvalidAttestationsCheckpointDetected, {
910
+ type: L2BlockSourceEvents.InvalidAttestationsCheckpointDetected,
911
+ validationResult,
912
+ });
913
+
914
+ // Persist a rejected-ancestor entry so any later checkpoint that builds on this one
915
+ // is detected and skipped (rather than tripping the addCheckpoints consecutive-number
916
+ // check and causing the sync point to roll back in a loop).
917
+ await this.stores.blocks.addRejectedCheckpoint({
918
+ checkpointNumber: published.checkpoint.number,
919
+ archiveRoot: published.checkpoint.archive.root,
920
+ parentArchiveRoot: published.checkpoint.header.lastArchiveRoot,
921
+ slotNumber: published.checkpoint.header.slotNumber,
922
+ l1: published.l1,
923
+ reason: 'invalid-attestations' as const,
924
+ });
925
+
926
+ continue;
927
+ }
928
+
929
+ if (rejectedAncestor) {
930
+ const descendantInfo = published.checkpoint.toCheckpointInfo();
931
+ this.log.warn(
932
+ `Skipping checkpoint ${published.checkpoint.number} as it is a descendant of ` +
933
+ `rejected checkpoint ${rejectedAncestor.checkpointNumber} (${rejectedAncestor.reason})`,
934
+ {
935
+ checkpointNumber: published.checkpoint.number,
936
+ checkpointHash: published.checkpoint.hash(),
937
+ l1BlockNumber: published.l1.blockNumber,
938
+ l1BlockHash: published.l1.blockHash,
939
+ ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
940
+ ancestorArchiveRoot: rejectedAncestor.archiveRoot.toString(),
941
+ ancestorReason: rejectedAncestor.reason,
942
+ },
943
+ );
944
+
945
+ this.events.emit(L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected, {
946
+ type: L2BlockSourceEvents.DescendentOfInvalidAttestationsCheckpointDetected,
947
+ checkpoint: descendantInfo,
948
+ ancestorArchiveRoot: rejectedAncestor.archiveRoot,
949
+ ancestorCheckpointNumber: rejectedAncestor.checkpointNumber,
950
+ });
951
+
952
+ // Persist this chainpoint as rejected as well, so we can construct a chain of
953
+ // skipped checkpoints starting from the first one with invalid attestations.
954
+ await this.stores.blocks.addRejectedCheckpoint({
955
+ checkpointNumber: published.checkpoint.number,
956
+ archiveRoot: published.checkpoint.archive.root,
957
+ parentArchiveRoot: published.checkpoint.header.lastArchiveRoot,
958
+ slotNumber: published.checkpoint.header.slotNumber,
959
+ l1: published.l1,
960
+ reason: 'descends-from-invalid-attestations' as const,
961
+ });
962
+
963
+ continue;
964
+ }
965
+
966
+ // Check the inHash of the checkpoint against the l1->l2 messages.
967
+ // The messages should've been synced up to the currentL1BlockNumber and must be available for the published
968
+ // checkpoints we just retrieved.
969
+ const l1ToL2Messages = await this.stores.messages.getL1ToL2Messages(published.checkpoint.number);
970
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
971
+ const publishedInHash = published.checkpoint.header.inHash;
972
+ if (!computedInHash.equals(publishedInHash)) {
973
+ this.log.fatal(`Mismatch inHash for checkpoint ${published.checkpoint.number}`, {
974
+ checkpointHash: published.checkpoint.hash(),
975
+ l1BlockNumber: published.l1.blockNumber,
976
+ computedInHash,
977
+ publishedInHash,
978
+ });
979
+ // Throwing an error since this is most likely caused by a bug.
980
+ throw new Error(
981
+ `Mismatch inHash for checkpoint ${published.checkpoint.number}. Expected ${computedInHash} but got ${publishedInHash}`,
982
+ );
983
+ }
984
+
985
+ validCheckpoints.push(published);
986
+ this.log.debug(
987
+ `Ingesting new checkpoint ${published.checkpoint.number} with ${published.checkpoint.blocks.length} blocks`,
988
+ {
989
+ checkpointHash: published.checkpoint.hash(),
990
+ l1BlockNumber: published.l1.blockNumber,
991
+ ...published.checkpoint.header.toInspect(),
992
+ blocks: published.checkpoint.blocks.map(b => b.getStats()),
993
+ },
994
+ );
995
+ }
996
+
997
+ for (const published of validCheckpoints) {
998
+ this.instrumentation.processCheckpointL1Timing({
999
+ slotNumber: published.checkpoint.header.slotNumber,
1000
+ l1Timestamp: published.l1.timestamp,
1001
+ l1Constants: this.l1Constants,
1002
+ });
1003
+ }
1004
+
1005
+ try {
1006
+ const updatedValidationResult =
1007
+ rollupStatus.validationResult === initialValidationResult ? undefined : rollupStatus.validationResult;
1008
+
1009
+ // Split valid checkpoints: the promoted one (if any) is persisted via the proposed-promotion path,
1010
+ // the rest via addCheckpoints. Both paths run within the same store transaction for atomicity.
1011
+ const [[maybeValidCheckpointToPromote], checkpointsToAdd] = partition(
1012
+ validCheckpoints,
1013
+ c => c.checkpoint.number === checkpointToPromote?.checkpoint.number,
1014
+ );
1015
+
1016
+ const [processDuration, result] = await elapsed(() =>
1017
+ execInSpan(this.tracer, 'Archiver.addCheckpoints', () =>
1018
+ this.updater.addCheckpoints(
1019
+ checkpointsToAdd,
1020
+ updatedValidationResult,
1021
+ maybeValidCheckpointToPromote && {
1022
+ l1: lastCalldataCheckpoint.l1,
1023
+ attestations: lastCalldataCheckpoint.attestations,
1024
+ checkpoint: maybeValidCheckpointToPromote,
1025
+ },
1026
+ evictProposedFrom,
1027
+ ),
1028
+ ),
1029
+ );
1030
+
1031
+ if (validCheckpoints.length > 0) {
1032
+ this.instrumentation.processNewCheckpointedBlocks(
1033
+ processDuration / validCheckpoints.length,
1034
+ validCheckpoints.flatMap(c => c.checkpoint.blocks),
1035
+ );
1036
+ }
1037
+
1038
+ // If blocks were pruned due to conflict with L1 checkpoints, emit event
1039
+ if (result.prunedBlocks && result.prunedBlocks.length > 0) {
1040
+ const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
1041
+ const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
1042
+
1043
+ this.log.info(
1044
+ `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
1045
+ { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
1046
+ );
1047
+
1048
+ // Emit event for listening services to react to the prune.
1049
+ // Note: slotNumber comes from the first pruned block. If pruned blocks theoretically spanned multiple slots,
1050
+ // only one slot number would be reported (though in practice all blocks in a checkpoint span a single slot).
1051
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
1052
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
1053
+ slotNumber: prunedSlotNumber,
1054
+ blocks: result.prunedBlocks,
1055
+ });
1056
+ }
1057
+ } catch (err) {
1058
+ if (err instanceof InitialCheckpointNumberNotSequentialError) {
1059
+ const { previousCheckpointNumber, newCheckpointNumber } = err;
1060
+ const previousCheckpoint = previousCheckpointNumber
1061
+ ? await this.stores.blocks.getCheckpointData(CheckpointNumber(previousCheckpointNumber))
1062
+ : undefined;
1063
+ const lastFinalizedCheckpoint = await this.stores.blocks.getCheckpointData(
1064
+ await this.stores.blocks.getFinalizedCheckpointNumber(),
1065
+ );
1066
+ const updatedL1SyncPoint =
1067
+ previousCheckpoint?.l1.blockNumber ??
1068
+ lastFinalizedCheckpoint?.l1.blockNumber ??
1069
+ this.l1Constants.l1StartBlock;
1070
+ await this.stores.blocks.setSynchedL1BlockNumber(updatedL1SyncPoint);
1071
+ this.log.warn(
1072
+ `Attempting to insert checkpoint ${newCheckpointNumber} with previous block ${previousCheckpointNumber}. Rolling back L1 sync point to ${updatedL1SyncPoint} to try and fetch the missing blocks.`,
1073
+ {
1074
+ previousCheckpointNumber,
1075
+ previousCheckpoint: previousCheckpoint?.header.toInspect(),
1076
+ lastFinalizedCheckpoint: lastFinalizedCheckpoint?.header.toInspect(),
1077
+ l1StartBlock: this.l1Constants.l1StartBlock,
1078
+ newCheckpointNumber,
1079
+ updatedL1SyncPoint,
1080
+ },
1081
+ );
1082
+ }
1083
+ throw err;
1084
+ }
1085
+
1086
+ for (const checkpoint of validCheckpoints) {
1087
+ this.log.info(`Downloaded checkpoint ${checkpoint.checkpoint.number}`, {
1088
+ checkpointHash: checkpoint.checkpoint.hash(),
1089
+ checkpointNumber: checkpoint.checkpoint.number,
1090
+ blockCount: checkpoint.checkpoint.blocks.length,
1091
+ txCount: checkpoint.checkpoint.blocks.reduce((acc, b) => acc + b.body.txEffects.length, 0),
1092
+ header: checkpoint.checkpoint.header.toInspect(),
1093
+ archiveRoot: checkpoint.checkpoint.archive.root.toString(),
1094
+ archiveNextLeafIndex: checkpoint.checkpoint.archive.nextAvailableLeafIndex,
1095
+ });
1096
+ }
1097
+ lastRetrievedCheckpoint = validCheckpoints.at(-1) ?? lastRetrievedCheckpoint;
1098
+ lastSeenCheckpoint = publishedCheckpoints.at(-1) ?? lastSeenCheckpoint;
1099
+ } while (searchEndBlock < currentL1BlockNumber);
1100
+
1101
+ // Important that we update AFTER inserting the blocks.
1102
+ await updateProvenCheckpoint();
1103
+
1104
+ return { ...rollupStatus, lastRetrievedCheckpoint, lastSeenCheckpoint };
1105
+ }
1106
+
1107
+ /**
1108
+ * Checks if a specific checkpoint matches a local pending entry, and if so, loads local data to build
1109
+ * a synthetic published checkpoint (skipping blob fetch).
1110
+ *
1111
+ * Returns { diverged: true, fromCheckpointNumber } when the L1 checkpoint does NOT match local pending
1112
+ * data for that number, so the caller can evict the entire pending suffix >= fromCheckpointNumber
1113
+ * (those entries chain off the now-invalid local state) within the same addCheckpoints transaction.
1114
+ */
1115
+ private async tryBuildPublishedCheckpointFromProposed(
1116
+ calldataCheckpoint: RetrievedCheckpointFromCalldata | undefined,
1117
+ ): Promise<PublishedCheckpoint | { diverged: true; fromCheckpointNumber: CheckpointNumber } | undefined> {
1118
+ if (this.config.skipPromoteProposedCheckpointDuringL1Sync || !calldataCheckpoint) {
1119
+ return undefined;
1120
+ }
1121
+
1122
+ // Look up the specific pending entry for the checkpoint being mined, not just the tip
1123
+ const proposed = await this.stores.blocks.getProposedCheckpointByNumber(calldataCheckpoint.checkpointNumber);
1124
+ if (!proposed) {
1125
+ return undefined;
1126
+ }
1127
+
1128
+ if (
1129
+ !proposed.header.equals(calldataCheckpoint.header) ||
1130
+ !proposed.archive.root.equals(calldataCheckpoint.archiveRoot)
1131
+ ) {
1132
+ this.log.warn(
1133
+ `Local proposed checkpoint ${proposed.checkpointNumber} does not match checkpoint retrieved from L1, overriding with L1 data`,
1134
+ {
1135
+ proposedCheckpointNumber: proposed.checkpointNumber,
1136
+ proposedHeader: proposed.header.toInspect(),
1137
+ proposedArchiveRoot: proposed.archive.root.toString(),
1138
+ calldataCheckpointNumber: calldataCheckpoint.checkpointNumber,
1139
+ calldataHeader: calldataCheckpoint.header.toInspect(),
1140
+ calldataArchiveRoot: calldataCheckpoint.archiveRoot.toString(),
1141
+ },
1142
+ );
1143
+ // Both the locally-proposed checkpoint and the L1-confirmed one are signed by the
1144
+ // slot proposer; emit a divergence event so the slasher can attribute equivocation.
1145
+ // Only emit when the slots match — uncheckpointed entries are pruned above so this
1146
+ // should always hold, but guard defensively to avoid mis-attributing a slash.
1147
+ if (proposed.header.slotNumber === calldataCheckpoint.header.slotNumber) {
1148
+ this.events.emit(L2BlockSourceEvents.CheckpointEquivocationDetected, {
1149
+ type: L2BlockSourceEvents.CheckpointEquivocationDetected,
1150
+ slotNumber: calldataCheckpoint.header.slotNumber,
1151
+ checkpointNumber: calldataCheckpoint.checkpointNumber,
1152
+ l1ArchiveRoot: calldataCheckpoint.archiveRoot,
1153
+ proposedArchiveRoot: proposed.archive.root,
1154
+ });
1155
+ }
1156
+ // Return a divergence signal so the caller can evict pending >= this number
1157
+ return { diverged: true, fromCheckpointNumber: proposed.checkpointNumber };
1158
+ }
1159
+
1160
+ this.log.debug(
1161
+ `Building published checkpoint from proposed ${calldataCheckpoint.checkpointNumber} (skipping blob fetch)`,
1162
+ { proposedHeader: proposed.header.toInspect(), proposedArchiveRoot: proposed.archive.root.toString() },
1163
+ );
1164
+
1165
+ const blocks = await this.stores.blocks.getBlocks({
1166
+ from: BlockNumber(proposed.startBlock),
1167
+ limit: proposed.blockCount,
1168
+ });
1169
+ if (blocks.length !== proposed.blockCount) {
1170
+ this.log.warn(
1171
+ `Local proposed checkpoint ${proposed.checkpointNumber} has wrong block count (expected ${proposed.blockCount} blocks starting at ${proposed.startBlock} but got ${blocks.length})`,
1172
+ {
1173
+ proposedCheckpointNumber: proposed.checkpointNumber,
1174
+ proposedStartBlock: proposed.startBlock,
1175
+ proposedBlockCount: proposed.blockCount,
1176
+ retrievedBlocks: blocks.map(b => b.number),
1177
+ },
1178
+ );
1179
+ return undefined;
1180
+ }
1181
+
1182
+ const checkpoint = Checkpoint.from({
1183
+ archive: proposed.archive,
1184
+ header: proposed.header,
1185
+ blocks,
1186
+ number: proposed.checkpointNumber,
1187
+ feeAssetPriceModifier: proposed.feeAssetPriceModifier,
1188
+ });
1189
+ const promotedCheckpoint = PublishedCheckpoint.from({
1190
+ checkpoint,
1191
+ l1: calldataCheckpoint.l1,
1192
+ attestations: calldataCheckpoint.attestations,
1193
+ });
1194
+ this.instrumentation.processCheckpointPromoted();
1195
+
1196
+ return promotedCheckpoint;
1197
+ }
1198
+
1199
+ private async checkForNewCheckpointsBeforeL1SyncPoint(
1200
+ status: RollupStatus,
1201
+ blocksSynchedTo: bigint,
1202
+ currentL1BlockNumber: bigint,
1203
+ ): Promise<void> {
1204
+ const { lastSeenCheckpoint, pendingCheckpointNumber } = status;
1205
+ // Compare the last checkpoint (valid or not) we have (either retrieved in this round or loaded from store)
1206
+ // with what the rollup contract told us was the latest one (pinned at the currentL1BlockNumber).
1207
+ const latestLocalCheckpointNumber =
1208
+ lastSeenCheckpoint?.checkpoint.number ??
1209
+ CheckpointNumber.max(
1210
+ await this.stores.blocks.getLatestCheckpointNumber(),
1211
+ await this.stores.blocks.getLatestRejectedCheckpointNumber(),
1212
+ ) ??
1213
+ CheckpointNumber.ZERO;
1214
+
1215
+ if (latestLocalCheckpointNumber < pendingCheckpointNumber) {
1216
+ // Here we have consumed all logs until the `currentL1Block` we pinned at the beginning of the archiver loop,
1217
+ // but still haven't reached the pending checkpoint according to the call to the rollup contract.
1218
+ // We suspect an L1 reorg that added checkpoints *behind* us. If that is the case, it must have happened between
1219
+ // the last checkpoint we saw and the current one, so we reset the last synched L1 block number. In the edge case
1220
+ // we don't have one, we go back 2 L1 epochs, which is the deepest possible reorg (assuming Casper is working).
1221
+ const latestLocalCheckpoint: PublishedCheckpoint | CheckpointData | RejectedCheckpoint | undefined =
1222
+ lastSeenCheckpoint ??
1223
+ (await this.stores.blocks.getCheckpointData(latestLocalCheckpointNumber)) ??
1224
+ (await this.stores.blocks.getRejectedCheckpointByNumber(latestLocalCheckpointNumber));
1225
+
1226
+ const targetL1BlockNumber =
1227
+ latestLocalCheckpoint?.l1.blockNumber ??
1228
+ maxBigint(currentL1BlockNumber - 64n, this.l1Constants.l1StartBlock, 0n);
1229
+
1230
+ this.log.warn(
1231
+ `Failed to reach checkpoint ${pendingCheckpointNumber} at ${currentL1BlockNumber} (latest is ${latestLocalCheckpointNumber}). ` +
1232
+ `Rolling back last synched L1 block number to ${targetL1BlockNumber}.`,
1233
+ {
1234
+ latestLocalCheckpointNumber,
1235
+ latestLocalCheckpointL1: latestLocalCheckpoint?.l1,
1236
+ blocksSynchedTo,
1237
+ currentL1BlockNumber,
1238
+ ...status,
1239
+ },
1240
+ );
1241
+ await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
1242
+ } else {
1243
+ this.log.trace(`No new checkpoints behind L1 sync point to retrieve.`, {
1244
+ latestLocalCheckpointNumber,
1245
+ pendingCheckpointNumber,
1246
+ });
1247
+ }
1248
+ }
1249
+
1250
+ private async getCheckpointHeader(number: CheckpointNumber) {
1251
+ const checkpoint = await this.stores.blocks.getCheckpointData(number);
1252
+ if (!checkpoint) {
1253
+ return undefined;
1254
+ }
1255
+ return checkpoint.header;
1256
+ }
1257
+ }