@aztec/archiver 0.0.1-commit.db765a8 → 0.0.1-commit.df81a97b5

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 (69) hide show
  1. package/dest/archiver.d.ts +3 -4
  2. package/dest/archiver.d.ts.map +1 -1
  3. package/dest/archiver.js +54 -19
  4. package/dest/config.d.ts +3 -3
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +2 -1
  7. package/dest/errors.d.ts +21 -9
  8. package/dest/errors.d.ts.map +1 -1
  9. package/dest/errors.js +27 -14
  10. package/dest/factory.d.ts +4 -5
  11. package/dest/factory.d.ts.map +1 -1
  12. package/dest/factory.js +24 -21
  13. package/dest/modules/data_source_base.d.ts +5 -5
  14. package/dest/modules/data_source_base.d.ts.map +1 -1
  15. package/dest/modules/data_source_base.js +5 -5
  16. package/dest/modules/data_store_updater.d.ts +17 -12
  17. package/dest/modules/data_store_updater.d.ts.map +1 -1
  18. package/dest/modules/data_store_updater.js +78 -77
  19. package/dest/modules/l1_synchronizer.d.ts +2 -1
  20. package/dest/modules/l1_synchronizer.d.ts.map +1 -1
  21. package/dest/modules/l1_synchronizer.js +37 -7
  22. package/dest/store/block_store.d.ts +12 -13
  23. package/dest/store/block_store.d.ts.map +1 -1
  24. package/dest/store/block_store.js +61 -61
  25. package/dest/store/contract_class_store.d.ts +2 -3
  26. package/dest/store/contract_class_store.d.ts.map +1 -1
  27. package/dest/store/contract_class_store.js +7 -67
  28. package/dest/store/contract_instance_store.d.ts +1 -1
  29. package/dest/store/contract_instance_store.d.ts.map +1 -1
  30. package/dest/store/contract_instance_store.js +6 -2
  31. package/dest/store/kv_archiver_store.d.ts +28 -18
  32. package/dest/store/kv_archiver_store.d.ts.map +1 -1
  33. package/dest/store/kv_archiver_store.js +34 -21
  34. package/dest/store/log_store.d.ts +6 -3
  35. package/dest/store/log_store.d.ts.map +1 -1
  36. package/dest/store/log_store.js +93 -16
  37. package/dest/store/message_store.d.ts +5 -1
  38. package/dest/store/message_store.d.ts.map +1 -1
  39. package/dest/store/message_store.js +14 -1
  40. package/dest/test/fake_l1_state.d.ts +8 -1
  41. package/dest/test/fake_l1_state.d.ts.map +1 -1
  42. package/dest/test/fake_l1_state.js +39 -5
  43. package/dest/test/mock_l2_block_source.d.ts +4 -3
  44. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  45. package/dest/test/mock_l2_block_source.js +7 -4
  46. package/dest/test/mock_structs.d.ts +4 -1
  47. package/dest/test/mock_structs.d.ts.map +1 -1
  48. package/dest/test/mock_structs.js +13 -1
  49. package/dest/test/noop_l1_archiver.d.ts +4 -1
  50. package/dest/test/noop_l1_archiver.d.ts.map +1 -1
  51. package/dest/test/noop_l1_archiver.js +5 -1
  52. package/package.json +13 -13
  53. package/src/archiver.ts +60 -20
  54. package/src/config.ts +8 -1
  55. package/src/errors.ts +40 -24
  56. package/src/factory.ts +23 -15
  57. package/src/modules/data_source_base.ts +11 -6
  58. package/src/modules/data_store_updater.ts +83 -107
  59. package/src/modules/l1_synchronizer.ts +47 -13
  60. package/src/store/block_store.ts +72 -69
  61. package/src/store/contract_class_store.ts +8 -106
  62. package/src/store/contract_instance_store.ts +8 -5
  63. package/src/store/kv_archiver_store.ts +43 -32
  64. package/src/store/log_store.ts +126 -27
  65. package/src/store/message_store.ts +20 -1
  66. package/src/test/fake_l1_state.ts +50 -9
  67. package/src/test/mock_l2_block_source.ts +15 -3
  68. package/src/test/mock_structs.ts +20 -6
  69. package/src/test/noop_l1_archiver.ts +7 -1
package/src/errors.ts CHANGED
@@ -6,24 +6,9 @@ export class NoBlobBodiesFoundError extends Error {
6
6
  }
7
7
  }
8
8
 
9
- export class InitialBlockNumberNotSequentialError extends Error {
10
- constructor(
11
- public readonly newBlockNumber: number,
12
- public readonly previousBlockNumber: number | undefined,
13
- ) {
14
- super(
15
- `Cannot insert new block ${newBlockNumber} given previous block number in store is ${
16
- previousBlockNumber ?? 'undefined'
17
- }`,
18
- );
19
- }
20
- }
21
-
22
9
  export class BlockNumberNotSequentialError extends Error {
23
10
  constructor(newBlockNumber: number, previous: number | undefined) {
24
- super(
25
- `Cannot insert new block ${newBlockNumber} given previous block number in batch is ${previous ?? 'undefined'}`,
26
- );
11
+ super(`Cannot insert new block ${newBlockNumber} given previous block number is ${previous ?? 'undefined'}`);
27
12
  }
28
13
  }
29
14
 
@@ -48,14 +33,6 @@ export class CheckpointNumberNotSequentialError extends Error {
48
33
  }
49
34
  }
50
35
 
51
- export class CheckpointNumberNotConsistentError extends Error {
52
- constructor(newCheckpointNumber: number, previous: number | undefined) {
53
- super(
54
- `Cannot insert block for new checkpoint ${newCheckpointNumber} given previous block was checkpoint ${previous ?? 'undefined'}`,
55
- );
56
- }
57
- }
58
-
59
36
  export class BlockIndexNotSequentialError extends Error {
60
37
  constructor(newBlockIndex: number, previousBlockIndex: number | undefined) {
61
38
  super(
@@ -89,6 +66,45 @@ export class BlockNotFoundError extends Error {
89
66
  }
90
67
  }
91
68
 
69
+ /** Thrown when a proposed block matches a block that was already checkpointed. This is expected for late proposals. */
70
+ export class BlockAlreadyCheckpointedError extends Error {
71
+ constructor(public readonly blockNumber: number) {
72
+ super(`Block ${blockNumber} has already been checkpointed with the same content`);
73
+ this.name = 'BlockAlreadyCheckpointedError';
74
+ }
75
+ }
76
+
77
+ /** Thrown when logs are added for a tag whose last stored log has a higher block number than the new log. */
78
+ export class OutOfOrderLogInsertionError extends Error {
79
+ constructor(
80
+ public readonly logType: 'private' | 'public',
81
+ public readonly tag: string,
82
+ public readonly lastBlockNumber: number,
83
+ public readonly newBlockNumber: number,
84
+ ) {
85
+ super(
86
+ `Out-of-order ${logType} log insertion for tag ${tag}: ` +
87
+ `last existing log is from block ${lastBlockNumber} but new log is from block ${newBlockNumber}`,
88
+ );
89
+ this.name = 'OutOfOrderLogInsertionError';
90
+ }
91
+ }
92
+
93
+ /** Thrown when L1 to L2 messages are requested for a checkpoint whose message tree hasn't been sealed yet. */
94
+ export class L1ToL2MessagesNotReadyError extends Error {
95
+ constructor(
96
+ public readonly checkpointNumber: number,
97
+ public readonly inboxTreeInProgress: bigint,
98
+ ) {
99
+ super(
100
+ `Cannot get L1 to L2 messages for checkpoint ${checkpointNumber}: ` +
101
+ `inbox tree in progress is ${inboxTreeInProgress}, messages not yet sealed`,
102
+ );
103
+ this.name = 'L1ToL2MessagesNotReadyError';
104
+ }
105
+ }
106
+
107
+ /** Thrown when a proposed block conflicts with an already checkpointed block (different content). */
92
108
  export class CannotOverwriteCheckpointedBlockError extends Error {
93
109
  constructor(
94
110
  public readonly blockNumber: number,
package/src/factory.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { EpochCache } from '@aztec/epoch-cache';
2
2
  import { createEthereumChain } from '@aztec/ethereum/chain';
3
+ import { makeL1HttpTransport } from '@aztec/ethereum/client';
3
4
  import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
4
5
  import type { ViemPublicDebugClient } from '@aztec/ethereum/types';
5
6
  import { BlockNumber } from '@aztec/foundation/branded-types';
@@ -7,18 +8,17 @@ import { Buffer32 } from '@aztec/foundation/buffer';
7
8
  import { merge } from '@aztec/foundation/collection';
8
9
  import { Fr } from '@aztec/foundation/curves/bn254';
9
10
  import { DateProvider } from '@aztec/foundation/timer';
10
- import type { DataStoreConfig } from '@aztec/kv-store/config';
11
11
  import { createStore } from '@aztec/kv-store/lmdb-v2';
12
12
  import { protocolContractNames } from '@aztec/protocol-contracts';
13
13
  import { BundledProtocolContractsProvider } from '@aztec/protocol-contracts/providers/bundle';
14
14
  import { FunctionType, decodeFunctionSignature } from '@aztec/stdlib/abi';
15
15
  import type { ArchiverEmitter } from '@aztec/stdlib/block';
16
- import { type ContractClassPublic, computePublicBytecodeCommitment } from '@aztec/stdlib/contract';
17
- import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
16
+ import { type ContractClassPublicWithCommitment, computePublicBytecodeCommitment } from '@aztec/stdlib/contract';
17
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
18
18
  import { getTelemetryClient } from '@aztec/telemetry-client';
19
19
 
20
20
  import { EventEmitter } from 'events';
21
- import { createPublicClient, fallback, http } from 'viem';
21
+ import { createPublicClient } from 'viem';
22
22
 
23
23
  import { Archiver, type ArchiverDeps } from './archiver.js';
24
24
  import { type ArchiverConfig, mapArchiverConfig } from './config.js';
@@ -32,14 +32,13 @@ export const ARCHIVER_STORE_NAME = 'archiver';
32
32
  /** Creates an archiver store. */
33
33
  export async function createArchiverStore(
34
34
  userConfig: Pick<ArchiverConfig, 'archiverStoreMapSizeKb' | 'maxLogs'> & DataStoreConfig,
35
- l1Constants: Pick<L1RollupConstants, 'epochDuration'>,
36
35
  ) {
37
36
  const config = {
38
37
  ...userConfig,
39
38
  dataStoreMapSizeKb: userConfig.archiverStoreMapSizeKb ?? userConfig.dataStoreMapSizeKb,
40
39
  };
41
40
  const store = await createStore(ARCHIVER_STORE_NAME, ARCHIVER_DB_VERSION, config);
42
- return new KVArchiverDataStore(store, config.maxLogs, l1Constants);
41
+ return new KVArchiverDataStore(store, config.maxLogs);
43
42
  }
44
43
 
45
44
  /**
@@ -54,14 +53,15 @@ export async function createArchiver(
54
53
  deps: ArchiverDeps,
55
54
  opts: { blockUntilSync: boolean } = { blockUntilSync: true },
56
55
  ): Promise<Archiver> {
57
- const archiverStore = await createArchiverStore(config, { epochDuration: config.aztecEpochDuration });
56
+ const archiverStore = await createArchiverStore(config);
58
57
  await registerProtocolContracts(archiverStore);
59
58
 
60
59
  // Create Ethereum clients
61
60
  const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
61
+ const httpTimeout = config.l1HttpTimeoutMS;
62
62
  const publicClient = createPublicClient({
63
63
  chain: chain.chainInfo,
64
- transport: fallback(config.l1RpcUrls.map(url => http(url, { batch: false }))),
64
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: httpTimeout }),
65
65
  pollingInterval: config.viemPollingIntervalMS,
66
66
  });
67
67
 
@@ -69,7 +69,7 @@ export async function createArchiver(
69
69
  const debugRpcUrls = config.l1DebugRpcUrls.length > 0 ? config.l1DebugRpcUrls : config.l1RpcUrls;
70
70
  const debugClient = createPublicClient({
71
71
  chain: chain.chainInfo,
72
- transport: fallback(debugRpcUrls.map(url => http(url, { batch: false }))),
72
+ transport: makeL1HttpTransport(debugRpcUrls, { timeout: httpTimeout }),
73
73
  pollingInterval: config.viemPollingIntervalMS,
74
74
  }) as ViemPublicDebugClient;
75
75
 
@@ -85,6 +85,7 @@ export async function createArchiver(
85
85
  genesisArchiveRoot,
86
86
  slashingProposerAddress,
87
87
  targetCommitteeSize,
88
+ rollupManaLimit,
88
89
  ] = await Promise.all([
89
90
  rollup.getL1StartBlock(),
90
91
  rollup.getL1GenesisTime(),
@@ -92,6 +93,7 @@ export async function createArchiver(
92
93
  rollup.getGenesisArchiveTreeRoot(),
93
94
  rollup.getSlashingProposerAddress(),
94
95
  rollup.getTargetCommitteeSize(),
96
+ rollup.getManaLimit(),
95
97
  ] as const);
96
98
 
97
99
  const l1StartBlockHash = await publicClient
@@ -110,6 +112,7 @@ export async function createArchiver(
110
112
  proofSubmissionEpochs: Number(proofSubmissionEpochs),
111
113
  targetCommitteeSize,
112
114
  genesisArchiveRoot: Fr.fromString(genesisArchiveRoot.toString()),
115
+ rollupManaLimit: Number(rollupManaLimit),
113
116
  };
114
117
 
115
118
  const archiverConfig = merge(
@@ -170,16 +173,22 @@ export async function createArchiver(
170
173
  return archiver;
171
174
  }
172
175
 
173
- /** Registers protocol contracts in the archiver store. */
176
+ /** Registers protocol contracts in the archiver store. Idempotent — skips contracts that already exist (e.g. on node restart). */
174
177
  export async function registerProtocolContracts(store: KVArchiverDataStore) {
175
178
  const blockNumber = 0;
176
179
  for (const name of protocolContractNames) {
177
180
  const provider = new BundledProtocolContractsProvider();
178
181
  const contract = await provider.getProtocolContractArtifact(name);
179
- const contractClassPublic: ContractClassPublic = {
182
+
183
+ // Skip if already registered (happens on node restart with a persisted store).
184
+ if (await store.getContractClass(contract.contractClass.id)) {
185
+ continue;
186
+ }
187
+
188
+ const publicBytecodeCommitment = await computePublicBytecodeCommitment(contract.contractClass.packedBytecode);
189
+ const contractClassPublic: ContractClassPublicWithCommitment = {
180
190
  ...contract.contractClass,
181
- privateFunctions: [],
182
- utilityFunctions: [],
191
+ publicBytecodeCommitment,
183
192
  };
184
193
 
185
194
  const publicFunctionSignatures = contract.artifact.functions
@@ -187,8 +196,7 @@ export async function registerProtocolContracts(store: KVArchiverDataStore) {
187
196
  .map(fn => decodeFunctionSignature(fn.name, fn.parameters));
188
197
 
189
198
  await store.registerContractFunctionSignatures(publicFunctionSignatures);
190
- const bytecodeCommitment = await computePublicBytecodeCommitment(contractClassPublic.packedBytecode);
191
- await store.addContractClasses([contractClassPublic], [bytecodeCommitment], BlockNumber(blockNumber));
199
+ await store.addContractClasses([contractClassPublic], BlockNumber(blockNumber));
192
200
  await store.addContractInstances([contract.instance], BlockNumber(blockNumber));
193
201
  }
194
202
  }
@@ -46,9 +46,9 @@ export abstract class ArchiverDataSourceBase
46
46
 
47
47
  abstract getL2Tips(): Promise<L2Tips>;
48
48
 
49
- abstract getL2SlotNumber(): Promise<SlotNumber | undefined>;
49
+ abstract getSyncedL2SlotNumber(): Promise<SlotNumber | undefined>;
50
50
 
51
- abstract getL2EpochNumber(): Promise<EpochNumber | undefined>;
51
+ abstract getSyncedL2EpochNumber(): Promise<EpochNumber | undefined>;
52
52
 
53
53
  abstract isEpochComplete(epochNumber: EpochNumber): Promise<boolean>;
54
54
 
@@ -154,7 +154,7 @@ export abstract class ArchiverDataSourceBase
154
154
  }
155
155
 
156
156
  public getSettledTxReceipt(txHash: TxHash): Promise<TxReceipt | undefined> {
157
- return this.store.getSettledTxReceipt(txHash);
157
+ return this.store.getSettledTxReceipt(txHash, this.l1Constants);
158
158
  }
159
159
 
160
160
  public isPendingChainInvalid(): Promise<boolean> {
@@ -165,16 +165,21 @@ export abstract class ArchiverDataSourceBase
165
165
  return (await this.store.getPendingChainValidationStatus()) ?? { valid: true };
166
166
  }
167
167
 
168
- public getPrivateLogsByTags(tags: SiloedTag[], page?: number): Promise<TxScopedL2Log[][]> {
169
- return this.store.getPrivateLogsByTags(tags, page);
168
+ public getPrivateLogsByTags(
169
+ tags: SiloedTag[],
170
+ page?: number,
171
+ upToBlockNumber?: BlockNumber,
172
+ ): Promise<TxScopedL2Log[][]> {
173
+ return this.store.getPrivateLogsByTags(tags, page, upToBlockNumber);
170
174
  }
171
175
 
172
176
  public getPublicLogsByTagsFromContract(
173
177
  contractAddress: AztecAddress,
174
178
  tags: Tag[],
175
179
  page?: number,
180
+ upToBlockNumber?: BlockNumber,
176
181
  ): Promise<TxScopedL2Log[][]> {
177
- return this.store.getPublicLogsByTagsFromContract(contractAddress, tags, page);
182
+ return this.store.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
178
183
  }
179
184
 
180
185
  public getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
@@ -1,29 +1,21 @@
1
1
  import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
- import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { filterAsync } from '@aztec/foundation/collection';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
- import {
5
- ContractClassPublishedEvent,
6
- PrivateFunctionBroadcastedEvent,
7
- UtilityFunctionBroadcastedEvent,
8
- } from '@aztec/protocol-contracts/class-registry';
4
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
9
5
  import {
10
6
  ContractInstancePublishedEvent,
11
7
  ContractInstanceUpdatedEvent,
12
8
  } from '@aztec/protocol-contracts/instance-registry';
13
9
  import type { L2Block, ValidateCheckpointResult } from '@aztec/stdlib/block';
14
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
10
+ import { type PublishedCheckpoint, validateCheckpoint } from '@aztec/stdlib/checkpoint';
15
11
  import {
16
- type ExecutablePrivateFunctionWithMembershipProof,
17
- type UtilityFunctionWithMembershipProof,
18
- computePublicBytecodeCommitment,
19
- isValidPrivateFunctionMembershipProof,
20
- isValidUtilityFunctionMembershipProof,
12
+ type ContractClassPublicWithCommitment,
13
+ computeContractAddressFromInstance,
14
+ computeContractClassId,
21
15
  } from '@aztec/stdlib/contract';
22
16
  import type { ContractClassLog, PrivateLog, PublicLog } from '@aztec/stdlib/logs';
23
17
  import type { UInt64 } from '@aztec/stdlib/types';
24
18
 
25
- import groupBy from 'lodash.groupby';
26
-
27
19
  import type { KVArchiverDataStore } from '../store/kv_archiver_store.js';
28
20
  import type { L2TipsCache } from '../store/l2_tips_cache.js';
29
21
 
@@ -48,32 +40,32 @@ export class ArchiverDataStoreUpdater {
48
40
  constructor(
49
41
  private store: KVArchiverDataStore,
50
42
  private l2TipsCache?: L2TipsCache,
43
+ private opts: { rollupManaLimit?: number } = {},
51
44
  ) {}
52
45
 
53
46
  /**
54
- * Adds proposed blocks to the store with contract class/instance extraction from logs.
55
- * These are uncheckpointed blocks that have been proposed by the sequencer but not yet included in a checkpoint on L1.
56
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
57
- * and individually broadcasted functions from the block logs.
47
+ * Adds a proposed block to the store with contract class/instance extraction from logs.
48
+ * This is an uncheckpointed block that has been proposed by the sequencer but not yet included in a checkpoint on L1.
49
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the block logs.
58
50
  *
59
- * @param blocks - The proposed L2 blocks to add.
51
+ * @param block - The proposed L2 block to add.
60
52
  * @param pendingChainValidationStatus - Optional validation status to set.
61
53
  * @returns True if the operation is successful.
62
54
  */
63
- public async addProposedBlocks(
64
- blocks: L2Block[],
55
+ public async addProposedBlock(
56
+ block: L2Block,
65
57
  pendingChainValidationStatus?: ValidateCheckpointResult,
66
58
  ): Promise<boolean> {
67
59
  const result = await this.store.transactionAsync(async () => {
68
- await this.store.addProposedBlocks(blocks);
60
+ await this.store.addProposedBlock(block);
69
61
 
70
62
  const opResults = await Promise.all([
71
63
  // Update the pending chain validation status if provided
72
64
  pendingChainValidationStatus && this.store.setPendingChainValidationStatus(pendingChainValidationStatus),
73
- // Add any logs emitted during the retrieved blocks
74
- this.store.addLogs(blocks),
75
- // Unroll all logs emitted during the retrieved blocks and extract any contract classes and instances from them
76
- ...blocks.map(block => this.addContractDataToDb(block)),
65
+ // Add any logs emitted during the retrieved block
66
+ this.store.addLogs([block]),
67
+ // Unroll all logs emitted during the retrieved block and extract any contract classes and instances from it
68
+ this.addContractDataToDb(block),
77
69
  ]);
78
70
 
79
71
  await this.l2TipsCache?.refresh();
@@ -86,8 +78,7 @@ export class ArchiverDataStoreUpdater {
86
78
  * Reconciles local blocks with incoming checkpoints from L1.
87
79
  * Adds new checkpoints to the store with contract class/instance extraction from logs.
88
80
  * Prunes any local blocks that conflict with checkpoint data (by comparing archive roots).
89
- * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events,
90
- * and individually broadcasted functions from the checkpoint block logs.
81
+ * Extracts ContractClassPublished, ContractInstancePublished, ContractInstanceUpdated events from the checkpoint block logs.
91
82
  *
92
83
  * @param checkpoints - The published checkpoints to add.
93
84
  * @param pendingChainValidationStatus - Optional validation status to set.
@@ -97,13 +88,17 @@ export class ArchiverDataStoreUpdater {
97
88
  checkpoints: PublishedCheckpoint[],
98
89
  pendingChainValidationStatus?: ValidateCheckpointResult,
99
90
  ): Promise<ReconcileCheckpointsResult> {
91
+ for (const checkpoint of checkpoints) {
92
+ validateCheckpoint(checkpoint.checkpoint, { rollupManaLimit: this.opts?.rollupManaLimit });
93
+ }
94
+
100
95
  const result = await this.store.transactionAsync(async () => {
101
96
  // Before adding checkpoints, check for conflicts with local blocks if any
102
97
  const { prunedBlocks, lastAlreadyInsertedBlockNumber } = await this.pruneMismatchingLocalBlocks(checkpoints);
103
98
 
104
99
  await this.store.addCheckpoints(checkpoints);
105
100
 
106
- // Filter out blocks that were already inserted via addProposedBlocks() to avoid duplicating logs/contract data
101
+ // Filter out blocks that were already inserted via addProposedBlock() to avoid duplicating logs/contract data
107
102
  const newBlocks = checkpoints
108
103
  .flatMap((ch: PublishedCheckpoint) => ch.checkpoint.blocks)
109
104
  .filter(b => lastAlreadyInsertedBlockNumber === undefined || b.number > lastAlreadyInsertedBlockNumber);
@@ -173,7 +168,7 @@ export class ArchiverDataStoreUpdater {
173
168
  this.log.verbose(`Block number ${blockNumber} already inserted and matches checkpoint`, blockInfos);
174
169
  lastAlreadyInsertedBlockNumber = blockNumber;
175
170
  } else {
176
- this.log.warn(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
171
+ this.log.info(`Conflict detected at block ${blockNumber} between checkpointed and local block`, blockInfos);
177
172
  const prunedBlocks = await this.removeBlocksAfter(BlockNumber(blockNumber - 1));
178
173
  return { prunedBlocks, lastAlreadyInsertedBlockNumber };
179
174
  }
@@ -276,6 +271,17 @@ export class ArchiverDataStoreUpdater {
276
271
  });
277
272
  }
278
273
 
274
+ /**
275
+ * Updates the finalized checkpoint number and refreshes the L2 tips cache.
276
+ * @param checkpointNumber - The checkpoint number to set as finalized.
277
+ */
278
+ public async setFinalizedCheckpointNumber(checkpointNumber: CheckpointNumber): Promise<void> {
279
+ await this.store.transactionAsync(async () => {
280
+ await this.store.setFinalizedCheckpointNumber(checkpointNumber);
281
+ await this.l2TipsCache?.refresh();
282
+ });
283
+ }
284
+
279
285
  /** Extracts and stores contract data from a single block. */
280
286
  private addContractDataToDb(block: L2Block): Promise<boolean> {
281
287
  return this.updateContractDataOnDb(block, Operation.Store);
@@ -297,9 +303,6 @@ export class ArchiverDataStoreUpdater {
297
303
  this.updatePublishedContractClasses(contractClassLogs, block.number, operation),
298
304
  this.updateDeployedContractInstances(privateLogs, block.number, operation),
299
305
  this.updateUpdatedContractInstances(publicLogs, block.header.globalVariables.timestamp, operation),
300
- operation === Operation.Store
301
- ? this.storeBroadcastedIndividualFunctions(contractClassLogs, block.number)
302
- : Promise.resolve(true),
303
306
  ])
304
307
  ).every(Boolean);
305
308
  }
@@ -316,18 +319,37 @@ export class ArchiverDataStoreUpdater {
316
319
  .filter(log => ContractClassPublishedEvent.isContractClassPublishedEvent(log))
317
320
  .map(log => ContractClassPublishedEvent.fromLog(log));
318
321
 
319
- const contractClasses = await Promise.all(contractClassPublishedEvents.map(e => e.toContractClassPublic()));
320
- if (contractClasses.length > 0) {
321
- contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
322
- if (operation == Operation.Store) {
323
- // TODO: Will probably want to create some worker threads to compute these bytecode commitments as they are expensive
324
- const commitments = await Promise.all(
325
- contractClasses.map(c => computePublicBytecodeCommitment(c.packedBytecode)),
326
- );
327
- return await this.store.addContractClasses(contractClasses, commitments, blockNum);
328
- } else if (operation == Operation.Delete) {
322
+ if (operation == Operation.Delete) {
323
+ const contractClasses = contractClassPublishedEvents.map(e => e.toContractClassPublic());
324
+ if (contractClasses.length > 0) {
325
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
329
326
  return await this.store.deleteContractClasses(contractClasses, blockNum);
330
327
  }
328
+ return true;
329
+ }
330
+
331
+ // Compute bytecode commitments and validate class IDs in a single pass.
332
+ const contractClasses: ContractClassPublicWithCommitment[] = [];
333
+ for (const event of contractClassPublishedEvents) {
334
+ const contractClass = await event.toContractClassPublicWithBytecodeCommitment();
335
+ const computedClassId = await computeContractClassId({
336
+ artifactHash: contractClass.artifactHash,
337
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
338
+ publicBytecodeCommitment: contractClass.publicBytecodeCommitment,
339
+ });
340
+ if (!computedClassId.equals(contractClass.id)) {
341
+ this.log.warn(
342
+ `Skipping contract class with mismatched id at block ${blockNum}. Claimed ${contractClass.id}, computed ${computedClassId}`,
343
+ { blockNum, contractClassId: event.contractClassId.toString() },
344
+ );
345
+ continue;
346
+ }
347
+ contractClasses.push(contractClass);
348
+ }
349
+
350
+ if (contractClasses.length > 0) {
351
+ contractClasses.forEach(c => this.log.verbose(`${Operation[operation]} contract class ${c.id.toString()}`));
352
+ return await this.store.addContractClasses(contractClasses, blockNum);
331
353
  }
332
354
  return true;
333
355
  }
@@ -340,10 +362,27 @@ export class ArchiverDataStoreUpdater {
340
362
  blockNum: BlockNumber,
341
363
  operation: Operation,
342
364
  ): Promise<boolean> {
343
- const contractInstances = allLogs
365
+ const allInstances = allLogs
344
366
  .filter(log => ContractInstancePublishedEvent.isContractInstancePublishedEvent(log))
345
367
  .map(log => ContractInstancePublishedEvent.fromLog(log))
346
368
  .map(e => e.toContractInstance());
369
+
370
+ // Verify that each instance's address matches the one derived from its fields if we're adding
371
+ const contractInstances =
372
+ operation === Operation.Delete
373
+ ? allInstances
374
+ : await filterAsync(allInstances, async instance => {
375
+ const computedAddress = await computeContractAddressFromInstance(instance);
376
+ if (!computedAddress.equals(instance.address)) {
377
+ this.log.warn(
378
+ `Found contract instance with mismatched address at block ${blockNum}. Claimed ${instance.address} but computed ${computedAddress}.`,
379
+ { instanceAddress: instance.address.toString(), computedAddress: computedAddress.toString(), blockNum },
380
+ );
381
+ return false;
382
+ }
383
+ return true;
384
+ });
385
+
347
386
  if (contractInstances.length > 0) {
348
387
  contractInstances.forEach(c =>
349
388
  this.log.verbose(`${Operation[operation]} contract instance at ${c.address.toString()}`),
@@ -382,67 +421,4 @@ export class ArchiverDataStoreUpdater {
382
421
  }
383
422
  return true;
384
423
  }
385
-
386
- /**
387
- * Stores the functions that were broadcasted individually.
388
- *
389
- * @dev Beware that there is not a delete variant of this, since they are added to contract classes
390
- * and will be deleted as part of the class if needed.
391
- */
392
- private async storeBroadcastedIndividualFunctions(
393
- allLogs: ContractClassLog[],
394
- _blockNum: BlockNumber,
395
- ): Promise<boolean> {
396
- // Filter out private and utility function broadcast events
397
- const privateFnEvents = allLogs
398
- .filter(log => PrivateFunctionBroadcastedEvent.isPrivateFunctionBroadcastedEvent(log))
399
- .map(log => PrivateFunctionBroadcastedEvent.fromLog(log));
400
- const utilityFnEvents = allLogs
401
- .filter(log => UtilityFunctionBroadcastedEvent.isUtilityFunctionBroadcastedEvent(log))
402
- .map(log => UtilityFunctionBroadcastedEvent.fromLog(log));
403
-
404
- // Group all events by contract class id
405
- for (const [classIdString, classEvents] of Object.entries(
406
- groupBy([...privateFnEvents, ...utilityFnEvents], e => e.contractClassId.toString()),
407
- )) {
408
- const contractClassId = Fr.fromHexString(classIdString);
409
- const contractClass = await this.store.getContractClass(contractClassId);
410
- if (!contractClass) {
411
- this.log.warn(`Skipping broadcasted functions as contract class ${contractClassId.toString()} was not found`);
412
- continue;
413
- }
414
-
415
- // Split private and utility functions, and filter out invalid ones
416
- const allFns = classEvents.map(e => e.toFunctionWithMembershipProof());
417
- const privateFns = allFns.filter(
418
- (fn): fn is ExecutablePrivateFunctionWithMembershipProof => 'utilityFunctionsTreeRoot' in fn,
419
- );
420
- const utilityFns = allFns.filter(
421
- (fn): fn is UtilityFunctionWithMembershipProof => 'privateFunctionsArtifactTreeRoot' in fn,
422
- );
423
-
424
- const privateFunctionsWithValidity = await Promise.all(
425
- privateFns.map(async fn => ({ fn, valid: await isValidPrivateFunctionMembershipProof(fn, contractClass) })),
426
- );
427
- const validPrivateFns = privateFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
428
- const utilityFunctionsWithValidity = await Promise.all(
429
- utilityFns.map(async fn => ({
430
- fn,
431
- valid: await isValidUtilityFunctionMembershipProof(fn, contractClass),
432
- })),
433
- );
434
- const validUtilityFns = utilityFunctionsWithValidity.filter(({ valid }) => valid).map(({ fn }) => fn);
435
- const validFnCount = validPrivateFns.length + validUtilityFns.length;
436
- if (validFnCount !== allFns.length) {
437
- this.log.warn(`Skipping ${allFns.length - validFnCount} invalid functions`);
438
- }
439
-
440
- // Store the functions in the contract class in a single operation
441
- if (validFnCount > 0) {
442
- this.log.verbose(`Storing ${validFnCount} functions for contract class ${contractClassId.toString()}`);
443
- }
444
- return await this.store.addFunctions(contractClassId, validPrivateFns, validUtilityFns);
445
- }
446
- return true;
447
- }
448
424
  }
@@ -3,6 +3,7 @@ import { EpochCache } from '@aztec/epoch-cache';
3
3
  import { InboxContract, RollupContract } from '@aztec/ethereum/contracts';
4
4
  import type { L1BlockId } from '@aztec/ethereum/l1-types';
5
5
  import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
6
+ import { asyncPool } from '@aztec/foundation/async-pool';
6
7
  import { maxBigint } from '@aztec/foundation/bigint';
7
8
  import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
8
9
  import { Buffer32 } from '@aztec/foundation/buffer';
@@ -69,13 +70,18 @@ export class ArchiverL1Synchronizer implements Traceable {
69
70
  private readonly epochCache: EpochCache,
70
71
  private readonly dateProvider: DateProvider,
71
72
  private readonly instrumentation: ArchiverInstrumentation,
72
- private readonly l1Constants: L1RollupConstants & { l1StartBlockHash: Buffer32; genesisArchiveRoot: Fr },
73
+ private readonly l1Constants: L1RollupConstants & {
74
+ l1StartBlockHash: Buffer32;
75
+ genesisArchiveRoot: Fr;
76
+ },
73
77
  private readonly events: ArchiverEmitter,
74
78
  tracer: Tracer,
75
79
  l2TipsCache?: L2TipsCache,
76
80
  private readonly log: Logger = createLogger('archiver:l1-sync'),
77
81
  ) {
78
- this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache);
82
+ this.updater = new ArchiverDataStoreUpdater(this.store, l2TipsCache, {
83
+ rollupManaLimit: l1Constants.rollupManaLimit,
84
+ });
79
85
  this.tracer = tracer;
80
86
  }
81
87
 
@@ -211,6 +217,9 @@ export class ArchiverL1Synchronizer implements Traceable {
211
217
  this.instrumentation.updateL1BlockHeight(currentL1BlockNumber);
212
218
  }
213
219
 
220
+ // Update the finalized L2 checkpoint based on L1 finality.
221
+ await this.updateFinalizedCheckpoint();
222
+
214
223
  // After syncing has completed, update the current l1 block number and timestamp,
215
224
  // otherwise we risk announcing to the world that we've synced to a given point,
216
225
  // but the corresponding blocks have not been processed (see #12631).
@@ -226,6 +235,27 @@ export class ArchiverL1Synchronizer implements Traceable {
226
235
  });
227
236
  }
228
237
 
238
+ /** Query L1 for its finalized block and update the finalized checkpoint accordingly. */
239
+ private async updateFinalizedCheckpoint(): Promise<void> {
240
+ try {
241
+ const finalizedL1Block = await this.publicClient.getBlock({ blockTag: 'finalized', includeTransactions: false });
242
+ const finalizedL1BlockNumber = finalizedL1Block.number;
243
+ const finalizedCheckpointNumber = await this.rollup.getProvenCheckpointNumber({
244
+ blockNumber: finalizedL1BlockNumber,
245
+ });
246
+ const localFinalizedCheckpointNumber = await this.store.getFinalizedCheckpointNumber();
247
+ if (localFinalizedCheckpointNumber !== finalizedCheckpointNumber) {
248
+ await this.updater.setFinalizedCheckpointNumber(finalizedCheckpointNumber);
249
+ this.log.info(`Updated finalized chain to checkpoint ${finalizedCheckpointNumber}`, {
250
+ finalizedCheckpointNumber,
251
+ finalizedL1BlockNumber,
252
+ });
253
+ }
254
+ } catch (err) {
255
+ this.log.warn(`Failed to update finalized checkpoint: ${err}`);
256
+ }
257
+ }
258
+
229
259
  /** Prune all proposed local blocks that should have been checkpointed by now. */
230
260
  private async pruneUncheckpointedBlocks(currentL1Timestamp: bigint) {
231
261
  const [lastCheckpointedBlockNumber, lastProposedBlockNumber] = await Promise.all([
@@ -304,17 +334,20 @@ export class ArchiverL1Synchronizer implements Traceable {
304
334
 
305
335
  const checkpointsToUnwind = localPendingCheckpointNumber - provenCheckpointNumber;
306
336
 
307
- const checkpointPromises = Array.from({ length: checkpointsToUnwind })
308
- .fill(0)
309
- .map((_, i) => this.store.getCheckpointData(CheckpointNumber(i + pruneFrom)));
310
- const checkpoints = await Promise.all(checkpointPromises);
311
-
312
- const blockPromises = await Promise.all(
313
- checkpoints
314
- .filter(isDefined)
315
- .map(cp => this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber))),
337
+ // Fetch checkpoints and blocks in bounded batches to avoid unbounded concurrent
338
+ // promises when the gap between local pending and proven checkpoint numbers is large.
339
+ const BATCH_SIZE = 10;
340
+ const indices = Array.from({ length: checkpointsToUnwind }, (_, i) => CheckpointNumber(i + pruneFrom));
341
+ const checkpoints = (await asyncPool(BATCH_SIZE, indices, idx => this.store.getCheckpointData(idx))).filter(
342
+ isDefined,
316
343
  );
317
- const newBlocks = blockPromises.filter(isDefined).flat();
344
+ const newBlocks = (
345
+ await asyncPool(BATCH_SIZE, checkpoints, cp =>
346
+ this.store.getBlocksForCheckpoint(CheckpointNumber(cp.checkpointNumber)),
347
+ )
348
+ )
349
+ .filter(isDefined)
350
+ .flat();
318
351
 
319
352
  // Emit an event for listening services to react to the chain prune
320
353
  this.events.emit(L2BlockSourceEvents.L2PruneUnproven, {
@@ -362,6 +395,7 @@ export class ArchiverL1Synchronizer implements Traceable {
362
395
  const localMessagesInserted = await this.store.getTotalL1ToL2MessageCount();
363
396
  const localLastMessage = await this.store.getLastL1ToL2Message();
364
397
  const remoteMessagesState = await this.inbox.getState({ blockNumber: currentL1BlockNumber });
398
+ await this.store.setInboxTreeInProgress(remoteMessagesState.treeInProgress);
365
399
 
366
400
  this.log.trace(`Retrieved remote inbox state at L1 block ${currentL1BlockNumber}.`, {
367
401
  localMessagesInserted,
@@ -822,7 +856,7 @@ export class ArchiverL1Synchronizer implements Traceable {
822
856
  const prunedCheckpointNumber = result.prunedBlocks[0].checkpointNumber;
823
857
  const prunedSlotNumber = result.prunedBlocks[0].header.globalVariables.slotNumber;
824
858
 
825
- this.log.warn(
859
+ this.log.info(
826
860
  `Pruned ${result.prunedBlocks.length} mismatching blocks for checkpoint ${prunedCheckpointNumber}`,
827
861
  { prunedBlocks: result.prunedBlocks.map(b => b.toBlockInfo()), prunedSlotNumber, prunedCheckpointNumber },
828
862
  );