@aztec/archiver 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (218) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +147 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +788 -0
  5. package/dest/config.d.ts +32 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +83 -0
  8. package/dest/errors.d.ts +92 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +136 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +100 -15
  14. package/dest/index.d.ts +12 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -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/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  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 +408 -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}/data_retrieval.js +86 -165
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_historical_logs.d.ts +23 -0
  42. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  43. package/dest/l1/validate_historical_logs.js +108 -0
  44. package/dest/l1/validate_trace.d.ts +32 -0
  45. package/dest/l1/validate_trace.d.ts.map +1 -0
  46. package/dest/l1/validate_trace.js +154 -0
  47. package/dest/modules/data_source_base.d.ts +95 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +234 -0
  50. package/dest/modules/data_store_updater.d.ts +93 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +345 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/modules/instrumentation.js +143 -0
  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 +1265 -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 +13 -7
  62. package/dest/store/block_store.d.ts +262 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1048 -0
  65. package/dest/store/contract_class_store.d.ts +17 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +64 -0
  68. package/dest/store/contract_instance_store.d.ts +24 -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 +7 -3
  71. package/dest/store/kv_archiver_store.d.ts +401 -0
  72. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  73. package/dest/store/kv_archiver_store.js +525 -0
  74. package/dest/store/l2_tips_cache.d.ts +20 -0
  75. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  76. package/dest/store/l2_tips_cache.js +109 -0
  77. package/dest/store/log_store.d.ts +57 -0
  78. package/dest/store/log_store.d.ts.map +1 -0
  79. package/dest/store/log_store.js +531 -0
  80. package/dest/store/message_store.d.ts +44 -0
  81. package/dest/store/message_store.d.ts.map +1 -0
  82. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  83. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  84. package/dest/structs/data_retrieval.d.ts.map +1 -0
  85. package/dest/structs/inbox_message.d.ts +15 -0
  86. package/dest/structs/inbox_message.d.ts.map +1 -0
  87. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  88. package/dest/structs/published.d.ts +2 -0
  89. package/dest/structs/published.d.ts.map +1 -0
  90. package/dest/test/fake_l1_state.d.ts +214 -0
  91. package/dest/test/fake_l1_state.d.ts.map +1 -0
  92. package/dest/test/fake_l1_state.js +517 -0
  93. package/dest/test/index.d.ts +2 -1
  94. package/dest/test/index.d.ts.map +1 -1
  95. package/dest/test/index.js +4 -1
  96. package/dest/test/mock_archiver.d.ts +16 -8
  97. package/dest/test/mock_archiver.d.ts.map +1 -1
  98. package/dest/test/mock_archiver.js +19 -14
  99. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  100. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  101. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  102. package/dest/test/mock_l2_block_source.d.ts +68 -20
  103. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  104. package/dest/test/mock_l2_block_source.js +298 -85
  105. package/dest/test/mock_structs.d.ts +83 -4
  106. package/dest/test/mock_structs.d.ts.map +1 -1
  107. package/dest/test/mock_structs.js +157 -11
  108. package/dest/test/noop_l1_archiver.d.ts +26 -0
  109. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  110. package/dest/test/noop_l1_archiver.js +74 -0
  111. package/package.json +20 -20
  112. package/src/archiver.ts +566 -0
  113. package/src/{archiver/config.ts → config.ts} +51 -14
  114. package/src/errors.ts +213 -0
  115. package/src/factory.ts +155 -17
  116. package/src/index.ts +12 -3
  117. package/src/interfaces.ts +9 -0
  118. package/src/l1/README.md +55 -0
  119. package/src/l1/bin/retrieve-calldata.ts +194 -0
  120. package/src/l1/calldata_retriever.ts +523 -0
  121. package/src/{archiver → l1}/data_retrieval.ts +155 -247
  122. package/src/l1/debug_tx.ts +99 -0
  123. package/src/l1/spire_proposer.ts +152 -0
  124. package/src/l1/trace_tx.ts +128 -0
  125. package/src/l1/types.ts +13 -0
  126. package/src/l1/validate_historical_logs.ts +140 -0
  127. package/src/l1/validate_trace.ts +229 -0
  128. package/src/modules/data_source_base.ts +364 -0
  129. package/src/modules/data_store_updater.ts +465 -0
  130. package/src/modules/instrumentation.ts +204 -0
  131. package/src/modules/l1_synchronizer.ts +1126 -0
  132. package/src/{archiver → modules}/validation.ts +21 -15
  133. package/src/store/block_store.ts +1361 -0
  134. package/src/store/contract_class_store.ts +82 -0
  135. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  136. package/src/store/kv_archiver_store.ts +765 -0
  137. package/src/store/l2_tips_cache.ts +134 -0
  138. package/src/store/log_store.ts +733 -0
  139. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  140. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  141. package/src/{archiver/structs → structs}/published.ts +0 -1
  142. package/src/test/fake_l1_state.ts +770 -0
  143. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  144. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  145. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  146. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  147. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  148. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  149. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  150. package/src/test/index.ts +4 -0
  151. package/src/test/mock_archiver.ts +23 -16
  152. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  153. package/src/test/mock_l2_block_source.ts +367 -93
  154. package/src/test/mock_structs.ts +289 -13
  155. package/src/test/noop_l1_archiver.ts +117 -0
  156. package/dest/archiver/archiver.d.ts +0 -287
  157. package/dest/archiver/archiver.d.ts.map +0 -1
  158. package/dest/archiver/archiver.js +0 -1408
  159. package/dest/archiver/archiver_store.d.ts +0 -255
  160. package/dest/archiver/archiver_store.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store.js +0 -4
  162. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  163. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  164. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  165. package/dest/archiver/config.d.ts +0 -21
  166. package/dest/archiver/config.d.ts.map +0 -1
  167. package/dest/archiver/config.js +0 -55
  168. package/dest/archiver/data_retrieval.d.ts +0 -79
  169. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  170. package/dest/archiver/errors.d.ts +0 -12
  171. package/dest/archiver/errors.d.ts.map +0 -1
  172. package/dest/archiver/errors.js +0 -17
  173. package/dest/archiver/index.d.ts +0 -7
  174. package/dest/archiver/index.d.ts.map +0 -1
  175. package/dest/archiver/index.js +0 -4
  176. package/dest/archiver/instrumentation.d.ts +0 -35
  177. package/dest/archiver/instrumentation.d.ts.map +0 -1
  178. package/dest/archiver/instrumentation.js +0 -140
  179. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  180. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  181. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  182. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  183. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  185. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  186. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  188. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  189. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  190. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  191. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  192. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  193. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  194. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  195. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  196. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  197. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  198. package/dest/archiver/structs/published.d.ts +0 -3
  199. package/dest/archiver/structs/published.d.ts.map +0 -1
  200. package/dest/archiver/validation.d.ts +0 -17
  201. package/dest/archiver/validation.d.ts.map +0 -1
  202. package/dest/rpc/index.d.ts +0 -9
  203. package/dest/rpc/index.d.ts.map +0 -1
  204. package/dest/rpc/index.js +0 -15
  205. package/src/archiver/archiver.ts +0 -1858
  206. package/src/archiver/archiver_store.ts +0 -305
  207. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  208. package/src/archiver/errors.ts +0 -26
  209. package/src/archiver/index.ts +0 -6
  210. package/src/archiver/instrumentation.ts +0 -187
  211. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  212. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  213. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  214. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  215. package/src/rpc/index.ts +0 -16
  216. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  217. /package/dest/{archiver/structs → structs}/published.js +0 -0
  218. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,566 @@
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 } 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
+ L2Block,
18
+ type L2BlockSink,
19
+ type L2Tips,
20
+ type ValidateCheckpointResult,
21
+ } from '@aztec/stdlib/block';
22
+ import { type ProposedCheckpointInput, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
23
+ import {
24
+ type L1RollupConstants,
25
+ getEpochAtSlot,
26
+ getSlotAtNextL1Block,
27
+ getSlotRangeForEpoch,
28
+ getTimestampForSlot,
29
+ getTimestampRangeForEpoch,
30
+ } from '@aztec/stdlib/epoch-helpers';
31
+ import { type TelemetryClient, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
32
+
33
+ import { type ArchiverConfig, mapArchiverConfig } from './config.js';
34
+ import { BlockAlreadyCheckpointedError, BlockOrCheckpointSlotExpiredError, NoBlobBodiesFoundError } from './errors.js';
35
+ import { validateAndLogHistoricalLogsAvailability } from './l1/validate_historical_logs.js';
36
+ import { validateAndLogTraceAvailability } from './l1/validate_trace.js';
37
+ import { ArchiverDataSourceBase } from './modules/data_source_base.js';
38
+ import { ArchiverDataStoreUpdater } from './modules/data_store_updater.js';
39
+ import type { ArchiverInstrumentation } from './modules/instrumentation.js';
40
+ import type { ArchiverL1Synchronizer } from './modules/l1_synchronizer.js';
41
+ import type { KVArchiverDataStore } from './store/kv_archiver_store.js';
42
+ import { L2TipsCache } from './store/l2_tips_cache.js';
43
+
44
+ /** Export ArchiverEmitter for use in factory and tests. */
45
+ export type { ArchiverEmitter };
46
+
47
+ /** Request to add a block to the archiver, queued for processing by the sync loop. */
48
+ type AddBlockRequest = {
49
+ type: 'block';
50
+ block: L2Block;
51
+ resolve: () => void;
52
+ reject: (err: Error) => void;
53
+ };
54
+
55
+ /** Request to add a proposed checkpoint to the archiver, queued for processing by the sync loop. */
56
+ type AddProposedCheckpointRequest = {
57
+ type: 'checkpoint';
58
+ checkpoint: ProposedCheckpointInput;
59
+ resolve: () => void;
60
+ reject: (err: Error) => void;
61
+ };
62
+
63
+ export type ArchiverDeps = {
64
+ telemetry?: TelemetryClient;
65
+ blobClient: BlobClientInterface;
66
+ epochCache?: EpochCache;
67
+ dateProvider?: DateProvider;
68
+ };
69
+
70
+ /**
71
+ * Pulls checkpoints in a non-blocking manner and provides interface for their retrieval.
72
+ * Responsible for handling robust L1 polling so that other components do not need to
73
+ * concern themselves with it.
74
+ */
75
+ export class Archiver extends ArchiverDataSourceBase implements L2BlockSink, Traceable {
76
+ /** Event emitter for archiver events (L2BlockProven, L2PruneUnproven, L2PruneUncheckpointed, etc). */
77
+ public readonly events: ArchiverEmitter;
78
+
79
+ /** A loop in which we will be continually fetching new checkpoints. */
80
+ protected runningPromise: RunningPromise;
81
+
82
+ /** L1 synchronizer that handles fetching checkpoints and messages from L1. */
83
+ private readonly synchronizer: ArchiverL1Synchronizer;
84
+
85
+ private initialSyncComplete: boolean = false;
86
+ private initialSyncPromise: PromiseWithResolvers<void>;
87
+
88
+ /** Queue of blocks and checkpoints to be added to the store, processed by the sync loop. */
89
+ private inboundQueue: (AddBlockRequest | AddProposedCheckpointRequest)[] = [];
90
+
91
+ /** Helper to handle updates to the store */
92
+ private readonly updater: ArchiverDataStoreUpdater;
93
+
94
+ /** In-memory cache for L2 chain tips. */
95
+ private readonly l2TipsCache: L2TipsCache;
96
+
97
+ public readonly tracer: Tracer;
98
+
99
+ private readonly instrumentation: ArchiverInstrumentation;
100
+
101
+ /**
102
+ * Creates a new instance of the Archiver.
103
+ * @param publicClient - A client for interacting with the Ethereum node.
104
+ * @param debugClient - A client for interacting with the Ethereum node for debug/trace methods.
105
+ * @param rollup - Rollup contract instance.
106
+ * @param inbox - Inbox contract instance.
107
+ * @param l1Addresses - L1 contract addresses (registry, governance proposer, slashing proposer).
108
+ * @param dataStore - An archiver data store for storage & retrieval of blocks, encrypted logs & contract data.
109
+ * @param config - Archiver configuration options.
110
+ * @param blobClient - Client for retrieving blob data.
111
+ * @param dateProvider - Provider for current date/time.
112
+ * @param instrumentation - Instrumentation for metrics and tracing.
113
+ * @param l1Constants - L1 rollup constants.
114
+ * @param log - A logger.
115
+ */
116
+ constructor(
117
+ private readonly publicClient: ViemPublicClient,
118
+ private readonly debugClient: ViemPublicDebugClient,
119
+ private readonly rollup: RollupContract,
120
+ private readonly l1Addresses: Pick<
121
+ L1ContractAddresses,
122
+ 'rollupAddress' | 'registryAddress' | 'inboxAddress' | 'governanceProposerAddress'
123
+ > & {
124
+ slashingProposerAddress: EthAddress;
125
+ },
126
+ readonly dataStore: KVArchiverDataStore,
127
+ private config: {
128
+ pollingIntervalMs: number;
129
+ batchSize: number;
130
+ skipValidateCheckpointAttestations?: boolean;
131
+ maxAllowedEthClientDriftSeconds: number;
132
+ ethereumAllowNoDebugHosts?: boolean;
133
+ skipHistoricalLogsCheck?: boolean;
134
+ },
135
+ private readonly blobClient: BlobClientInterface,
136
+ instrumentation: ArchiverInstrumentation,
137
+ protected override readonly l1Constants: L1RollupConstants & {
138
+ l1StartBlockHash: Buffer32;
139
+ genesisArchiveRoot: Fr;
140
+ },
141
+ synchronizer: ArchiverL1Synchronizer,
142
+ events: ArchiverEmitter,
143
+ l2TipsCache?: L2TipsCache,
144
+ private readonly log: Logger = createLogger('archiver'),
145
+ ) {
146
+ super(dataStore, l1Constants);
147
+
148
+ this.tracer = instrumentation.tracer;
149
+ this.instrumentation = instrumentation;
150
+ this.initialSyncPromise = promiseWithResolvers();
151
+ this.synchronizer = synchronizer;
152
+ this.events = events;
153
+ this.l2TipsCache = l2TipsCache ?? new L2TipsCache(this.dataStore.blockStore);
154
+ this.updater = new ArchiverDataStoreUpdater(this.dataStore, this.l2TipsCache, {
155
+ rollupManaLimit: l1Constants.rollupManaLimit,
156
+ });
157
+
158
+ // Running promise starts with a small interval inbetween runs, so all iterations needed for the initial sync
159
+ // are done as fast as possible. This then gets updated once the initial sync completes.
160
+ this.runningPromise = new RunningPromise(
161
+ () => this.sync(),
162
+ this.log,
163
+ this.config.pollingIntervalMs / 10,
164
+ makeLoggingErrorHandler(this.log, NoBlobBodiesFoundError, BlockTagTooOldError),
165
+ );
166
+ }
167
+
168
+ /** Updates archiver config */
169
+ public updateConfig(newConfig: Partial<ArchiverConfig>) {
170
+ this.config = merge(this.config, mapArchiverConfig(newConfig));
171
+ this.synchronizer.setConfig(this.config);
172
+ }
173
+
174
+ /**
175
+ * Starts sync process.
176
+ * @param blockUntilSynced - If true, blocks until the archiver has fully synced.
177
+ */
178
+ public async start(blockUntilSynced: boolean): Promise<void> {
179
+ if (this.runningPromise.isRunning()) {
180
+ throw new Error('Archiver is already running');
181
+ }
182
+
183
+ await this.blobClient.testSources();
184
+ await this.synchronizer.testEthereumNodeSynced();
185
+ await validateAndLogTraceAvailability(
186
+ this.debugClient,
187
+ this.config.ethereumAllowNoDebugHosts ?? false,
188
+ this.log.getBindings(),
189
+ );
190
+ await validateAndLogHistoricalLogsAvailability(
191
+ this.publicClient,
192
+ {
193
+ rollupAddress: this.l1Addresses.rollupAddress,
194
+ inboxAddress: this.l1Addresses.inboxAddress,
195
+ registryAddress: this.l1Addresses.registryAddress,
196
+ governanceProposerAddress: this.l1Addresses.governanceProposerAddress,
197
+ },
198
+ this.config.skipHistoricalLogsCheck ?? false,
199
+ this.log.getBindings(),
200
+ );
201
+
202
+ // Log initial state for the archiver
203
+ const { l1StartBlock } = this.l1Constants;
204
+ const { blocksSynchedTo = l1StartBlock, messagesSynchedTo = l1StartBlock } = await this.store.getSynchPoint();
205
+ const currentL2Checkpoint = await this.getSynchedCheckpointNumber();
206
+ this.log.info(
207
+ `Starting archiver sync to rollup contract ${this.rollup.address} from L1 block ${blocksSynchedTo} and L2 checkpoint ${currentL2Checkpoint}`,
208
+ { blocksSynchedTo, messagesSynchedTo, currentL2Checkpoint },
209
+ );
210
+
211
+ // Start sync loop, and return the wait for initial sync if we are asked to block until synced
212
+ this.runningPromise.start();
213
+ if (blockUntilSynced) {
214
+ return this.waitForInitialSync();
215
+ }
216
+ }
217
+
218
+ public syncImmediate() {
219
+ return this.runningPromise.trigger();
220
+ }
221
+
222
+ public trySyncImmediate() {
223
+ try {
224
+ return this.syncImmediate();
225
+ } catch (err) {
226
+ this.log.error(`Failed to trigger immediate archiver sync: ${err}`, err);
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Queues a block to be added to the archiver store and triggers processing.
232
+ * The block will be processed by the sync loop.
233
+ * Implements the L2BlockSink interface.
234
+ * @param block - The L2 block to add.
235
+ * @returns A promise that resolves when the block has been added to the store, or rejects on error.
236
+ */
237
+ public addBlock(block: L2Block): Promise<void> {
238
+ const promise = promiseWithResolvers<void>();
239
+ this.inboundQueue.push({ block, ...promise, type: 'block' });
240
+ this.log.debug(`Queued block ${block.number} for processing`);
241
+ void this.trySyncImmediate();
242
+ return promise.promise;
243
+ }
244
+
245
+ /**
246
+ * Queues a new proposed checkpoint into the archiver store.
247
+ * Checks that the checkpoint is not for an L2 slot already synced from L1.
248
+ * Resolves once the checkpoint has been processed.
249
+ */
250
+ public addProposedCheckpoint(pending: ProposedCheckpointInput): Promise<void> {
251
+ const promise = promiseWithResolvers<void>();
252
+ this.inboundQueue.push({ checkpoint: pending, ...promise, type: 'checkpoint' });
253
+ this.log.debug(`Queued checkpoint ${pending.checkpointNumber} for processing`);
254
+ void this.trySyncImmediate();
255
+ return promise.promise;
256
+ }
257
+
258
+ /**
259
+ * Processes all queued blocks and checkpoints, adding them to the store.
260
+ * Called at the beginning of each sync iteration.
261
+ * Items are processed in the order they were queued.
262
+ */
263
+ private async processInboundQueue(): Promise<void> {
264
+ if (this.inboundQueue.length === 0) {
265
+ return;
266
+ }
267
+
268
+ // Take all items from the queue
269
+ const queuedItems = this.inboundQueue.splice(0, this.inboundQueue.length);
270
+ this.log.debug(`Processing ${queuedItems.length} queued inbound items`);
271
+
272
+ // Calculate slot threshold for validation
273
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
274
+ const slotAtNextL1Block =
275
+ l1Timestamp === undefined ? undefined : getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
276
+
277
+ // Helpers for manipulating blocks and checkpoints in the queue
278
+ const getSlot: (item: AddBlockRequest | AddProposedCheckpointRequest) => SlotNumber = item =>
279
+ item.type === 'block' ? item.block.header.globalVariables.slotNumber : item.checkpoint.header.slotNumber;
280
+ const getNumber: (item: AddBlockRequest | AddProposedCheckpointRequest) => number = item =>
281
+ item.type === 'block' ? item.block.number : item.checkpoint.checkpointNumber;
282
+
283
+ // Process each item individually to properly resolve/reject each promise
284
+ for (const item of queuedItems) {
285
+ const { resolve, reject, type } = item;
286
+ const itemSlot = getSlot(item);
287
+ const itemNumber = getNumber(item);
288
+ if (slotAtNextL1Block !== undefined && itemSlot < slotAtNextL1Block) {
289
+ const nextSlotTimestamp = getTimestampForSlot(slotAtNextL1Block, this.l1Constants);
290
+ this.log.warn(
291
+ `Rejecting proposed ${type} ${itemNumber} for past slot ${itemSlot} (current ${slotAtNextL1Block})`,
292
+ { number: itemNumber, type, l1Timestamp, slotAtNextL1Block, nextSlotTimestamp },
293
+ );
294
+ reject(new BlockOrCheckpointSlotExpiredError(itemSlot, nextSlotTimestamp, l1Timestamp));
295
+ continue;
296
+ }
297
+
298
+ try {
299
+ if (type === 'block') {
300
+ const [durationMs] = await elapsed(() => this.updater.addProposedBlock(item.block));
301
+ this.instrumentation.processNewProposedBlock(durationMs, item.block);
302
+ } else {
303
+ await this.updater.addProposedCheckpoint(item.checkpoint);
304
+ }
305
+ this.log.debug(`Added ${type} ${itemNumber} to store`);
306
+ resolve();
307
+ } catch (err: any) {
308
+ if (err instanceof BlockAlreadyCheckpointedError) {
309
+ this.log.debug(`Proposed block ${itemNumber} matches already checkpointed block, ignoring late proposal`);
310
+ resolve();
311
+ continue;
312
+ }
313
+ this.log.error(`Failed to add ${type} ${itemNumber} to store: ${err.message}`, err, {
314
+ number: itemNumber,
315
+ type,
316
+ });
317
+ reject(err);
318
+ }
319
+ }
320
+ }
321
+
322
+ public waitForInitialSync() {
323
+ return this.initialSyncPromise.promise;
324
+ }
325
+
326
+ /**
327
+ * Fetches logs from L1 contracts and processes them.
328
+ */
329
+ @trackSpan('Archiver.sync')
330
+ private async sync() {
331
+ // Process any queued blocks first, before doing L1 sync
332
+ await this.processInboundQueue();
333
+ // Now perform L1 sync
334
+ await this.syncFromL1();
335
+ }
336
+
337
+ private async syncFromL1() {
338
+ // Delegate to the L1 synchronizer
339
+ await this.synchronizer.syncFromL1(this.initialSyncComplete);
340
+
341
+ // Check if we've completed initial sync
342
+ const currentL1BlockNumber = this.synchronizer.getL1BlockNumber();
343
+ if (currentL1BlockNumber !== undefined && !this.initialSyncComplete) {
344
+ const l1BlockNumberAtEnd = await this.publicClient.getBlockNumber();
345
+ if (currentL1BlockNumber + 1n >= l1BlockNumberAtEnd) {
346
+ this.log.info(`Initial archiver sync to L1 block ${currentL1BlockNumber} complete`, {
347
+ l1BlockNumber: currentL1BlockNumber,
348
+ syncPoint: await this.store.getSynchPoint(),
349
+ ...(await this.getL2Tips()),
350
+ });
351
+ this.runningPromise.setPollingIntervalMS(this.config.pollingIntervalMs);
352
+ this.initialSyncComplete = true;
353
+ this.initialSyncPromise.resolve();
354
+ }
355
+ }
356
+ }
357
+
358
+ /** Resumes the archiver after a stop. */
359
+ public resume() {
360
+ if (this.runningPromise.isRunning()) {
361
+ this.log.warn(`Archiver already running`);
362
+ }
363
+ this.log.info(`Restarting archiver`);
364
+ this.runningPromise.start();
365
+ }
366
+
367
+ /**
368
+ * Stops the archiver.
369
+ * @returns A promise signalling completion of the stop process.
370
+ */
371
+ public async stop(): Promise<void> {
372
+ this.log.debug('Stopping...');
373
+ await this.runningPromise.stop();
374
+
375
+ this.log.info('Stopped.');
376
+ return Promise.resolve();
377
+ }
378
+
379
+ public backupTo(destPath: string): Promise<string> {
380
+ return this.dataStore.backupTo(destPath);
381
+ }
382
+
383
+ public getL1Constants(): Promise<L1RollupConstants> {
384
+ return Promise.resolve(this.l1Constants);
385
+ }
386
+
387
+ public getGenesisValues(): Promise<{ genesisArchiveRoot: Fr }> {
388
+ return Promise.resolve({ genesisArchiveRoot: this.l1Constants.genesisArchiveRoot });
389
+ }
390
+
391
+ public getRollupAddress(): Promise<EthAddress> {
392
+ return Promise.resolve(EthAddress.fromString(this.rollup.address));
393
+ }
394
+
395
+ public getRegistryAddress(): Promise<EthAddress> {
396
+ return Promise.resolve(this.l1Addresses.registryAddress);
397
+ }
398
+
399
+ public getL1BlockNumber(): bigint | undefined {
400
+ return this.synchronizer.getL1BlockNumber();
401
+ }
402
+
403
+ public getL1Timestamp(): Promise<bigint | undefined> {
404
+ return Promise.resolve(this.synchronizer.getL1Timestamp());
405
+ }
406
+
407
+ public async getSyncedL2SlotNumber(): Promise<SlotNumber | undefined> {
408
+ // The synced L2 slot is the latest slot for which we have all L1 data,
409
+ // either because we have seen all L1 blocks for that slot, or because
410
+ // we have seen the corresponding checkpoint.
411
+
412
+ let slotFromL1Sync: SlotNumber | undefined;
413
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
414
+ if (l1Timestamp !== undefined) {
415
+ const nextL1BlockSlot = getSlotAtNextL1Block(l1Timestamp, this.l1Constants);
416
+ if (Number(nextL1BlockSlot) > 0) {
417
+ slotFromL1Sync = SlotNumber.add(nextL1BlockSlot, -1);
418
+ }
419
+ }
420
+
421
+ let slotFromCheckpoint: SlotNumber | undefined;
422
+ const latestCheckpointNumber = await this.store.getSynchedCheckpointNumber();
423
+ if (latestCheckpointNumber > 0) {
424
+ const checkpointData = await this.store.getCheckpointData(latestCheckpointNumber);
425
+ if (checkpointData) {
426
+ slotFromCheckpoint = checkpointData.header.slotNumber;
427
+ }
428
+ }
429
+
430
+ if (slotFromL1Sync === undefined && slotFromCheckpoint === undefined) {
431
+ return undefined;
432
+ }
433
+ return SlotNumber(Math.max(slotFromL1Sync ?? 0, slotFromCheckpoint ?? 0));
434
+ }
435
+
436
+ public async getSyncedL2EpochNumber(): Promise<EpochNumber | undefined> {
437
+ const syncedSlot = await this.getSyncedL2SlotNumber();
438
+ if (syncedSlot === undefined) {
439
+ return undefined;
440
+ }
441
+ // An epoch is fully synced when all its slots are synced.
442
+ // We check if syncedSlot is the last slot of its epoch; if so, that epoch is fully synced.
443
+ // Otherwise, only the previous epoch is fully synced.
444
+ const epoch = getEpochAtSlot(syncedSlot, this.l1Constants);
445
+ const [, endSlot] = getSlotRangeForEpoch(epoch, this.l1Constants);
446
+ if (syncedSlot >= endSlot) {
447
+ return epoch;
448
+ }
449
+ return Number(epoch) > 0 ? EpochNumber(Number(epoch) - 1) : undefined;
450
+ }
451
+
452
+ public async isEpochComplete(epochNumber: EpochNumber): Promise<boolean> {
453
+ // The epoch is complete if the current checkpointed L2 block is the last one in the epoch (or later).
454
+ // We use the checkpointed block number (synced from L1) instead of 'latest' to avoid returning true
455
+ // prematurely when proposed blocks have been pushed to the archiver but not yet checkpointed on L1.
456
+ const checkpointedBlockNumber = await this.getCheckpointedL2BlockNumber();
457
+ const header = checkpointedBlockNumber > 0 ? await this.getBlockHeader(checkpointedBlockNumber) : undefined;
458
+ const slot = header ? header.globalVariables.slotNumber : undefined;
459
+ const [_startSlot, endSlot] = getSlotRangeForEpoch(epochNumber, this.l1Constants);
460
+ if (slot && slot >= endSlot) {
461
+ return true;
462
+ }
463
+
464
+ // If we haven't run an initial sync, just return false.
465
+ const l1Timestamp = this.synchronizer.getL1Timestamp();
466
+ if (l1Timestamp === undefined) {
467
+ return false;
468
+ }
469
+
470
+ // If not, the epoch may also be complete if the L2 slot has passed without a block
471
+ // We compute this based on the end timestamp for the given epoch and the timestamp of the last L1 block
472
+ const [_startTimestamp, endTimestamp] = getTimestampRangeForEpoch(epochNumber, this.l1Constants);
473
+
474
+ // For this computation, we throw in a few extra seconds just for good measure,
475
+ // since we know the next L1 block won't be mined within this range. Remember that
476
+ // l1timestamp is the timestamp of the last l1 block we've seen, so this relies on
477
+ // the fact that L1 won't mine two blocks within this time of each other.
478
+ // TODO(palla/reorg): Is the above a safe assumption?
479
+ const leeway = 1n;
480
+ return l1Timestamp + leeway >= endTimestamp;
481
+ }
482
+
483
+ /** Returns whether the archiver has completed an initial sync run successfully. */
484
+ public isInitialSyncComplete(): boolean {
485
+ return this.initialSyncComplete;
486
+ }
487
+
488
+ public removeCheckpointsAfter(checkpointNumber: CheckpointNumber): Promise<boolean> {
489
+ return this.updater.removeCheckpointsAfter(checkpointNumber);
490
+ }
491
+
492
+ /** Used by TXE to add checkpoints directly without syncing from L1. */
493
+ public async addCheckpoints(
494
+ checkpoints: PublishedCheckpoint[],
495
+ pendingChainValidationStatus?: ValidateCheckpointResult,
496
+ ): Promise<boolean> {
497
+ await this.updater.addCheckpoints(checkpoints, pendingChainValidationStatus);
498
+ return true;
499
+ }
500
+
501
+ public getL2Tips(): Promise<L2Tips> {
502
+ return this.l2TipsCache.getL2Tips();
503
+ }
504
+
505
+ public async rollbackTo(targetL2BlockNumber: BlockNumber): Promise<void> {
506
+ const currentBlocks = await this.getL2Tips();
507
+ const currentL2Block = currentBlocks.proposed.number;
508
+ const currentProvenBlock = currentBlocks.proven.block.number;
509
+
510
+ if (targetL2BlockNumber >= currentL2Block) {
511
+ throw new Error(`Target L2 block ${targetL2BlockNumber} must be less than current L2 block ${currentL2Block}`);
512
+ }
513
+ const targetL2Block = await this.store.getCheckpointedBlock(targetL2BlockNumber);
514
+ if (!targetL2Block) {
515
+ throw new Error(`Target L2 block ${targetL2BlockNumber} not found`);
516
+ }
517
+ const targetCheckpointNumber = targetL2Block.checkpointNumber;
518
+
519
+ // Rollback operates at checkpoint granularity: the target block must be the last block of its checkpoint.
520
+ const checkpointData = await this.store.getCheckpointData(targetCheckpointNumber);
521
+ if (checkpointData) {
522
+ const lastBlockInCheckpoint = BlockNumber(checkpointData.startBlock + checkpointData.blockCount - 1);
523
+ if (targetL2BlockNumber !== lastBlockInCheckpoint) {
524
+ const previousCheckpointBoundary =
525
+ checkpointData.startBlock > 1 ? BlockNumber(checkpointData.startBlock - 1) : BlockNumber(0);
526
+ throw new Error(
527
+ `Target L2 block ${targetL2BlockNumber} is not at a checkpoint boundary. ` +
528
+ `Checkpoint ${targetCheckpointNumber} spans blocks ${checkpointData.startBlock} to ${lastBlockInCheckpoint}. ` +
529
+ `Use block ${lastBlockInCheckpoint} to roll back to this checkpoint, ` +
530
+ `or block ${previousCheckpointBoundary} to roll back to the previous one.`,
531
+ );
532
+ }
533
+ }
534
+
535
+ const targetL1BlockNumber = targetL2Block.l1.blockNumber;
536
+ const targetL1Block = await this.publicClient.getBlock({
537
+ blockNumber: targetL1BlockNumber,
538
+ includeTransactions: false,
539
+ });
540
+ if (!targetL1Block) {
541
+ throw new Error(`Missing L1 block ${targetL1BlockNumber}`);
542
+ }
543
+ const targetL1BlockHash = Buffer32.fromString(targetL1Block.hash);
544
+ this.log.info(
545
+ `Removing checkpoints after checkpoint ${targetCheckpointNumber} (target block ${targetL2BlockNumber})`,
546
+ );
547
+ await this.updater.removeCheckpointsAfter(targetCheckpointNumber);
548
+ this.log.info(`Rolling back L1 to L2 messages to checkpoint ${targetCheckpointNumber}`);
549
+ await this.store.rollbackL1ToL2MessagesToCheckpoint(targetCheckpointNumber);
550
+ this.log.info(`Setting L1 syncpoints to ${targetL1BlockNumber}`);
551
+ await this.store.setCheckpointSynchedL1BlockNumber(targetL1BlockNumber);
552
+ await this.store.setMessageSyncState(
553
+ { l1BlockNumber: targetL1BlockNumber, l1BlockHash: targetL1BlockHash },
554
+ undefined,
555
+ );
556
+ if (targetL2BlockNumber < currentProvenBlock) {
557
+ this.log.info(`Rolling back proven L2 checkpoint to ${targetCheckpointNumber}`);
558
+ await this.updater.setProvenCheckpointNumber(targetCheckpointNumber);
559
+ }
560
+ const currentFinalizedBlock = currentBlocks.finalized.block.number;
561
+ if (targetL2BlockNumber < currentFinalizedBlock) {
562
+ this.log.info(`Rolling back finalized L2 checkpoint to ${targetCheckpointNumber}`);
563
+ await this.updater.setFinalizedCheckpointNumber(targetCheckpointNumber);
564
+ }
565
+ }
566
+ }
@@ -1,18 +1,20 @@
1
- import { type BlobSinkConfig, blobSinkConfigMapping } from '@aztec/blob-sink/client';
2
- import {
3
- type L1ContractsConfig,
4
- type L1ReaderConfig,
5
- l1ContractAddressesMapping,
6
- l1ContractsConfigMappings,
7
- l1ReaderConfigMappings,
8
- } from '@aztec/ethereum';
1
+ import { type BlobClientConfig, blobClientConfigMapping } from '@aztec/blob-client/client/config';
2
+ import { type L1ContractsConfig, l1ContractsConfigMappings } from '@aztec/ethereum/config';
3
+ import { l1ContractAddressesMapping } from '@aztec/ethereum/l1-contract-addresses';
4
+ import { type L1ReaderConfig, l1ReaderConfigMappings } from '@aztec/ethereum/l1-reader';
9
5
  import {
10
6
  type ConfigMappingsType,
11
7
  booleanConfigHelper,
12
8
  getConfigFromMappings,
13
9
  numberConfigHelper,
10
+ optionalNumberConfigHelper,
14
11
  } from '@aztec/foundation/config';
15
- import { type ChainConfig, chainConfigMappings } from '@aztec/stdlib/config';
12
+ import {
13
+ type ChainConfig,
14
+ type PipelineConfig,
15
+ chainConfigMappings,
16
+ pipelineConfigMappings,
17
+ } from '@aztec/stdlib/config';
16
18
  import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
17
19
 
18
20
  /**
@@ -22,10 +24,16 @@ import type { ArchiverSpecificConfig } from '@aztec/stdlib/interfaces/server';
22
24
  * Results of calls to eth_blockNumber are cached by viem with this cache being updated periodically at the interval specified by viemPollingIntervalMS.
23
25
  * As a result the maximum observed polling time for new blocks will be viemPollingIntervalMS + archiverPollingIntervalMS.
24
26
  */
25
- export type ArchiverConfig = ArchiverSpecificConfig & L1ReaderConfig & L1ContractsConfig & BlobSinkConfig & ChainConfig;
27
+ export type ArchiverConfig = ArchiverSpecificConfig &
28
+ L1ReaderConfig &
29
+ L1ContractsConfig &
30
+ PipelineConfig & // required to pass through to epoch cache
31
+ BlobClientConfig &
32
+ ChainConfig;
26
33
 
27
34
  export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
28
- ...blobSinkConfigMapping,
35
+ ...blobClientConfigMapping,
36
+ ...pipelineConfigMappings,
29
37
  archiverPollingIntervalMS: {
30
38
  env: 'ARCHIVER_POLLING_INTERVAL_MS',
31
39
  description: 'The polling interval in ms for retrieving new L2 blocks and encrypted logs.',
@@ -43,11 +51,15 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
43
51
  },
44
52
  archiverStoreMapSizeKb: {
45
53
  env: 'ARCHIVER_STORE_MAP_SIZE_KB',
46
- parseEnv: (val: string | undefined) => (val ? +val : undefined),
54
+ ...optionalNumberConfigHelper(),
47
55
  description: 'The maximum possible size of the archiver DB in KB. Overwrites the general dataStoreMapSizeKb.',
48
56
  },
49
- skipValidateBlockAttestations: {
50
- description: 'Whether to skip validating block attestations (use only for testing).',
57
+ skipValidateCheckpointAttestations: {
58
+ description: 'Skip validating checkpoint attestations (for testing purposes only)',
59
+ ...booleanConfigHelper(false),
60
+ },
61
+ skipPromoteProposedCheckpointDuringL1Sync: {
62
+ description: 'Skip promoting proposed checkpoints during L1 sync (for testing purposes only)',
51
63
  ...booleanConfigHelper(false),
52
64
  },
53
65
  maxAllowedEthClientDriftSeconds: {
@@ -55,6 +67,18 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
55
67
  description: 'Maximum allowed drift in seconds between the Ethereum client and current time.',
56
68
  ...numberConfigHelper(300),
57
69
  },
70
+ ethereumAllowNoDebugHosts: {
71
+ env: 'ETHEREUM_ALLOW_NO_DEBUG_HOSTS',
72
+ description: 'Whether to allow starting the archiver without debug/trace method support on Ethereum hosts',
73
+ ...booleanConfigHelper(true),
74
+ },
75
+ archiverSkipHistoricalLogsCheck: {
76
+ env: 'ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK',
77
+ description:
78
+ 'Skip the startup check that probes the L1 RPC for historical Rollup contract logs. ' +
79
+ 'Set to true to bypass the check when the connected RPC node is known to prune old logs.',
80
+ ...booleanConfigHelper(false),
81
+ },
58
82
  ...chainConfigMappings,
59
83
  ...l1ReaderConfigMappings,
60
84
  viemPollingIntervalMS: {
@@ -77,3 +101,16 @@ export const archiverConfigMappings: ConfigMappingsType<ArchiverConfig> = {
77
101
  export function getArchiverConfigFromEnv(): ArchiverConfig {
78
102
  return getConfigFromMappings<ArchiverConfig>(archiverConfigMappings);
79
103
  }
104
+
105
+ /** Extracts the archiver-specific configuration from the full ArchiverConfig */
106
+ export function mapArchiverConfig(config: Partial<ArchiverConfig>) {
107
+ return {
108
+ pollingIntervalMs: config.archiverPollingIntervalMS,
109
+ batchSize: config.archiverBatchSize,
110
+ skipValidateCheckpointAttestations: config.skipValidateCheckpointAttestations,
111
+ skipPromoteProposedCheckpointDuringL1Sync: config.skipPromoteProposedCheckpointDuringL1Sync,
112
+ maxAllowedEthClientDriftSeconds: config.maxAllowedEthClientDriftSeconds,
113
+ ethereumAllowNoDebugHosts: config.ethereumAllowNoDebugHosts,
114
+ skipHistoricalLogsCheck: config.archiverSkipHistoricalLogsCheck,
115
+ };
116
+ }