@aztec/archiver 0.0.1-commit.e558bd1c → 0.0.1-commit.e57c76e

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 (136) hide show
  1. package/README.md +19 -11
  2. package/dest/archiver.d.ts +58 -18
  3. package/dest/archiver.d.ts.map +1 -1
  4. package/dest/archiver.js +284 -160
  5. package/dest/config.d.ts +4 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +21 -14
  8. package/dest/errors.d.ts +55 -9
  9. package/dest/errors.d.ts.map +1 -1
  10. package/dest/errors.js +81 -14
  11. package/dest/factory.d.ts +14 -9
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +55 -39
  14. package/dest/index.d.ts +12 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +11 -2
  17. package/dest/l1/bin/retrieve-calldata.js +32 -28
  18. package/dest/l1/calldata_retriever.d.ts +74 -50
  19. package/dest/l1/calldata_retriever.d.ts.map +1 -1
  20. package/dest/l1/calldata_retriever.js +201 -260
  21. package/dest/l1/data_retrieval.d.ts +26 -17
  22. package/dest/l1/data_retrieval.d.ts.map +1 -1
  23. package/dest/l1/data_retrieval.js +42 -47
  24. package/dest/l1/spire_proposer.d.ts +5 -5
  25. package/dest/l1/spire_proposer.d.ts.map +1 -1
  26. package/dest/l1/spire_proposer.js +9 -17
  27. package/dest/l1/trace_tx.d.ts +12 -66
  28. package/dest/l1/trace_tx.d.ts.map +1 -1
  29. package/dest/l1/validate_historical_logs.d.ts +23 -0
  30. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  31. package/dest/l1/validate_historical_logs.js +108 -0
  32. package/dest/modules/contract_data_source_adapter.d.ts +25 -0
  33. package/dest/modules/contract_data_source_adapter.d.ts.map +1 -0
  34. package/dest/modules/contract_data_source_adapter.js +40 -0
  35. package/dest/modules/data_source_base.d.ts +74 -45
  36. package/dest/modules/data_source_base.d.ts.map +1 -1
  37. package/dest/modules/data_source_base.js +269 -181
  38. package/dest/modules/data_store_updater.d.ts +49 -17
  39. package/dest/modules/data_store_updater.d.ts.map +1 -1
  40. package/dest/modules/data_store_updater.js +211 -121
  41. package/dest/modules/instrumentation.d.ts +21 -3
  42. package/dest/modules/instrumentation.d.ts.map +1 -1
  43. package/dest/modules/instrumentation.js +44 -9
  44. package/dest/modules/l1_synchronizer.d.ts +14 -12
  45. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  46. package/dest/modules/l1_synchronizer.js +443 -211
  47. package/dest/modules/outbox_trees_resolver.d.ts +62 -0
  48. package/dest/modules/outbox_trees_resolver.d.ts.map +1 -0
  49. package/dest/modules/outbox_trees_resolver.js +162 -0
  50. package/dest/modules/validation.d.ts +4 -3
  51. package/dest/modules/validation.d.ts.map +1 -1
  52. package/dest/modules/validation.js +6 -6
  53. package/dest/store/block_store.d.ts +174 -72
  54. package/dest/store/block_store.d.ts.map +1 -1
  55. package/dest/store/block_store.js +739 -272
  56. package/dest/store/contract_class_store.d.ts +17 -4
  57. package/dest/store/contract_class_store.d.ts.map +1 -1
  58. package/dest/store/contract_class_store.js +24 -68
  59. package/dest/store/contract_instance_store.d.ts +28 -1
  60. package/dest/store/contract_instance_store.d.ts.map +1 -1
  61. package/dest/store/contract_instance_store.js +37 -2
  62. package/dest/store/data_stores.d.ts +68 -0
  63. package/dest/store/data_stores.d.ts.map +1 -0
  64. package/dest/store/data_stores.js +54 -0
  65. package/dest/store/function_names_cache.d.ts +17 -0
  66. package/dest/store/function_names_cache.d.ts.map +1 -0
  67. package/dest/store/function_names_cache.js +30 -0
  68. package/dest/store/l2_tips_cache.d.ts +25 -0
  69. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  70. package/dest/store/l2_tips_cache.js +26 -0
  71. package/dest/store/log_store.d.ts +42 -37
  72. package/dest/store/log_store.d.ts.map +1 -1
  73. package/dest/store/log_store.js +262 -408
  74. package/dest/store/log_store_codec.d.ts +70 -0
  75. package/dest/store/log_store_codec.d.ts.map +1 -0
  76. package/dest/store/log_store_codec.js +101 -0
  77. package/dest/store/message_store.d.ts +11 -1
  78. package/dest/store/message_store.d.ts.map +1 -1
  79. package/dest/store/message_store.js +51 -9
  80. package/dest/test/fake_l1_state.d.ts +25 -1
  81. package/dest/test/fake_l1_state.d.ts.map +1 -1
  82. package/dest/test/fake_l1_state.js +166 -32
  83. package/dest/test/mock_archiver.d.ts +1 -1
  84. package/dest/test/mock_archiver.d.ts.map +1 -1
  85. package/dest/test/mock_archiver.js +3 -2
  86. package/dest/test/mock_l1_to_l2_message_source.d.ts +1 -1
  87. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  88. package/dest/test/mock_l1_to_l2_message_source.js +2 -1
  89. package/dest/test/mock_l2_block_source.d.ts +64 -47
  90. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  91. package/dest/test/mock_l2_block_source.js +323 -214
  92. package/dest/test/mock_structs.d.ts +4 -1
  93. package/dest/test/mock_structs.d.ts.map +1 -1
  94. package/dest/test/mock_structs.js +13 -1
  95. package/dest/test/noop_l1_archiver.d.ts +13 -6
  96. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  97. package/dest/test/noop_l1_archiver.js +27 -10
  98. package/package.json +14 -14
  99. package/src/archiver.ts +359 -183
  100. package/src/config.ts +24 -11
  101. package/src/errors.ts +122 -21
  102. package/src/factory.ts +79 -38
  103. package/src/index.ts +19 -2
  104. package/src/l1/README.md +25 -68
  105. package/src/l1/bin/retrieve-calldata.ts +40 -27
  106. package/src/l1/calldata_retriever.ts +260 -379
  107. package/src/l1/data_retrieval.ts +58 -69
  108. package/src/l1/spire_proposer.ts +7 -15
  109. package/src/l1/validate_historical_logs.ts +140 -0
  110. package/src/modules/contract_data_source_adapter.ts +55 -0
  111. package/src/modules/data_source_base.ts +354 -226
  112. package/src/modules/data_store_updater.ts +248 -153
  113. package/src/modules/instrumentation.ts +56 -9
  114. package/src/modules/l1_synchronizer.ts +585 -258
  115. package/src/modules/outbox_trees_resolver.ts +199 -0
  116. package/src/modules/validation.ts +10 -9
  117. package/src/store/block_store.ts +917 -343
  118. package/src/store/contract_class_store.ts +31 -103
  119. package/src/store/contract_instance_store.ts +51 -5
  120. package/src/store/data_stores.ts +104 -0
  121. package/src/store/function_names_cache.ts +37 -0
  122. package/src/store/l2_tips_cache.ts +35 -0
  123. package/src/store/log_store.ts +301 -559
  124. package/src/store/log_store_codec.ts +132 -0
  125. package/src/store/message_store.ts +60 -10
  126. package/src/structs/inbox_message.ts +1 -1
  127. package/src/test/fake_l1_state.ts +213 -42
  128. package/src/test/mock_archiver.ts +3 -2
  129. package/src/test/mock_l1_to_l2_message_source.ts +1 -0
  130. package/src/test/mock_l2_block_source.ts +391 -232
  131. package/src/test/mock_structs.ts +20 -6
  132. package/src/test/noop_l1_archiver.ts +49 -10
  133. package/dest/store/kv_archiver_store.d.ts +0 -340
  134. package/dest/store/kv_archiver_store.d.ts.map +0 -1
  135. package/dest/store/kv_archiver_store.js +0 -446
  136. package/src/store/kv_archiver_store.ts +0 -639
@@ -0,0 +1,199 @@
1
+ import type { OutboxContract } from '@aztec/ethereum/contracts';
2
+ import type { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
3
+ import { chunkBy } from '@aztec/foundation/collection';
4
+ import type { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { type Logger, createLogger } from '@aztec/foundation/log';
6
+ import type { L2Block } from '@aztec/stdlib/block';
7
+ import type { CheckpointData } from '@aztec/stdlib/checkpoint';
8
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
9
+ import { type L2ToL1MembershipWitness, computeL2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
10
+ import type { IndexedTxEffect, TxHash } from '@aztec/stdlib/tx';
11
+
12
+ /**
13
+ * Archiver-side view of the data the resolver needs to assemble a witness. The archiver implements
14
+ * each of these natively, so no L2 RPC plumbing is required.
15
+ */
16
+ export interface OutboxTreesArchiverView {
17
+ getBlocks(query: { epoch: EpochNumber; onlyCheckpointed: true }): Promise<L2Block[]>;
18
+ getBlock(query: { number: BlockNumber }): Promise<L2Block | undefined>;
19
+ getCheckpointsData(query: { epoch: EpochNumber }): Promise<CheckpointData[]>;
20
+ getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined>;
21
+ }
22
+
23
+ /** A cached per-epoch set of Outbox roots, tagged with the synced L1 block they were read at. */
24
+ type CachedRoots = {
25
+ /** The `MAX_CHECKPOINTS_PER_EPOCH`-length array of partial-proof roots the L1 Outbox holds for the epoch. */
26
+ roots: Fr[];
27
+ /** The node's synced L1 block number at the moment we fetched these roots. */
28
+ fetchedAtL1Block: bigint;
29
+ };
30
+
31
+ /**
32
+ * Holds an in-memory cache of per-epoch Outbox roots used to build L2-to-L1 message membership
33
+ * witnesses, plus the single-flight registry that dedupes concurrent fetches.
34
+ *
35
+ * Roots are fetched lazily on request and cached against the node's synced L1 block: a cached entry
36
+ * is reused only while the synced L1 block is unchanged, and re-fetched from L1 once the node
37
+ * advances. The cache is intentionally not persisted — entries are valid for at most one L1 slot, so
38
+ * there is nothing worth carrying across restarts. The four merkle-tree levels are rebuilt per
39
+ * request from the archiver's raw L2 data via `computeL2ToL1MembershipWitness`; no trees or
40
+ * intermediate out-hashes are cached.
41
+ *
42
+ * TODO: Re-add permanent caching for sealed-and-L1-finalized epochs so their roots can be frozen
43
+ * and served without any L1 read once they can no longer change. That logic was dropped here to keep
44
+ * the cache simple; it would likely want a persisted store again.
45
+ */
46
+ export class OutboxTreesResolver {
47
+ /** In-memory cache of per-epoch Outbox roots, keyed by epoch number. */
48
+ #cache: Map<EpochNumber, CachedRoots> = new Map();
49
+
50
+ /** Single-flight registry for in-flight roots fetches, keyed by epoch number. */
51
+ #pending: Map<EpochNumber, Promise<Fr[] | undefined>> = new Map();
52
+
53
+ /** Adapter exposing the slice of the node API that `computeL2ToL1MembershipWitness` requires. */
54
+ #node: Parameters<typeof computeL2ToL1MembershipWitness>[0];
55
+
56
+ constructor(
57
+ private readonly outbox: OutboxContract,
58
+ private readonly archiver: OutboxTreesArchiverView,
59
+ private readonly getSyncedL1BlockNumber: () => Promise<bigint | undefined>,
60
+ private readonly epochDuration: number,
61
+ private readonly log: Logger = createLogger('archiver:outbox'),
62
+ ) {
63
+ this.#node = this.makeNodeView();
64
+ }
65
+
66
+ /**
67
+ * Builds the L2-to-L1 membership witness for `message` in tx `txHash`. Returns `undefined` if the
68
+ * tx isn't yet in a block/epoch, or if the Outbox holds no covering partial-proof root for the
69
+ * tx's checkpoint as of the node's synced L1 block — callers should retry in that case.
70
+ */
71
+ public async getL2ToL1MembershipWitness(
72
+ txHash: TxHash,
73
+ message: Fr,
74
+ messageIndexInTx?: number,
75
+ ): Promise<L2ToL1MembershipWitness | undefined> {
76
+ const indexed = await this.archiver.getTxEffect(txHash);
77
+ if (!indexed) {
78
+ this.log.trace(`No tx effect for tx, no witness available`, { txHash });
79
+ return undefined;
80
+ }
81
+
82
+ // Derive the epoch from the tx's slot the same way the node assembles a mined receipt, so the
83
+ // witness helper sees the same view a `getTxReceipt` caller would.
84
+ const epochNumber = getEpochAtSlot(indexed.slotNumber, { epochDuration: this.epochDuration });
85
+ const roots = await this.#getRoots(epochNumber);
86
+ if (roots === undefined) {
87
+ return undefined;
88
+ }
89
+
90
+ const receipt = {
91
+ txHash,
92
+ epochNumber,
93
+ blockNumber: indexed.l2BlockNumber,
94
+ txIndexInBlock: indexed.txIndexInBlock,
95
+ };
96
+
97
+ const syncedBefore = await this.getSyncedL1BlockNumber();
98
+ try {
99
+ return await computeL2ToL1MembershipWitness(this.#node, roots, message, receipt, messageIndexInTx);
100
+ } catch (err) {
101
+ // The helper throws if the locally-assembled epoch root disagrees with the cached Outbox root.
102
+ // The cached roots are pinned to the node's synced L1 block, but the helper reads block /
103
+ // checkpoint data live, so if the archiver advanced mid-assembly the two can momentarily reflect
104
+ // different heights and produce a transient mismatch. When the synced block moved during
105
+ // assembly we treat the mismatch as transient and return undefined so the caller can retry; a
106
+ // mismatch at a stable synced block is a genuine node/L1 disagreement and must surface.
107
+ const syncedAfter = await this.getSyncedL1BlockNumber();
108
+ if (syncedBefore !== syncedAfter && err instanceof Error && err.message.includes('does not match Outbox')) {
109
+ this.log.debug(`Transient outbox root mismatch during sync, returning no witness`, {
110
+ txHash,
111
+ epoch: epochNumber,
112
+ });
113
+ return undefined;
114
+ }
115
+ throw err;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Lazily returns the per-epoch Outbox roots, reusing the cached entry while the node's synced L1
121
+ * block is unchanged and re-fetching from L1 once it advances. Returns `undefined` if the node has
122
+ * not established a synced L1 block yet. Concurrent requests for the same epoch share a single
123
+ * in-flight fetch via {@link #pending}.
124
+ */
125
+ #getRoots(epoch: EpochNumber): Promise<Fr[] | undefined> {
126
+ const inFlight = this.#pending.get(epoch);
127
+ if (inFlight) {
128
+ return inFlight;
129
+ }
130
+
131
+ const promise = this.#refreshRoots(epoch).finally(() => {
132
+ this.#pending.delete(epoch);
133
+ });
134
+ this.#pending.set(epoch, promise);
135
+ return promise;
136
+ }
137
+
138
+ /**
139
+ * Single-flight body for {@link #getRoots}. Re-reads the cached entry and synced block here —
140
+ * rather than capturing them before winning the {@link #pending} slot — so a late entrant that
141
+ * missed the slot cannot overwrite a fresher entry the previous winner just wrote.
142
+ */
143
+ async #refreshRoots(epoch: EpochNumber): Promise<Fr[] | undefined> {
144
+ const synced = await this.getSyncedL1BlockNumber();
145
+ if (synced === undefined) {
146
+ // The archiver has no synced L1 block yet, so there is no consistent height to read the Outbox
147
+ // at. The caller retries once the node has synced.
148
+ return undefined;
149
+ }
150
+
151
+ const cached = this.#cache.get(epoch);
152
+ if (cached && cached.fetchedAtL1Block === synced) {
153
+ return cached.roots;
154
+ }
155
+
156
+ // TODO: Re-add permanent caching for sealed-and-L1-finalized epochs so we can skip the L1 read
157
+ // entirely once an epoch's roots can no longer change. For now the cache is valid only for the
158
+ // current synced L1 block and we re-query the Outbox whenever the node advances.
159
+ const roots = await this.outbox.getRoots(epoch, { blockNumber: synced });
160
+ this.#cache.set(epoch, { roots, fetchedAtL1Block: synced });
161
+ this.log.trace(`Fetched outbox roots for epoch ${epoch}`, {
162
+ epoch,
163
+ syncedL1Block: synced,
164
+ nonZeroRoots: roots.filter(r => !r.isZero()).length,
165
+ });
166
+ return roots;
167
+ }
168
+
169
+ /**
170
+ * Returns the L2-to-L1 messages in `epoch`, organized as `checkpoint[] → block[] → tx[] →
171
+ * message[]`. Mirrors `AztecNodeService.getL2ToL1Messages` so the resolver can run off the
172
+ * archiver directly without going through the node RPC surface.
173
+ */
174
+ async #getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
175
+ const blocks = await this.archiver.getBlocks({ epoch, onlyCheckpointed: true });
176
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
177
+ return blocksInCheckpoints.map(slotBlocks =>
178
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Builds the node-shaped adapter handed to `computeL2ToL1MembershipWitness`. The helper invokes
184
+ * `getL2ToL1Messages` / `getBlock` / `getCheckpointsData`; `getTxReceipt` is part of the helper's
185
+ * node type but is never invoked because we always pass an already-resolved receipt.
186
+ */
187
+ private makeNodeView(): Parameters<typeof computeL2ToL1MembershipWitness>[0] {
188
+ return {
189
+ getL2ToL1Messages: (epoch: EpochNumber) => this.#getL2ToL1Messages(epoch),
190
+ getBlock: ((param: BlockNumber) => this.archiver.getBlock({ number: param })) as Parameters<
191
+ typeof computeL2ToL1MembershipWitness
192
+ >[0]['getBlock'],
193
+ getCheckpointsData: (query: { epoch: EpochNumber }) => this.archiver.getCheckpointsData(query),
194
+ getTxReceipt: (() => {
195
+ throw new Error('OutboxTreesResolver always passes a resolved receipt; getTxReceipt must not be called');
196
+ }) as Parameters<typeof computeL2ToL1MembershipWitness>[0]['getTxReceipt'],
197
+ };
198
+ }
199
+ }
@@ -9,8 +9,8 @@ import {
9
9
  getAttestationInfoFromPayload,
10
10
  } from '@aztec/stdlib/block';
11
11
  import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
12
- import { type L1RollupConstants, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
13
- import { ConsensusPayload } from '@aztec/stdlib/p2p';
12
+ import { type L1RollupConstants, computeQuorum, getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
13
+ import { ConsensusPayload, type CoordinationSignatureContext } from '@aztec/stdlib/p2p';
14
14
 
15
15
  export type { ValidateCheckpointResult };
16
16
 
@@ -18,11 +18,11 @@ export type { ValidateCheckpointResult };
18
18
  * Extracts attestation information from a published checkpoint.
19
19
  * Returns info for each attestation, preserving array indices.
20
20
  */
21
- export function getAttestationInfoFromPublishedCheckpoint({
22
- checkpoint,
23
- attestations,
24
- }: PublishedCheckpoint): AttestationInfo[] {
25
- const payload = ConsensusPayload.fromCheckpoint(checkpoint);
21
+ export function getAttestationInfoFromPublishedCheckpoint(
22
+ { checkpoint, attestations }: PublishedCheckpoint,
23
+ signatureContext: CoordinationSignatureContext,
24
+ ): AttestationInfo[] {
25
+ const payload = ConsensusPayload.fromCheckpoint(checkpoint, signatureContext);
26
26
  return getAttestationInfoFromPayload(payload, attestations);
27
27
  }
28
28
 
@@ -34,9 +34,10 @@ export async function validateCheckpointAttestations(
34
34
  publishedCheckpoint: PublishedCheckpoint,
35
35
  epochCache: EpochCache,
36
36
  constants: Pick<L1RollupConstants, 'epochDuration'>,
37
+ signatureContext: CoordinationSignatureContext,
37
38
  logger?: Logger,
38
39
  ): Promise<ValidateCheckpointResult> {
39
- const attestorInfos = getAttestationInfoFromPublishedCheckpoint(publishedCheckpoint);
40
+ const attestorInfos = getAttestationInfoFromPublishedCheckpoint(publishedCheckpoint, signatureContext);
40
41
  const attestors = compactArray(attestorInfos.map(info => ('address' in info ? info.address : undefined)));
41
42
  const { checkpoint, attestations } = publishedCheckpoint;
42
43
  const headerHash = checkpoint.header.hash();
@@ -66,7 +67,7 @@ export async function validateCheckpointAttestations(
66
67
  return { valid: true };
67
68
  }
68
69
 
69
- const requiredAttestationCount = Math.floor((committee.length * 2) / 3) + 1;
70
+ const requiredAttestationCount = computeQuorum(committee.length);
70
71
 
71
72
  const failedValidationResult = <TReason extends ValidateCheckpointNegativeResult['reason']>(reason: TReason) => ({
72
73
  valid: false as const,