@aztec/archiver 4.0.0-nightly.20260113 → 4.0.0-nightly.20260114

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 (47) hide show
  1. package/README.md +139 -22
  2. package/dest/archiver/archive_source_base.d.ts +75 -0
  3. package/dest/archiver/archive_source_base.d.ts.map +1 -0
  4. package/dest/archiver/archive_source_base.js +202 -0
  5. package/dest/archiver/archiver.d.ts +28 -167
  6. package/dest/archiver/archiver.d.ts.map +1 -1
  7. package/dest/archiver/archiver.js +46 -601
  8. package/dest/archiver/archiver_store_updates.d.ts +38 -0
  9. package/dest/archiver/archiver_store_updates.d.ts.map +1 -0
  10. package/dest/archiver/archiver_store_updates.js +212 -0
  11. package/dest/archiver/index.d.ts +3 -2
  12. package/dest/archiver/index.d.ts.map +1 -1
  13. package/dest/archiver/index.js +2 -0
  14. package/dest/archiver/kv_archiver_store/block_store.d.ts +1 -1
  15. package/dest/archiver/kv_archiver_store/block_store.js +1 -1
  16. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +1 -1
  17. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  18. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +1 -1
  19. package/dest/archiver/kv_archiver_store/contract_instance_store.js +1 -1
  20. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +169 -9
  21. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  22. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +157 -49
  23. package/dest/archiver/l1/data_retrieval.d.ts +9 -11
  24. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -1
  25. package/dest/archiver/l1/data_retrieval.js +32 -51
  26. package/dest/archiver/test/fake_l1_state.d.ts +173 -0
  27. package/dest/archiver/test/fake_l1_state.d.ts.map +1 -0
  28. package/dest/archiver/test/fake_l1_state.js +364 -0
  29. package/package.json +13 -13
  30. package/src/archiver/archive_source_base.ts +339 -0
  31. package/src/archiver/archiver.ts +62 -808
  32. package/src/archiver/archiver_store_updates.ts +321 -0
  33. package/src/archiver/index.ts +2 -1
  34. package/src/archiver/kv_archiver_store/block_store.ts +1 -1
  35. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  36. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  37. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +170 -8
  38. package/src/archiver/l1/data_retrieval.ts +51 -68
  39. package/src/archiver/test/fake_l1_state.ts +561 -0
  40. package/dest/archiver/archiver_store.d.ts +0 -315
  41. package/dest/archiver/archiver_store.d.ts.map +0 -1
  42. package/dest/archiver/archiver_store.js +0 -4
  43. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  44. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  45. package/dest/archiver/archiver_store_test_suite.js +0 -2770
  46. package/src/archiver/archiver_store.ts +0 -380
  47. package/src/archiver/archiver_store_test_suite.ts +0 -2842
@@ -0,0 +1,321 @@
1
+ import type { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import { createLogger } from '@aztec/foundation/log';
4
+ import {
5
+ ContractClassPublishedEvent,
6
+ PrivateFunctionBroadcastedEvent,
7
+ UtilityFunctionBroadcastedEvent,
8
+ } from '@aztec/protocol-contracts/class-registry';
9
+ import {
10
+ ContractInstancePublishedEvent,
11
+ ContractInstanceUpdatedEvent,
12
+ } from '@aztec/protocol-contracts/instance-registry';
13
+ import type { L2BlockNew, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
15
+ import {
16
+ type ExecutablePrivateFunctionWithMembershipProof,
17
+ type UtilityFunctionWithMembershipProof,
18
+ computePublicBytecodeCommitment,
19
+ isValidPrivateFunctionMembershipProof,
20
+ isValidUtilityFunctionMembershipProof,
21
+ } from '@aztec/stdlib/contract';
22
+ import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
+ import type { UInt64 } from '@aztec/stdlib/types';
24
+
25
+ import groupBy from 'lodash.groupby';
26
+
27
+ import type { KVArchiverDataStore } from './kv_archiver_store/kv_archiver_store.js';
28
+
29
+ const log = createLogger('archiver:store-updates');
30
+
31
+ /** Operation type for contract data updates. */
32
+ enum Operation {
33
+ Store,
34
+ Delete,
35
+ }
36
+
37
+ /**
38
+ * Adds blocks to the store with contract class/instance extraction from logs.
39
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
40
+ * and individually broadcasted functions from the block logs.
41
+ *
42
+ * @param store - The archiver data store.
43
+ * @param blocks - The L2 blocks to add.
44
+ * @param pendingChainValidationStatus - Optional validation status to set.
45
+ * @returns True if the operation is successful.
46
+ */
47
+ export function addBlocksWithContractData(
48
+ store: KVArchiverDataStore,
49
+ blocks: L2BlockNew[],
50
+ pendingChainValidationStatus?: ValidateCheckpointResult,
51
+ ): Promise<boolean> {
52
+ return store.transactionAsync(async () => {
53
+ await store.addBlocks(blocks);
54
+
55
+ const opResults = await Promise.all([
56
+ // Update the pending chain validation status if provided
57
+ pendingChainValidationStatus && store.setPendingChainValidationStatus(pendingChainValidationStatus),
58
+ // Add any logs emitted during the retrieved blocks
59
+ store.addLogs(blocks),
60
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
61
+ ...blocks.map(block => addBlockDataToDB(store, block)),
62
+ ]);
63
+
64
+ return opResults.every(Boolean);
65
+ });
66
+ }
67
+
68
+ /**
69
+ * Adds checkpoints to the store with contract class/instance extraction from logs.
70
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
71
+ * and individually broadcasted functions from the checkpoint block logs.
72
+ *
73
+ * @param store - The archiver data store.
74
+ * @param checkpoints - The published checkpoints to add.
75
+ * @param pendingChainValidationStatus - Optional validation status to set.
76
+ * @returns True if the operation is successful.
77
+ */
78
+ export function addCheckpointsWithContractData(
79
+ store: KVArchiverDataStore,
80
+ checkpoints: PublishedCheckpoint[],
81
+ pendingChainValidationStatus?: ValidateCheckpointResult,
82
+ ): Promise<boolean> {
83
+ return store.transactionAsync(async () => {
84
+ await store.addCheckpoints(checkpoints);
85
+ const allBlocks = checkpoints.flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks);
86
+
87
+ const opResults = await Promise.all([
88
+ // Update the pending chain validation status if provided
89
+ pendingChainValidationStatus && store.setPendingChainValidationStatus(pendingChainValidationStatus),
90
+ // Add any logs emitted during the retrieved blocks
91
+ store.addLogs(allBlocks),
92
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
93
+ ...allBlocks.map(block => addBlockDataToDB(store, block)),
94
+ ]);
95
+
96
+ return opResults.every(Boolean);
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Unwinds checkpoints from the store with reverse contract extraction.
102
+ * Deletes ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated data
103
+ * that was stored for the unwound checkpoints.
104
+ *
105
+ * @param store - The archiver data store.
106
+ * @param from - The checkpoint number to unwind from (must be the current tip).
107
+ * @param checkpointsToUnwind - The number of checkpoints to unwind.
108
+ * @returns True if the operation is successful.
109
+ */
110
+ export async function unwindCheckpointsWithContractData(
111
+ store: KVArchiverDataStore,
112
+ from: CheckpointNumber,
113
+ checkpointsToUnwind: number,
114
+ ): Promise<boolean> {
115
+ if (checkpointsToUnwind <= 0) {
116
+ throw new Error(`Cannot unwind ${checkpointsToUnwind} blocks`);
117
+ }
118
+
119
+ const last = await store.getSynchedCheckpointNumber();
120
+ if (from != last) {
121
+ throw new Error(`Cannot unwind checkpoints from checkpoint ${from} when the last checkpoint is ${last}`);
122
+ }
123
+
124
+ const blocks = [];
125
+ const lastCheckpointNumber = from + checkpointsToUnwind - 1;
126
+ for (let checkpointNumber = from; checkpointNumber <= lastCheckpointNumber; checkpointNumber++) {
127
+ const blocksForCheckpoint = await store.getBlocksForCheckpoint(checkpointNumber);
128
+ if (!blocksForCheckpoint) {
129
+ continue;
130
+ }
131
+ blocks.push(...blocksForCheckpoint);
132
+ }
133
+
134
+ const opResults = await Promise.all([
135
+ // Prune rolls back to the last proven block, which is by definition valid
136
+ store.setPendingChainValidationStatus({ valid: true }),
137
+ // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
138
+ ...blocks.map(async block => {
139
+ const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
140
+ // ContractInstancePublished event logs are broadcast in privateLogs.
141
+ const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
142
+ const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
143
+
144
+ return (
145
+ await Promise.all([
146
+ updatePublishedContractClasses(store, contractClassLogs, block.number, Operation.Delete),
147
+ updateDeployedContractInstances(store, privateLogs, block.number, Operation.Delete),
148
+ updateUpdatedContractInstances(store, publicLogs, block.header.globalVariables.timestamp, Operation.Delete),
149
+ ])
150
+ ).every(Boolean);
151
+ }),
152
+
153
+ store.deleteLogs(blocks),
154
+ store.unwindCheckpoints(from, checkpointsToUnwind),
155
+ ]);
156
+
157
+ return opResults.every(Boolean);
158
+ }
159
+
160
+ /**
161
+ * Extracts and stores contract data from a single block.
162
+ */
163
+ async function addBlockDataToDB(store: KVArchiverDataStore, block: L2BlockNew): Promise<boolean> {
164
+ const contractClassLogs = block.body.txEffects.flatMap(txEffect => txEffect.contractClassLogs);
165
+ // ContractInstancePublished event logs are broadcast in privateLogs.
166
+ const privateLogs = block.body.txEffects.flatMap(txEffect => txEffect.privateLogs);
167
+ const publicLogs = block.body.txEffects.flatMap(txEffect => txEffect.publicLogs);
168
+
169
+ return (
170
+ await Promise.all([
171
+ updatePublishedContractClasses(store, contractClassLogs, block.number, Operation.Store),
172
+ updateDeployedContractInstances(store, privateLogs, block.number, Operation.Store),
173
+ updateUpdatedContractInstances(store, publicLogs, block.header.globalVariables.timestamp, Operation.Store),
174
+ storeBroadcastedIndividualFunctions(store, contractClassLogs, block.number),
175
+ ])
176
+ ).every(Boolean);
177
+ }
178
+
179
+ /**
180
+ * Extracts and stores contract classes out of ContractClassPublished events emitted by the class registry contract.
181
+ */
182
+ async function updatePublishedContractClasses(
183
+ store: KVArchiverDataStore,
184
+ allLogs: ContractClassLog[],
185
+ blockNum: BlockNumber,
186
+ operation: Operation,
187
+ ): Promise<boolean> {
188
+ const contractClassPublishedEvents = allLogs
189
+ .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
190
+ .map(log => ContractClassPublishedEvent.fromLog(log));
191
+
192
+ const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
193
+ if (contractClasses.length > 0) {
194
+ contractClasses.forEach(c => log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
195
+ if (operation == Operation.Store) {
196
+ // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
197
+ const commitments = await Promise.all(
198
+ contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
199
+ );
200
+ return await store.addContractClasses(contractClasses, commitments, blockNum);
201
+ } else if (operation == Operation.Delete) {
202
+ return await store.deleteContractClasses(contractClasses, blockNum);
203
+ }
204
+ }
205
+ return true;
206
+ }
207
+
208
+ /**
209
+ * Extracts and stores contract instances out of ContractInstancePublished events emitted by the canonical deployer contract.
210
+ */
211
+ async function updateDeployedContractInstances(
212
+ store: KVArchiverDataStore,
213
+ allLogs: PrivateLog[],
214
+ blockNum: BlockNumber,
215
+ operation: Operation,
216
+ ): Promise<boolean> {
217
+ const contractInstances = allLogs
218
+ .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
219
+ .map(log => ContractInstancePublishedEvent.fromLog(log))
220
+ .map(e => e.toContractInstance());
221
+ if (contractInstances.length > 0) {
222
+ contractInstances.forEach(c => log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`));
223
+ if (operation == Operation.Store) {
224
+ return await store.addContractInstances(contractInstances, blockNum);
225
+ } else if (operation == Operation.Delete) {
226
+ return await store.deleteContractInstances(contractInstances, blockNum);
227
+ }
228
+ }
229
+ return true;
230
+ }
231
+
232
+ /**
233
+ * Extracts and stores contract instance updates out of ContractInstanceUpdated events.
234
+ */
235
+ async function updateUpdatedContractInstances(
236
+ store: KVArchiverDataStore,
237
+ allLogs: PublicLog[],
238
+ timestamp: UInt64,
239
+ operation: Operation,
240
+ ): Promise<boolean> {
241
+ const contractUpdates = allLogs
242
+ .filter(log => ContractInstanceUpdatedEvent.isContractInstanceUpdatedEvent(log))
243
+ .map(log => ContractInstanceUpdatedEvent.fromLog(log))
244
+ .map(e => e.toContractInstanceUpdate());
245
+
246
+ if (contractUpdates.length > 0) {
247
+ contractUpdates.forEach(c =>
248
+ log.verbose(`${Operation[operation]} contract instance update at ${c.address.toString()}`),
249
+ );
250
+ if (operation == Operation.Store) {
251
+ return await store.addContractInstanceUpdates(contractUpdates, timestamp);
252
+ } else if (operation == Operation.Delete) {
253
+ return await store.deleteContractInstanceUpdates(contractUpdates, timestamp);
254
+ }
255
+ }
256
+ return true;
257
+ }
258
+
259
+ /**
260
+ * Stores the functions that were broadcasted individually.
261
+ *
262
+ * @dev Beware that there is not a delete variant of this, since they are added to contract classes
263
+ * and will be deleted as part of the class if needed.
264
+ */
265
+ async function storeBroadcastedIndividualFunctions(
266
+ store: KVArchiverDataStore,
267
+ allLogs: ContractClassLog[],
268
+ _blockNum: BlockNumber,
269
+ ): Promise<boolean> {
270
+ // Filter out private and utility function broadcast events
271
+ const privateFnEvents = allLogs
272
+ .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
273
+ .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
274
+ const utilityFnEvents = allLogs
275
+ .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
276
+ .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
277
+
278
+ // Group all events by contract class id
279
+ for (const [classIdString, classEvents] of Object.entries(
280
+ groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
281
+ )) {
282
+ const contractClassId = Fr.fromHexString(classIdString);
283
+ const contractClass = await store.getContractClass(contractClassId);
284
+ if (!contractClass) {
285
+ log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
286
+ continue;
287
+ }
288
+
289
+ // Split private and utility functions, and filter out invalid ones
290
+ const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
291
+ const privateFns = allFns.filter(
292
+ (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
293
+ );
294
+ const utilityFns = allFns.filter(
295
+ (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
296
+ );
297
+
298
+ const privateFunctionsWithValidity = await Promise.all(
299
+ privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
300
+ );
301
+ const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
302
+ const utilityFunctionsWithValidity = await Promise.all(
303
+ utilityFns.map(async fn => ({
304
+ fn,
305
+ valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
306
+ })),
307
+ );
308
+ const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
309
+ const validFnCount = validPrivateFns.length + validUtilityFns.length;
310
+ if (validFnCount !== allFns.length) {
311
+ log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
312
+ }
313
+
314
+ // Store the functions in the contract class in a single operation
315
+ if (validFnCount > 0) {
316
+ log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
317
+ }
318
+ return await store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
319
+ }
320
+ return true;
321
+ }
@@ -1,6 +1,7 @@
1
1
  export * from './archiver.js';
2
+ export * from './archive_source_base.js';
3
+ export * from './archiver_store_updates.js';
2
4
  export * from './config.js';
3
5
  export { type L1PublishedData } from './structs/published.js';
4
- export type { ArchiverDataStore } from './archiver_store.js';
5
6
  export { KVArchiverDataStore, ARCHIVER_DB_VERSION } from './kv_archiver_store/kv_archiver_store.js';
6
7
  export { ContractInstanceStore } from './kv_archiver_store/contract_instance_store.js';
@@ -76,7 +76,7 @@ export type CheckpointData = {
76
76
  };
77
77
 
78
78
  /**
79
- * LMDB implementation of the ArchiverDataStore interface.
79
+ * LMDB-based block storage for the archiver.
80
80
  */
81
81
  export class BlockStore {
82
82
  /** Map block number to block data */
@@ -12,7 +12,7 @@ import type {
12
12
  import { Vector } from '@aztec/stdlib/types';
13
13
 
14
14
  /**
15
- * LMDB implementation of the ArchiverDataStore interface.
15
+ * LMDB-based contract class storage for the archiver.
16
16
  */
17
17
  export class ContractClassStore {
18
18
  #contractClasses: AztecAsyncMap<string, Buffer>;
@@ -12,7 +12,7 @@ import type { UInt64 } from '@aztec/stdlib/types';
12
12
  type ContractInstanceUpdateKey = [string, string] | [string, string, number];
13
13
 
14
14
  /**
15
- * LMDB implementation of the ArchiverDataStore interface.
15
+ * LMDB-based contract instance storage for the archiver.
16
16
  */
17
17
  export class ContractInstanceStore {
18
18
  #contractInstances: AztecAsyncMap<string, Buffer>;