@aztec/archiver 0.16.4 → 0.16.6

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.
@@ -1,110 +0,0 @@
1
- import { Fr } from '@aztec/foundation/fields';
2
- import { L1ToL2Message } from '@aztec/types';
3
-
4
- /**
5
- * A simple in-memory implementation of an L1 to L2 message store
6
- * that handles message duplication.
7
- */
8
- export class L1ToL2MessageStore {
9
- /**
10
- * A map containing the message key to the corresponding L1 to L2
11
- * messages (and the number of times the message has been seen).
12
- */
13
- protected store: Map<bigint, L1ToL2MessageAndCount> = new Map();
14
- private messagesByBlock = new Set<string>();
15
-
16
- constructor() {}
17
-
18
- addMessage(messageKey: Fr, message: L1ToL2Message, l1BlocKNumber: bigint, messageIndex: number) {
19
- if (this.messagesByBlock.has(`${l1BlocKNumber}-${messageIndex}`)) {
20
- return;
21
- }
22
- this.messagesByBlock.add(`${l1BlocKNumber}-${messageIndex}`);
23
-
24
- this.addMessageUnsafe(messageKey, message);
25
- }
26
-
27
- addMessageUnsafe(messageKey: Fr, message: L1ToL2Message) {
28
- const messageKeyBigInt = messageKey.value;
29
- const msgAndCount = this.store.get(messageKeyBigInt);
30
- if (msgAndCount) {
31
- msgAndCount.count++;
32
- } else {
33
- this.store.set(messageKeyBigInt, { message, count: 1 });
34
- }
35
- }
36
-
37
- getMessage(messageKey: Fr): L1ToL2Message | undefined {
38
- return this.store.get(messageKey.value)?.message;
39
- }
40
-
41
- getMessageAndCount(messageKey: Fr): L1ToL2MessageAndCount | undefined {
42
- return this.store.get(messageKey.value);
43
- }
44
- }
45
-
46
- /**
47
- * Specifically for the store that will hold pending messages
48
- * for removing messages or fetching multiple messages.
49
- */
50
- export class PendingL1ToL2MessageStore extends L1ToL2MessageStore {
51
- private cancelledMessagesByBlock = new Set<string>();
52
- getMessageKeys(limit: number): Fr[] {
53
- if (limit < 1) {
54
- return [];
55
- }
56
- // fetch `limit` number of messages from the store with the highest fee.
57
- // Note the store has multiple of the same message. So if a message has count 2, include both of them in the result:
58
- const messages: Fr[] = [];
59
- const sortedMessages = Array.from(this.store.values()).sort((a, b) => b.message.fee - a.message.fee);
60
- for (const messageAndCount of sortedMessages) {
61
- for (let i = 0; i < messageAndCount.count; i++) {
62
- messages.push(messageAndCount.message.entryKey!);
63
- if (messages.length === limit) {
64
- return messages;
65
- }
66
- }
67
- }
68
- return messages;
69
- }
70
-
71
- removeMessage(messageKey: Fr, l1BlockNumber: bigint, messageIndex: number) {
72
- // ignore 0 - messageKey is a hash, so a 0 can probabilistically never occur. It is best to skip it.
73
- if (messageKey.equals(Fr.ZERO)) {
74
- return;
75
- }
76
-
77
- if (this.cancelledMessagesByBlock.has(`${l1BlockNumber}-${messageIndex}`)) {
78
- return;
79
- }
80
- this.cancelledMessagesByBlock.add(`${l1BlockNumber}-${messageIndex}`);
81
- this.removeMessageUnsafe(messageKey);
82
- }
83
-
84
- removeMessageUnsafe(messageKey: Fr) {
85
- const messageKeyBigInt = messageKey.value;
86
- const msgAndCount = this.store.get(messageKeyBigInt);
87
- if (!msgAndCount) {
88
- throw new Error(`Unable to remove message: L1 to L2 Message with key ${messageKeyBigInt} not found in store`);
89
- }
90
- if (msgAndCount.count > 1) {
91
- msgAndCount.count--;
92
- } else {
93
- this.store.delete(messageKeyBigInt);
94
- }
95
- }
96
- }
97
-
98
- /**
99
- * Useful to keep track of the number of times a message has been seen.
100
- */
101
- type L1ToL2MessageAndCount = {
102
- /**
103
- * The message.
104
- */
105
- message: L1ToL2Message;
106
- /**
107
- * The number of times the message has been seen.
108
- */
109
- count: number;
110
- };
@@ -1,399 +0,0 @@
1
- import { Fr, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/circuits.js';
2
- import { AztecAddress } from '@aztec/foundation/aztec-address';
3
- import {
4
- CancelledL1ToL2Message,
5
- ContractData,
6
- ExtendedContractData,
7
- ExtendedUnencryptedL2Log,
8
- GetUnencryptedLogsResponse,
9
- INITIAL_L2_BLOCK_NUM,
10
- L1ToL2Message,
11
- L2Block,
12
- L2BlockContext,
13
- L2BlockL2Logs,
14
- L2Tx,
15
- LogFilter,
16
- LogId,
17
- LogType,
18
- PendingL1ToL2Message,
19
- TxHash,
20
- UnencryptedL2Log,
21
- } from '@aztec/types';
22
-
23
- import { ArchiverDataStore } from '../archiver_store.js';
24
- import { L1ToL2MessageStore, PendingL1ToL2MessageStore } from './l1_to_l2_message_store.js';
25
-
26
- /**
27
- * Simple, in-memory implementation of an archiver data store.
28
- */
29
- export class MemoryArchiverStore implements ArchiverDataStore {
30
- /**
31
- * An array containing all the L2 blocks that have been fetched so far.
32
- */
33
- private l2BlockContexts: L2BlockContext[] = [];
34
-
35
- /**
36
- * An array containing all the L2 Txs in the L2 blocks that have been fetched so far.
37
- */
38
- private l2Txs: L2Tx[] = [];
39
-
40
- /**
41
- * An array containing all the encrypted logs that have been fetched so far.
42
- * Note: Index in the "outer" array equals to (corresponding L2 block's number - INITIAL_L2_BLOCK_NUM).
43
- */
44
- private encryptedLogsPerBlock: L2BlockL2Logs[] = [];
45
-
46
- /**
47
- * An array containing all the unencrypted logs that have been fetched so far.
48
- * Note: Index in the "outer" array equals to (corresponding L2 block's number - INITIAL_L2_BLOCK_NUM).
49
- */
50
- private unencryptedLogsPerBlock: L2BlockL2Logs[] = [];
51
-
52
- /**
53
- * A sparse array containing all the extended contract data that have been fetched so far.
54
- */
55
- private extendedContractDataByBlock: (ExtendedContractData[] | undefined)[] = [];
56
-
57
- /**
58
- * A mapping of contract address to extended contract data.
59
- */
60
- private extendedContractData: Map<string, ExtendedContractData> = new Map();
61
-
62
- /**
63
- * Contains all the confirmed L1 to L2 messages (i.e. messages that were consumed in an L2 block)
64
- * It is a map of entryKey to the corresponding L1 to L2 message and the number of times it has appeared
65
- */
66
- private confirmedL1ToL2Messages: L1ToL2MessageStore = new L1ToL2MessageStore();
67
-
68
- /**
69
- * Contains all the pending L1 to L2 messages (accounts for duplication of messages)
70
- */
71
- private pendingL1ToL2Messages: PendingL1ToL2MessageStore = new PendingL1ToL2MessageStore();
72
-
73
- constructor(
74
- /** The max number of logs that can be obtained in 1 "getUnencryptedLogs" call. */
75
- public readonly maxLogs: number,
76
- ) {}
77
-
78
- /**
79
- * Append new blocks to the store's list.
80
- * @param blocks - The L2 blocks to be added to the store.
81
- * @returns True if the operation is successful (always in this implementation).
82
- */
83
- public addBlocks(blocks: L2Block[]): Promise<boolean> {
84
- this.l2BlockContexts.push(...blocks.map(block => new L2BlockContext(block)));
85
- this.l2Txs.push(...blocks.flatMap(b => b.getTxs()));
86
- return Promise.resolve(true);
87
- }
88
-
89
- /**
90
- * Append new logs to the store's list.
91
- * @param encryptedLogs - The encrypted logs to be added to the store.
92
- * @param unencryptedLogs - The unencrypted logs to be added to the store.
93
- * @param blockNumber - The block for which to add the logs.
94
- * @returns True if the operation is successful.
95
- */
96
- addLogs(encryptedLogs: L2BlockL2Logs, unencryptedLogs: L2BlockL2Logs, blockNumber: number): Promise<boolean> {
97
- if (encryptedLogs) {
98
- this.encryptedLogsPerBlock[blockNumber - INITIAL_L2_BLOCK_NUM] = encryptedLogs;
99
- }
100
-
101
- if (unencryptedLogs) {
102
- this.unencryptedLogsPerBlock[blockNumber - INITIAL_L2_BLOCK_NUM] = unencryptedLogs;
103
- }
104
-
105
- return Promise.resolve(true);
106
- }
107
-
108
- /**
109
- * Append new pending L1 to L2 messages to the store.
110
- * @param messages - The L1 to L2 messages to be added to the store.
111
- * @returns True if the operation is successful (always in this implementation).
112
- */
113
- public addPendingL1ToL2Messages(messages: PendingL1ToL2Message[]): Promise<boolean> {
114
- for (const { message, blockNumber, indexInBlock } of messages) {
115
- this.pendingL1ToL2Messages.addMessage(message.entryKey!, message, blockNumber, indexInBlock);
116
- }
117
- return Promise.resolve(true);
118
- }
119
-
120
- /**
121
- * Remove pending L1 to L2 messages from the store (if they were cancelled).
122
- * @param messages - The message keys to be removed from the store.
123
- * @returns True if the operation is successful (always in this implementation).
124
- */
125
- public cancelPendingL1ToL2Messages(messages: CancelledL1ToL2Message[]): Promise<boolean> {
126
- messages.forEach(({ entryKey, blockNumber, indexInBlock }) => {
127
- this.pendingL1ToL2Messages.removeMessage(entryKey, blockNumber, indexInBlock);
128
- });
129
- return Promise.resolve(true);
130
- }
131
-
132
- /**
133
- * Messages that have been published in an L2 block are confirmed.
134
- * Add them to the confirmed store, also remove them from the pending store.
135
- * @param messageKeys - The message keys to be removed from the store.
136
- * @returns True if the operation is successful (always in this implementation).
137
- */
138
- public confirmL1ToL2Messages(messageKeys: Fr[]): Promise<boolean> {
139
- messageKeys.forEach(messageKey => {
140
- this.confirmedL1ToL2Messages.addMessageUnsafe(messageKey, this.pendingL1ToL2Messages.getMessage(messageKey)!);
141
- this.pendingL1ToL2Messages.removeMessageUnsafe(messageKey);
142
- });
143
- return Promise.resolve(true);
144
- }
145
-
146
- /**
147
- * Store new extended contract data from an L2 block to the store's list.
148
- * @param data - List of contracts' data to be added.
149
- * @param blockNum - Number of the L2 block the contract data was deployed in.
150
- * @returns True if the operation is successful (always in this implementation).
151
- */
152
- public addExtendedContractData(data: ExtendedContractData[], blockNum: number): Promise<boolean> {
153
- // Add to the contracts mapping
154
- for (const contractData of data) {
155
- const key = contractData.contractData.contractAddress.toString();
156
- this.extendedContractData.set(key, contractData);
157
- }
158
-
159
- // Add the index per block
160
- if (this.extendedContractDataByBlock[blockNum]?.length) {
161
- this.extendedContractDataByBlock[blockNum]?.push(...data);
162
- } else {
163
- this.extendedContractDataByBlock[blockNum] = [...data];
164
- }
165
- return Promise.resolve(true);
166
- }
167
-
168
- /**
169
- * Gets up to `limit` amount of L2 blocks starting from `from`.
170
- * @param from - Number of the first block to return (inclusive).
171
- * @param limit - The number of blocks to return.
172
- * @returns The requested L2 blocks.
173
- * @remarks When "from" is smaller than genesis block number, blocks from the beginning are returned.
174
- */
175
- public getBlocks(from: number, limit: number): Promise<L2Block[]> {
176
- // Return an empty array if we are outside of range
177
- if (limit < 1) {
178
- return Promise.reject(new Error(`Invalid limit: ${limit}`));
179
- }
180
-
181
- const fromIndex = Math.max(from - INITIAL_L2_BLOCK_NUM, 0);
182
- if (fromIndex >= this.l2BlockContexts.length) {
183
- return Promise.resolve([]);
184
- }
185
-
186
- const toIndex = fromIndex + limit;
187
- return Promise.resolve(this.l2BlockContexts.slice(fromIndex, toIndex).map(blockContext => blockContext.block));
188
- }
189
-
190
- /**
191
- * Gets an l2 tx.
192
- * @param txHash - The txHash of the l2 tx.
193
- * @returns The requested L2 tx.
194
- */
195
- public getL2Tx(txHash: TxHash): Promise<L2Tx | undefined> {
196
- const l2Tx = this.l2Txs.find(tx => tx.txHash.equals(txHash));
197
- return Promise.resolve(l2Tx);
198
- }
199
-
200
- /**
201
- * Gets up to `limit` amount of pending L1 to L2 messages, sorted by fee
202
- * @param limit - The number of messages to return (by default NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP).
203
- * @returns The requested L1 to L2 message keys.
204
- */
205
- public getPendingL1ToL2MessageKeys(limit: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP): Promise<Fr[]> {
206
- return Promise.resolve(this.pendingL1ToL2Messages.getMessageKeys(limit));
207
- }
208
-
209
- /**
210
- * Gets the confirmed L1 to L2 message corresponding to the given message key.
211
- * @param messageKey - The message key to look up.
212
- * @returns The requested L1 to L2 message or throws if not found.
213
- */
214
- public getConfirmedL1ToL2Message(messageKey: Fr): Promise<L1ToL2Message> {
215
- const message = this.confirmedL1ToL2Messages.getMessage(messageKey);
216
- if (!message) {
217
- throw new Error(`L1 to L2 Message with key ${messageKey.toString()} not found in the confirmed messages store`);
218
- }
219
- return Promise.resolve(message);
220
- }
221
-
222
- /**
223
- * Gets up to `limit` amount of logs starting from `from`.
224
- * @param from - Number of the L2 block to which corresponds the first logs to be returned.
225
- * @param limit - The number of logs to return.
226
- * @param logType - Specifies whether to return encrypted or unencrypted logs.
227
- * @returns The requested logs.
228
- */
229
- getLogs(from: number, limit: number, logType: LogType): Promise<L2BlockL2Logs[]> {
230
- if (from < INITIAL_L2_BLOCK_NUM || limit < 1) {
231
- throw new Error(`Invalid limit: ${limit}`);
232
- }
233
- const logs = logType === LogType.ENCRYPTED ? this.encryptedLogsPerBlock : this.unencryptedLogsPerBlock;
234
- if (from > logs.length) {
235
- return Promise.resolve([]);
236
- }
237
- const startIndex = from - INITIAL_L2_BLOCK_NUM;
238
- const endIndex = startIndex + limit;
239
- return Promise.resolve(logs.slice(startIndex, endIndex));
240
- }
241
-
242
- /**
243
- * Gets unencrypted logs based on the provided filter.
244
- * @param filter - The filter to apply to the logs.
245
- * @returns The requested logs.
246
- * @remarks Works by doing an intersection of all params in the filter.
247
- */
248
- getUnencryptedLogs(filter: LogFilter): Promise<GetUnencryptedLogsResponse> {
249
- let txHash: TxHash | undefined;
250
- let fromBlockIndex = 0;
251
- let toBlockIndex = this.unencryptedLogsPerBlock.length;
252
- let txIndexInBlock = 0;
253
- let logIndexInTx = 0;
254
-
255
- if (filter.afterLog) {
256
- // Continuation parameter is set --> tx hash is ignored
257
- if (filter.fromBlock == undefined || filter.fromBlock <= filter.afterLog.blockNumber) {
258
- fromBlockIndex = filter.afterLog.blockNumber - INITIAL_L2_BLOCK_NUM;
259
- txIndexInBlock = filter.afterLog.txIndex;
260
- logIndexInTx = filter.afterLog.logIndex + 1; // We want to start from the next log
261
- } else {
262
- fromBlockIndex = filter.fromBlock - INITIAL_L2_BLOCK_NUM;
263
- }
264
- } else {
265
- txHash = filter.txHash;
266
-
267
- if (filter.fromBlock !== undefined) {
268
- fromBlockIndex = filter.fromBlock - INITIAL_L2_BLOCK_NUM;
269
- }
270
- }
271
-
272
- if (filter.toBlock !== undefined) {
273
- toBlockIndex = filter.toBlock - INITIAL_L2_BLOCK_NUM;
274
- }
275
-
276
- // Ensure the indices are within block array bounds
277
- fromBlockIndex = Math.max(fromBlockIndex, 0);
278
- toBlockIndex = Math.min(toBlockIndex, this.unencryptedLogsPerBlock.length);
279
-
280
- if (fromBlockIndex > this.unencryptedLogsPerBlock.length || toBlockIndex < fromBlockIndex || toBlockIndex <= 0) {
281
- return Promise.resolve({
282
- logs: [],
283
- maxLogsHit: false,
284
- });
285
- }
286
-
287
- const contractAddress = filter.contractAddress;
288
- const selector = filter.selector;
289
-
290
- const logs: ExtendedUnencryptedL2Log[] = [];
291
-
292
- for (; fromBlockIndex < toBlockIndex; fromBlockIndex++) {
293
- const blockContext = this.l2BlockContexts[fromBlockIndex];
294
- const blockLogs = this.unencryptedLogsPerBlock[fromBlockIndex];
295
- for (; txIndexInBlock < blockLogs.txLogs.length; txIndexInBlock++) {
296
- const txLogs = blockLogs.txLogs[txIndexInBlock].unrollLogs().map(log => UnencryptedL2Log.fromBuffer(log));
297
- for (; logIndexInTx < txLogs.length; logIndexInTx++) {
298
- const log = txLogs[logIndexInTx];
299
- if (
300
- (!txHash || blockContext.getTxHash(txIndexInBlock).equals(txHash)) &&
301
- (!contractAddress || log.contractAddress.equals(contractAddress)) &&
302
- (!selector || log.selector.equals(selector))
303
- ) {
304
- logs.push(
305
- new ExtendedUnencryptedL2Log(new LogId(blockContext.block.number, txIndexInBlock, logIndexInTx), log),
306
- );
307
- if (logs.length === this.maxLogs) {
308
- return Promise.resolve({
309
- logs,
310
- maxLogsHit: true,
311
- });
312
- }
313
- }
314
- }
315
- logIndexInTx = 0;
316
- }
317
- txIndexInBlock = 0;
318
- }
319
-
320
- return Promise.resolve({
321
- logs,
322
- maxLogsHit: false,
323
- });
324
- }
325
-
326
- /**
327
- * Get the extended contract data for this contract.
328
- * @param contractAddress - The contract data address.
329
- * @returns The extended contract data or undefined if not found.
330
- */
331
- getExtendedContractData(contractAddress: AztecAddress): Promise<ExtendedContractData | undefined> {
332
- const result = this.extendedContractData.get(contractAddress.toString());
333
- return Promise.resolve(result);
334
- }
335
-
336
- /**
337
- * Lookup all contract data in an L2 block.
338
- * @param blockNum - The block number to get all contract data from.
339
- * @returns All extended contract data in the block (if found).
340
- */
341
- public getExtendedContractDataInBlock(blockNum: number): Promise<ExtendedContractData[]> {
342
- if (blockNum > this.l2BlockContexts.length) {
343
- return Promise.resolve([]);
344
- }
345
- return Promise.resolve(this.extendedContractDataByBlock[blockNum] || []);
346
- }
347
-
348
- /**
349
- * Get basic info for an L2 contract.
350
- * Contains contract address & the ethereum portal address.
351
- * @param contractAddress - The contract data address.
352
- * @returns ContractData with the portal address (if we didn't throw an error).
353
- */
354
- public getContractData(contractAddress: AztecAddress): Promise<ContractData | undefined> {
355
- if (contractAddress.isZero()) {
356
- return Promise.resolve(undefined);
357
- }
358
- for (const blockContext of this.l2BlockContexts) {
359
- for (const contractData of blockContext.block.newContractData) {
360
- if (contractData.contractAddress.equals(contractAddress)) {
361
- return Promise.resolve(contractData);
362
- }
363
- }
364
- }
365
- return Promise.resolve(undefined);
366
- }
367
-
368
- /**
369
- * Get basic info for an all L2 contracts deployed in a block.
370
- * Contains contract address & the ethereum portal address.
371
- * @param l2BlockNum - Number of the L2 block where contracts were deployed.
372
- * @returns ContractData with the portal address (if we didn't throw an error).
373
- */
374
- public getContractDataInBlock(l2BlockNum: number): Promise<ContractData[] | undefined> {
375
- if (l2BlockNum > this.l2BlockContexts.length) {
376
- return Promise.resolve([]);
377
- }
378
- const block: L2Block | undefined = this.l2BlockContexts[l2BlockNum - INITIAL_L2_BLOCK_NUM]?.block;
379
- return Promise.resolve(block?.newContractData);
380
- }
381
-
382
- /**
383
- * Gets the number of the latest L2 block processed.
384
- * @returns The number of the latest L2 block processed.
385
- */
386
- public getBlockNumber(): Promise<number> {
387
- if (this.l2BlockContexts.length === 0) {
388
- return Promise.resolve(INITIAL_L2_BLOCK_NUM - 1);
389
- }
390
- return Promise.resolve(this.l2BlockContexts[this.l2BlockContexts.length - 1].block.number);
391
- }
392
-
393
- public getL1BlockNumber(): Promise<bigint> {
394
- if (this.l2BlockContexts.length === 0) {
395
- return Promise.resolve(0n);
396
- }
397
- return Promise.resolve(this.l2BlockContexts[this.l2BlockContexts.length - 1].block.getL1BlockNumber());
398
- }
399
- }
package/src/index.ts DELETED
@@ -1,53 +0,0 @@
1
- import { createDebugLogger } from '@aztec/foundation/log';
2
- import { fileURLToPath } from '@aztec/foundation/url';
3
-
4
- import { createPublicClient, http } from 'viem';
5
- import { localhost } from 'viem/chains';
6
-
7
- import { Archiver, getConfigEnvVars } from './archiver/index.js';
8
- import { MemoryArchiverStore } from './archiver/memory_archiver_store/memory_archiver_store.js';
9
-
10
- export * from './archiver/index.js';
11
-
12
- const log = createDebugLogger('aztec:archiver');
13
-
14
- /**
15
- * A function which instantiates and starts Archiver.
16
- */
17
- // eslint-disable-next-line require-await
18
- async function main() {
19
- const config = getConfigEnvVars();
20
- const { rpcUrl, l1Contracts } = config;
21
-
22
- const publicClient = createPublicClient({
23
- chain: localhost,
24
- transport: http(rpcUrl),
25
- });
26
-
27
- const archiverStore = new MemoryArchiverStore(1000);
28
-
29
- const archiver = new Archiver(
30
- publicClient,
31
- l1Contracts.rollupAddress,
32
- l1Contracts.inboxAddress,
33
- l1Contracts.registryAddress,
34
- l1Contracts.contractDeploymentEmitterAddress,
35
- archiverStore,
36
- );
37
-
38
- const shutdown = async () => {
39
- await archiver.stop();
40
- process.exit(0);
41
- };
42
- process.once('SIGINT', shutdown);
43
- process.once('SIGTERM', shutdown);
44
- }
45
-
46
- // See https://twitter.com/Rich_Harris/status/1355289863130673153
47
- if (process.argv[1] === fileURLToPath(import.meta.url).replace(/\/index\.js$/, '')) {
48
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
49
- main().catch(err => {
50
- log.error(err);
51
- process.exit(1);
52
- });
53
- }