@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,681 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { EpochCache } from '@aztec/epoch-cache';
3
+ import { BlockTagTooOldError, RollupContract } from '@aztec/ethereum/contracts';
4
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
5
+ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
7
+ import { Buffer32 } from '@aztec/foundation/buffer';
8
+ import { merge, pick } from '@aztec/foundation/collection';
9
+ import { Fr } from '@aztec/foundation/curves/bn254';
10
+ import { EthAddress } from '@aztec/foundation/eth-address';
11
+ import { type Logger, createLogger } from '@aztec/foundation/log';
12
+ import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
13
+ import { RunningPromise, makeLoggingErrorHandler } from '@aztec/foundation/running-promise';
14
+ import { DateProvider, elapsed } from '@aztec/foundation/timer';
15
+ import {
16
+ type ArchiverEmitter,
17
+ type BlockHash,
18
+ L2Block,
19
+ type L2BlockSink,
20
+ L2BlockSourceEvents,
21
+ type L2Tips,
22
+ type ValidateCheckpointResult,
23
+ } from '@aztec/stdlib/block';
24
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
25
+ import {
26
+ type L1RollupConstants,
27
+ getEpochAtSlot,
28
+ getSlotAtNextL1Block,
29
+ getSlotRangeForEpoch,
30
+ getTimestampForSlot,
31
+ getTimestampRangeForEpoch,
32
+ } from '@aztec/stdlib/epoch-helpers';
33
+ import type { BlockHeader } from '@aztec/stdlib/tx';
34
+ import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
35
+
36
+ import { type ArchiverConfig, mapArchiverConfig } from './config.js';
37
+ import { BlockAlreadyCheckpointedError, BlockOrCheckpointSlotExpiredError, NoBlobBodiesFoundError } from './errors.js';
38
+ import { validateAndLogHistoricalLogsAvailability } from './l1/validate_historical_logs.js';
39
+ import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
40
+ import { ArchiverDataSourceBase } from './modules/data_source_base.js';
41
+ import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
42
+ import type { ArchiverInstrumentation } from './modules/instrumentation.js';
43
+ import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
44
+ import { type ArchiverDataStores, backupArchiverDataStores, getArchiverSynchPoint } from './store/data_stores.js';
45
+ import { L2TipsCache } from './store/l2_tips_cache.js';
46
+
47
+ /** Export ArchiverEmitter for use in factory and tests. */
48
+ export type { ArchiverEmitter };
49
+
50
+ /** Request to add a block to the archiver, queued for processing by the sync loop. */
51
+ type AddBlockRequest = {
52
+ type: 'block';
53
+ block: L2Block;
54
+ resolve: () => void;
55
+ reject: (err: Error) => void;
56
+ };
57
+
58
+ /** Request to add a proposed checkpoint to the archiver, queued for processing by the sync loop. */
59
+ type AddProposedCheckpointRequest = {
60
+ type: 'checkpoint';
61
+ checkpoint: ProposedCheckpointInput;
62
+ resolve: () => void;
63
+ reject: (err: Error) => void;
64
+ };
65
+
66
+ export type ArchiverDeps = {
67
+ telemetry?: TelemetryClient;
68
+ blobClient: BlobClientInterface;
69
+ epochCache?: EpochCache;
70
+ dateProvider?: DateProvider;
71
+ };
72
+
73
+ /**
74
+ * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
75
+ * Responsible for handling robust L1 polling so that other components do not need to
76
+ * concern themselves with it.
77
+ */
78
+ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Traceable {
79
+ /** Event emitter for archiver events (L2BlockProven, L2PruneUnproven, L2PruneUncheckpointed, etc). */
80
+ public readonly events: ArchiverEmitter;
81
+
82
+ /** A loop in which we will be continually fetching new checkpoints. */
83
+ protected runningPromise: RunningPromise;
84
+
85
+ /** L1 synchronizer that handles fetching checkpoints and messages from L1. */
86
+ private readonly synchronizer: ArchiverL1Synchronizer;
87
+
88
+ private initialSyncComplete: boolean = false;
89
+ private initialSyncPromise: PromiseWithResolvers<void>;
90
+
91
+ /** Queue of blocks and checkpoints to be added to the store, processed by the sync loop. */
92
+ private inboundQueue: (AddBlockRequest | AddProposedCheckpointRequest)[] = [];
93
+
94
+ /** Helper to handle updates to the store */
95
+ private readonly updater: ArchiverDataStoreUpdater;
96
+
97
+ /** In-memory cache for L2 chain tips. */
98
+ private readonly l2TipsCache: L2TipsCache;
99
+
100
+ public readonly tracer: Tracer;
101
+
102
+ private readonly instrumentation: ArchiverInstrumentation;
103
+
104
+ /**
105
+ * Creates a new instance of the Archiver.
106
+ * @param publicClient - A client for interacting with the Ethereum node.
107
+ * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
108
+ * @param rollup - Rollup contract instance.
109
+ * @param inbox - Inbox contract instance.
110
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
111
+ * @param dataStores - Archiver substores for storage & retrieval of blocks, encrypted logs & contract data.
112
+ * @param config - Archiver configuration options.
113
+ * @param blobClient - Client for retrieving blob data.
114
+ * @param instrumentation - Instrumentation for metrics and tracing.
115
+ * @param l1Constants - L1 rollup constants.
116
+ * @param synchronizer - L1 synchronizer that handles fetching checkpoints and messages from L1.
117
+ * @param events - Event emitter shared with the synchronizer.
118
+ * @param initialHeader - Genesis block header.
119
+ * @param initialBlockHash - Precomputed hash of the genesis block header.
120
+ * @param l2TipsCache - In-memory cache for L2 chain tips.
121
+ * @param epochCache - Cache used to compute the proposer pipelining offset.
122
+ * @param dateProvider - Provider for current date/time, used for wall-clock orphan-block pruning.
123
+ * @param log - A logger.
124
+ */
125
+ constructor(
126
+ private readonly publicClient: ViemPublicClient,
127
+ private readonly debugClient: ViemPublicDebugClient,
128
+ private readonly rollup: RollupContract,
129
+ private readonly l1Addresses: Pick<
130
+ L1ContractAddresses,
131
+ 'rollupAddress' | 'registryAddress' | 'inboxAddress' | 'governanceProposerAddress'
132
+ > & {
133
+ slashingProposerAddress: EthAddress;
134
+ },
135
+ readonly dataStores: ArchiverDataStores,
136
+ private config: {
137
+ pollingIntervalMs: number;
138
+ batchSize: number;
139
+ skipValidateCheckpointAttestations?: boolean;
140
+ maxAllowedEthClientDriftSeconds: number;
141
+ ethereumAllowNoDebugHosts?: boolean;
142
+ skipHistoricalLogsCheck?: boolean;
143
+ orphanProposedBlockPruneGraceSeconds: number;
144
+ },
145
+ private readonly blobClient: BlobClientInterface,
146
+ instrumentation: ArchiverInstrumentation,
147
+ protected override readonly l1Constants: L1RollupConstants & {
148
+ l1StartBlockHash: Buffer32;
149
+ genesisArchiveRoot: Fr;
150
+ },
151
+ synchronizer: ArchiverL1Synchronizer,
152
+ events: ArchiverEmitter,
153
+ initialHeader: BlockHeader,
154
+ initialBlockHash: BlockHash,
155
+ l2TipsCache: L2TipsCache,
156
+ private readonly epochCache: EpochCache,
157
+ private readonly dateProvider: DateProvider,
158
+ private readonly log: Logger = createLogger('archiver'),
159
+ ) {
160
+ super(dataStores, l1Constants, initialHeader, initialBlockHash, l1Constants.genesisArchiveRoot);
161
+
162
+ this.tracer = instrumentation.tracer;
163
+ this.instrumentation = instrumentation;
164
+ this.initialSyncPromise = promiseWithResolvers();
165
+ this.synchronizer = synchronizer;
166
+ this.events = events;
167
+ this.l2TipsCache = l2TipsCache;
168
+ this.updater = new ArchiverDataStoreUpdater(this.dataStores, this.l2TipsCache, {
169
+ rollupManaLimit: l1Constants.rollupManaLimit,
170
+ });
171
+
172
+ // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
173
+ // are done as fast as possible. This then gets updated once the initial sync completes.
174
+ this.runningPromise = new RunningPromise(
175
+ () => this.sync(),
176
+ this.log,
177
+ this.config.pollingIntervalMs / 10,
178
+ makeLoggingErrorHandler(this.log, NoBlobBodiesFoundError, BlockTagTooOldError),
179
+ );
180
+ }
181
+
182
+ /** Updates archiver config */
183
+ public updateConfig(newConfig: Partial<ArchiverConfig>) {
184
+ this.config = merge(this.config, mapArchiverConfig(newConfig));
185
+ this.synchronizer.setConfig(this.config);
186
+ }
187
+
188
+ /**
189
+ * Starts sync process.
190
+ * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
191
+ */
192
+ public async start(blockUntilSynced: boolean): Promise<void> {
193
+ if (this.runningPromise.isRunning()) {
194
+ throw new Error('Archiver is already running');
195
+ }
196
+
197
+ await this.blobClient.testSources();
198
+ await this.synchronizer.testEthereumNodeSynced();
199
+ await validateAndLogTraceAvailability(
200
+ this.debugClient,
201
+ this.config.ethereumAllowNoDebugHosts ?? false,
202
+ this.log.getBindings(),
203
+ );
204
+ await validateAndLogHistoricalLogsAvailability(
205
+ this.publicClient,
206
+ {
207
+ rollupAddress: this.l1Addresses.rollupAddress,
208
+ inboxAddress: this.l1Addresses.inboxAddress,
209
+ registryAddress: this.l1Addresses.registryAddress,
210
+ governanceProposerAddress: this.l1Addresses.governanceProposerAddress,
211
+ },
212
+ this.config.skipHistoricalLogsCheck ?? false,
213
+ this.log.getBindings(),
214
+ );
215
+
216
+ // Log initial state for the archiver
217
+ const { l1StartBlock } = this.l1Constants;
218
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await getArchiverSynchPoint(
219
+ this.stores,
220
+ );
221
+ const currentL2Checkpoint = await this.getCheckpointNumber();
222
+ this.log.info(
223
+ `Starting archiver sync to rollup contract ${this.rollup.address} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`,
224
+ { blocksSynchedTo, messagesSynchedTo, currentL2Checkpoint },
225
+ );
226
+
227
+ // Start sync loop, and return the wait for initial sync if we are asked to block until synced
228
+ this.runningPromise.start();
229
+ if (blockUntilSynced) {
230
+ return this.waitForInitialSync();
231
+ }
232
+ }
233
+
234
+ public syncImmediate() {
235
+ return this.runningPromise.trigger();
236
+ }
237
+
238
+ public trySyncImmediate() {
239
+ try {
240
+ return this.syncImmediate();
241
+ } catch (err) {
242
+ this.log.error(`Failed to trigger immediate archiver sync: ${err}`, err);
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Queues a block to be added to the archiver store and triggers processing.
248
+ * The block will be processed by the sync loop.
249
+ * Implements the L2BlockSink interface.
250
+ * @param block - The L2 block to add.
251
+ * @returns A promise that resolves when the block has been added to the store, or rejects on error.
252
+ */
253
+ public addBlock(block: L2Block): Promise<void> {
254
+ const promise = promiseWithResolvers<void>();
255
+ this.inboundQueue.push({ block, ...promise, type: 'block' });
256
+ this.log.debug(`Queued block ${block.number} for processing`);
257
+ void this.trySyncImmediate();
258
+ return promise.promise;
259
+ }
260
+
261
+ /**
262
+ * Queues a new proposed checkpoint into the archiver store.
263
+ * Checks that the checkpoint is not for an L2 slot already synced from L1.
264
+ * Resolves once the checkpoint has been processed.
265
+ */
266
+ public addProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
267
+ const promise = promiseWithResolvers<void>();
268
+ this.inboundQueue.push({ checkpoint: pending, ...promise, type: 'checkpoint' });
269
+ this.log.debug(`Queued checkpoint ${pending.checkpointNumber} for processing`);
270
+ void this.trySyncImmediate();
271
+ return promise.promise;
272
+ }
273
+
274
+ /**
275
+ * Processes all queued blocks and checkpoints, adding them to the store.
276
+ * Called at the beginning of each sync iteration.
277
+ * Items are processed in the order they were queued.
278
+ */
279
+ private async processInboundQueue(): Promise<void> {
280
+ if (this.inboundQueue.length === 0) {
281
+ return;
282
+ }
283
+
284
+ // Take all items from the queue
285
+ const queuedItems = this.inboundQueue.splice(0, this.inboundQueue.length);
286
+ this.log.debug(`Processing ${queuedItems.length} queued inbound items`);
287
+
288
+ // Calculate slot threshold for validation
289
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
290
+ const slotAtNextL1Block =
291
+ l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
292
+
293
+ // Helpers for manipulating blocks and checkpoints in the queue
294
+ const getSlot: (item: AddBlockRequest | AddProposedCheckpointRequest) => SlotNumber = item =>
295
+ item.type === 'block' ? item.block.header.globalVariables.slotNumber : item.checkpoint.header.slotNumber;
296
+ const getNumber: (item: AddBlockRequest | AddProposedCheckpointRequest) => number = item =>
297
+ item.type === 'block' ? item.block.number : item.checkpoint.checkpointNumber;
298
+
299
+ // Process each item individually to properly resolve/reject each promise
300
+ for (const item of queuedItems) {
301
+ const { resolve, reject, type } = item;
302
+ const itemSlot = getSlot(item);
303
+ const itemNumber = getNumber(item);
304
+ if (slotAtNextL1Block !== undefined && itemSlot < slotAtNextL1Block) {
305
+ const nextSlotTimestamp = getTimestampForSlot(slotAtNextL1Block, this.l1Constants);
306
+ this.log.warn(
307
+ `Rejecting proposed ${type} ${itemNumber} for past slot ${itemSlot} (current ${slotAtNextL1Block})`,
308
+ { number: itemNumber, type, l1Timestamp, slotAtNextL1Block, nextSlotTimestamp },
309
+ );
310
+ reject(new BlockOrCheckpointSlotExpiredError(itemSlot, nextSlotTimestamp, l1Timestamp));
311
+ continue;
312
+ }
313
+
314
+ try {
315
+ if (type === 'block') {
316
+ const [durationMs] = await elapsed(() => this.updater.addProposedBlock(item.block));
317
+ this.instrumentation.processNewProposedBlock(durationMs, item.block);
318
+ } else {
319
+ await this.updater.addProposedCheckpoint(item.checkpoint);
320
+ }
321
+ this.log.debug(`Added ${type} ${itemNumber} to store`);
322
+ resolve();
323
+ } catch (err: any) {
324
+ if (err instanceof BlockAlreadyCheckpointedError) {
325
+ this.log.debug(`Proposed block ${itemNumber} matches already checkpointed block, ignoring late proposal`);
326
+ resolve();
327
+ continue;
328
+ }
329
+ this.log.error(`Failed to add ${type} ${itemNumber} to store: ${err.message}`, err, {
330
+ number: itemNumber,
331
+ type,
332
+ });
333
+ reject(err);
334
+ }
335
+ }
336
+ }
337
+
338
+ public waitForInitialSync() {
339
+ return this.initialSyncPromise.promise;
340
+ }
341
+
342
+ /**
343
+ * Fetches logs from L1 contracts and processes them.
344
+ */
345
+ @trackSpan('Archiver.sync')
346
+ private async sync() {
347
+ // Process any queued blocks first, before doing L1 sync
348
+ await this.processInboundQueue();
349
+ // Now perform L1 sync
350
+ await this.syncFromL1();
351
+ // Prune proposed blocks with no corresponding proposed checkpoint by the end of their build slot.
352
+ await this.pruneOrphanProposedBlocks();
353
+ }
354
+
355
+ /**
356
+ * Prunes a block-only local tip that was built atop a checkpoint that was never itself proposed.
357
+ *
358
+ * Under pipelining, a proposer publishes the blocks for a checkpoint (block-only proposals) before
359
+ * assembling and publishing the enclosing proposed checkpoint at the end of the build slot. A node
360
+ * that received those blocks but never the proposed checkpoint is left with an orphan tip it must
361
+ * not build on. We prune it once enough wall-clock time has elapsed that the proposed checkpoint
362
+ * should have arrived. This runs on wall-clock time (not L1 block advancement) so it fires during
363
+ * quiet L1 periods, and is the liveness counterpart to the sequencer's checkSync guard.
364
+ *
365
+ * The uncheckpointed suffix is scanned in order. Blocks covered by proposed checkpoints are left in
366
+ * place; the first block not covered by a proposed checkpoint starts the orphan suffix to prune.
367
+ */
368
+ private async pruneOrphanProposedBlocks(): Promise<void> {
369
+ const tips = await this.getL2Tips();
370
+ const now = BigInt(this.dateProvider.nowInSeconds());
371
+ const pipeliningOffset = this.epochCache.pipeliningOffset();
372
+
373
+ // This only applies under pipelining
374
+ if (pipeliningOffset === 0) {
375
+ this.log.trace(`Pipelining offset is 0, skipping orphan proposed block pruning`);
376
+ return;
377
+ }
378
+
379
+ // The proposed tip is a proposed-checkpointed block, so there are no orphan proposed blocks to prune
380
+ if (tips.proposedCheckpoint.block.number === tips.proposed.number) {
381
+ this.log.trace(
382
+ `No orphan proposed blocks to prune: proposed tip ${tips.proposed.number} is checkpointed`,
383
+ pick(tips, 'proposed', 'proposedCheckpoint'),
384
+ );
385
+ return;
386
+ }
387
+
388
+ // Load the blocks that are candidates for pruning (ie blocks without a proposed checkpoint covering them)
389
+ const blocksWithoutProposedCheckpoint = await this.stores.blocks.getBlocksData({
390
+ from: BlockNumber(tips.proposedCheckpoint.block.number + 1),
391
+ limit: tips.proposed.number - tips.proposedCheckpoint.block.number,
392
+ });
393
+
394
+ // Iterate through them in order, the first one with a slot that should have received a proposed checkpoint
395
+ // is the first orphan block, and all blocks after it are also orphaned and should be pruned.
396
+ let lastSlotChecked = undefined;
397
+ for (const blockData of blocksWithoutProposedCheckpoint) {
398
+ // No need to recheck if this block had the same slot as the previous one.
399
+ const blockSlot = blockData.header.getSlot();
400
+ const blockNumber = blockData.header.getBlockNumber();
401
+ if (lastSlotChecked !== undefined && blockSlot === lastSlotChecked) {
402
+ continue;
403
+ }
404
+ lastSlotChecked = blockSlot;
405
+
406
+ // The proposed checkpoint should have landed by the start of the slot after the block's build slot
407
+ // (build slot = blockSlot - pipeliningOffset). Wait a grace period beyond that to tolerate propagation.
408
+ const expectedCheckpointedBySlot = SlotNumber(Number(blockSlot) - pipeliningOffset + 1);
409
+ const expectedCheckpointedByTime =
410
+ getTimestampForSlot(expectedCheckpointedBySlot, this.l1Constants) +
411
+ BigInt(this.config.orphanProposedBlockPruneGraceSeconds);
412
+
413
+ // If it's not checkpointed by the expected time, prune it along with all blocks after it.
414
+ if (now >= expectedCheckpointedByTime) {
415
+ const pruneAfterBlockNumber = BlockNumber(blockNumber - 1);
416
+ this.log.warn(
417
+ `Pruning orphan blocks after block ${pruneAfterBlockNumber}: block at slot ${blockSlot} belongs to ` +
418
+ `checkpoint ${blockData.checkpointNumber} which has no matching proposed checkpoint`,
419
+ {
420
+ firstUncheckpointedBlockHeader: blockData.header.toInspect(),
421
+ blockCheckpointNumber: blockData.checkpointNumber,
422
+ blockNumber,
423
+ blockSlot,
424
+ pipeliningOffset,
425
+ expectedCheckpointedBySlot,
426
+ expectedCheckpointedByTime,
427
+ now,
428
+ },
429
+ );
430
+
431
+ const prunedBlocks = await this.updater.removeBlocksWithoutProposedCheckpointAfter(pruneAfterBlockNumber);
432
+ if (prunedBlocks.length > 0) {
433
+ this.events.emit(L2BlockSourceEvents.L2PruneUncheckpointed, {
434
+ type: L2BlockSourceEvents.L2PruneUncheckpointed,
435
+ slotNumber: blockSlot,
436
+ blocks: prunedBlocks,
437
+ });
438
+ }
439
+ return;
440
+ }
441
+ }
442
+
443
+ this.log.trace('No orphan proposed blocks to prune: all uncheckpointed blocks are still within the grace period', {
444
+ blocksWithoutProposedCheckpoint: blocksWithoutProposedCheckpoint.map(b => b.header.toInspect()),
445
+ });
446
+ }
447
+
448
+ private async syncFromL1() {
449
+ // Delegate to the L1 synchronizer
450
+ await this.synchronizer.syncFromL1(this.initialSyncComplete);
451
+
452
+ // Check if we've completed initial sync
453
+ const currentL1BlockNumber = this.synchronizer.getL1BlockNumber();
454
+ if (currentL1BlockNumber !== undefined && !this.initialSyncComplete) {
455
+ const l1BlockNumberAtEnd = await this.publicClient.getBlockNumber();
456
+ if (currentL1BlockNumber + 1n >= l1BlockNumberAtEnd) {
457
+ this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
458
+ l1BlockNumber: currentL1BlockNumber,
459
+ syncPoint: await getArchiverSynchPoint(this.stores),
460
+ ...(await this.getL2Tips()),
461
+ });
462
+ this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
463
+ this.initialSyncComplete = true;
464
+ this.initialSyncPromise.resolve();
465
+ }
466
+ }
467
+ }
468
+
469
+ /** Resumes the archiver after a stop. */
470
+ public resume() {
471
+ if (this.runningPromise.isRunning()) {
472
+ this.log.warn(`Archiver already running`);
473
+ }
474
+ this.log.info(`Restarting archiver`);
475
+ this.runningPromise.start();
476
+ }
477
+
478
+ /**
479
+ * Stops the archiver.
480
+ * @returns A promise signalling completion of the stop process.
481
+ */
482
+ public async stop(): Promise<void> {
483
+ this.log.debug('Stopping...');
484
+ await this.runningPromise.stop();
485
+
486
+ this.log.info('Stopped.');
487
+ return Promise.resolve();
488
+ }
489
+
490
+ public backupTo(destPath: string): Promise<string> {
491
+ return backupArchiverDataStores(this.dataStores, destPath);
492
+ }
493
+
494
+ public getL1Constants(): Promise<L1RollupConstants> {
495
+ return Promise.resolve(this.l1Constants);
496
+ }
497
+
498
+ public getGenesisValues(): Promise<{ genesisArchiveRoot: Fr }> {
499
+ return Promise.resolve({ genesisArchiveRoot: this.l1Constants.genesisArchiveRoot });
500
+ }
501
+
502
+ public getRollupAddress(): Promise<EthAddress> {
503
+ return Promise.resolve(EthAddress.fromString(this.rollup.address));
504
+ }
505
+
506
+ public getRegistryAddress(): Promise<EthAddress> {
507
+ return Promise.resolve(this.l1Addresses.registryAddress);
508
+ }
509
+
510
+ public getL1BlockNumber(): bigint | undefined {
511
+ return this.synchronizer.getL1BlockNumber();
512
+ }
513
+
514
+ public getL1Timestamp(): Promise<bigint | undefined> {
515
+ return Promise.resolve(this.synchronizer.getL1Timestamp());
516
+ }
517
+
518
+ public async getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
519
+ // The synced L2 slot is the latest slot for which we have all L1 data,
520
+ // either because we have seen all L1 blocks for that slot, or because
521
+ // we have seen the corresponding checkpoint.
522
+
523
+ let slotFromL1Sync: SlotNumber | undefined;
524
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
525
+ if (l1Timestamp !== undefined) {
526
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
527
+ if (Number(nextL1BlockSlot) > 0) {
528
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
529
+ }
530
+ }
531
+
532
+ let slotFromCheckpoint: SlotNumber | undefined;
533
+ const latestCheckpointNumber = await this.stores.blocks.getLatestCheckpointNumber();
534
+ if (latestCheckpointNumber > 0) {
535
+ const checkpointData = await this.stores.blocks.getCheckpointData(latestCheckpointNumber);
536
+ if (checkpointData) {
537
+ slotFromCheckpoint = checkpointData.header.slotNumber;
538
+ }
539
+ }
540
+
541
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
542
+ return undefined;
543
+ }
544
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
545
+ }
546
+
547
+ public async getSyncedL2EpochNumber(): Promise<EpochNumber | undefined> {
548
+ const syncedSlot = await this.getSyncedL2SlotNumber();
549
+ if (syncedSlot === undefined) {
550
+ return undefined;
551
+ }
552
+ // An epoch is fully synced when all its slots are synced.
553
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
554
+ // Otherwise, only the previous epoch is fully synced.
555
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
556
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
557
+ if (syncedSlot >= endSlot) {
558
+ return epoch;
559
+ }
560
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
561
+ }
562
+
563
+ public async isEpochComplete(epochNumber: EpochNumber): Promise<boolean> {
564
+ // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
565
+ // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
566
+ // prematurely when proposed blocks have been pushed to the archiver but not yet checkpointed on L1.
567
+ const header = (await this.getBlockData({ tag: 'checkpointed' }))?.header;
568
+ const slot = header ? header.globalVariables.slotNumber : undefined;
569
+ const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
570
+ if (slot && slot >= endSlot) {
571
+ return true;
572
+ }
573
+
574
+ // If we haven't run an initial sync, just return false.
575
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
576
+ if (l1Timestamp === undefined) {
577
+ return false;
578
+ }
579
+
580
+ // If not, the epoch may also be complete if the L2 slot has passed without a block
581
+ // We compute this based on the end timestamp for the given epoch and the timestamp of the last L1 block
582
+ const [_startTimestamp, endTimestamp] = getTimestampRangeForEpoch(epochNumber, this.l1Constants);
583
+
584
+ // For this computation, we throw in a few extra seconds just for good measure,
585
+ // since we know the next L1 block won't be mined within this range. Remember that
586
+ // l1timestamp is the timestamp of the last l1 block we've seen, so this relies on
587
+ // the fact that L1 won't mine two blocks within this time of each other.
588
+ // TODO(palla/reorg): Is the above a safe assumption?
589
+ const leeway = 1n;
590
+ return l1Timestamp + leeway >= endTimestamp;
591
+ }
592
+
593
+ /** Returns whether the archiver has completed an initial sync run successfully. */
594
+ public isInitialSyncComplete(): boolean {
595
+ return this.initialSyncComplete;
596
+ }
597
+
598
+ public removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
599
+ return this.updater.removeCheckpointsAfter(checkpointNumber);
600
+ }
601
+
602
+ /** Used by TXE to add checkpoints directly without syncing from L1. */
603
+ public async addCheckpoints(
604
+ checkpoints: PublishedCheckpoint[],
605
+ pendingChainValidationStatus?: ValidateCheckpointResult,
606
+ ): Promise<boolean> {
607
+ await this.updater.addCheckpoints(checkpoints, pendingChainValidationStatus);
608
+ return true;
609
+ }
610
+
611
+ public getL2Tips(): Promise<L2Tips> {
612
+ return this.l2TipsCache.getL2Tips();
613
+ }
614
+
615
+ public async rollbackTo(targetL2BlockNumber: BlockNumber): Promise<void> {
616
+ const currentBlocks = await this.getL2Tips();
617
+ const currentL2Block = currentBlocks.proposed.number;
618
+ const currentProvenBlock = currentBlocks.proven.block.number;
619
+
620
+ if (targetL2BlockNumber >= currentL2Block) {
621
+ throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
622
+ }
623
+ const checkpointedTip = await this.stores.blocks.getCheckpointedL2BlockNumber();
624
+ if (targetL2BlockNumber > checkpointedTip) {
625
+ throw new Error(`Target L2 block ${targetL2BlockNumber} is not checkpointed yet`);
626
+ }
627
+ const targetBlockData = await this.stores.blocks.getBlockData({ number: targetL2BlockNumber });
628
+ if (!targetBlockData) {
629
+ throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
630
+ }
631
+ const targetCheckpointNumber = targetBlockData.checkpointNumber;
632
+
633
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
634
+ const checkpointData = await this.stores.blocks.getCheckpointData(targetCheckpointNumber);
635
+ if (!checkpointData) {
636
+ throw new Error(`Checkpoint ${targetCheckpointNumber} not found for block ${targetL2BlockNumber}`);
637
+ }
638
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
639
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
640
+ const previousCheckpointBoundary =
641
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
642
+ throw new Error(
643
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
644
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
645
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
646
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
647
+ );
648
+ }
649
+
650
+ const targetL1BlockNumber = checkpointData.l1.blockNumber;
651
+ const targetL1Block = await this.publicClient.getBlock({
652
+ blockNumber: targetL1BlockNumber,
653
+ includeTransactions: false,
654
+ });
655
+ if (!targetL1Block) {
656
+ throw new Error(`Missing L1 block ${targetL1BlockNumber}`);
657
+ }
658
+ const targetL1BlockHash = Buffer32.fromString(targetL1Block.hash);
659
+ this.log.info(
660
+ `Removing checkpoints after checkpoint ${targetCheckpointNumber} (target block ${targetL2BlockNumber})`,
661
+ );
662
+ await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
663
+ this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
664
+ await this.stores.messages.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
665
+ this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
666
+ await this.stores.blocks.setSynchedL1BlockNumber(targetL1BlockNumber);
667
+ await this.stores.messages.setMessageSyncState(
668
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
669
+ undefined,
670
+ );
671
+ if (targetL2BlockNumber < currentProvenBlock) {
672
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
673
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
674
+ }
675
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
676
+ if (targetL2BlockNumber < currentFinalizedBlock) {
677
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
678
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
679
+ }
680
+ }
681
+ }