@aztec/aztec-node 0.0.0-test.1 → 0.0.1-commit.b655e406

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/dest/aztec-node/config.d.ts +14 -9
  2. package/dest/aztec-node/config.d.ts.map +1 -1
  3. package/dest/aztec-node/config.js +75 -14
  4. package/dest/aztec-node/node_metrics.d.ts +4 -0
  5. package/dest/aztec-node/node_metrics.d.ts.map +1 -1
  6. package/dest/aztec-node/node_metrics.js +21 -0
  7. package/dest/aztec-node/server.d.ts +90 -50
  8. package/dest/aztec-node/server.d.ts.map +1 -1
  9. package/dest/aztec-node/server.js +526 -218
  10. package/dest/bin/index.js +4 -2
  11. package/dest/index.d.ts +0 -1
  12. package/dest/index.d.ts.map +1 -1
  13. package/dest/index.js +0 -1
  14. package/dest/sentinel/config.d.ts +8 -0
  15. package/dest/sentinel/config.d.ts.map +1 -0
  16. package/dest/sentinel/config.js +29 -0
  17. package/dest/sentinel/factory.d.ts +9 -0
  18. package/dest/sentinel/factory.d.ts.map +1 -0
  19. package/dest/sentinel/factory.js +17 -0
  20. package/dest/sentinel/index.d.ts +3 -0
  21. package/dest/sentinel/index.d.ts.map +1 -0
  22. package/dest/sentinel/index.js +1 -0
  23. package/dest/sentinel/sentinel.d.ts +91 -0
  24. package/dest/sentinel/sentinel.d.ts.map +1 -0
  25. package/dest/sentinel/sentinel.js +391 -0
  26. package/dest/sentinel/store.d.ts +34 -0
  27. package/dest/sentinel/store.d.ts.map +1 -0
  28. package/dest/sentinel/store.js +169 -0
  29. package/dest/test/index.d.ts +31 -0
  30. package/dest/test/index.d.ts.map +1 -0
  31. package/dest/test/index.js +1 -0
  32. package/package.json +42 -32
  33. package/src/aztec-node/config.ts +128 -25
  34. package/src/aztec-node/node_metrics.ts +28 -0
  35. package/src/aztec-node/server.ts +684 -278
  36. package/src/bin/index.ts +4 -2
  37. package/src/index.ts +0 -1
  38. package/src/sentinel/config.ts +37 -0
  39. package/src/sentinel/factory.ts +36 -0
  40. package/src/sentinel/index.ts +8 -0
  41. package/src/sentinel/sentinel.ts +489 -0
  42. package/src/sentinel/store.ts +184 -0
  43. package/src/test/index.ts +32 -0
  44. package/dest/aztec-node/http_rpc_server.d.ts +0 -8
  45. package/dest/aztec-node/http_rpc_server.d.ts.map +0 -1
  46. package/dest/aztec-node/http_rpc_server.js +0 -9
  47. package/src/aztec-node/http_rpc_server.ts +0 -11
@@ -5,33 +5,44 @@ function _ts_decorate(decorators, target, key, desc) {
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  }
7
7
  import { createArchiver } from '@aztec/archiver';
8
- import { BBCircuitVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
8
+ import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
9
9
  import { createBlobSinkClient } from '@aztec/blob-sink/client';
10
- import { INITIAL_L2_BLOCK_NUM, REGISTERER_CONTRACT_ADDRESS } from '@aztec/constants';
10
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
11
11
  import { EpochCache } from '@aztec/epoch-cache';
12
- import { createEthereumChain } from '@aztec/ethereum';
13
- import { compactArray } from '@aztec/foundation/collection';
12
+ import { RegistryContract, RollupContract, createEthereumChain, getPublicClient } from '@aztec/ethereum';
13
+ import { compactArray, pick } from '@aztec/foundation/collection';
14
14
  import { EthAddress } from '@aztec/foundation/eth-address';
15
15
  import { Fr } from '@aztec/foundation/fields';
16
+ import { BadRequestError } from '@aztec/foundation/json-rpc';
16
17
  import { createLogger } from '@aztec/foundation/log';
18
+ import { SerialQueue } from '@aztec/foundation/queue';
19
+ import { count } from '@aztec/foundation/string';
17
20
  import { DateProvider, Timer } from '@aztec/foundation/timer';
18
- import { SiblingPath } from '@aztec/foundation/trees';
19
- import { openTmpStore } from '@aztec/kv-store/lmdb';
20
- import { SHA256Trunc, StandardTree, UnbalancedTree } from '@aztec/merkle-tree';
21
- import { createP2PClient } from '@aztec/p2p';
21
+ import { MembershipWitness } from '@aztec/foundation/trees';
22
+ import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
23
+ import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
24
+ import { createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
25
+ import { createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
22
26
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
23
- import { GlobalVariableBuilder, SequencerClient, createSlasherClient, createValidatorForAcceptingTxs, getDefaultAllowedSetupFunctions } from '@aztec/sequencer-client';
27
+ import { BlockBuilder, GlobalVariableBuilder, SequencerClient, createValidatorForAcceptingTxs } from '@aztec/sequencer-client';
24
28
  import { PublicProcessorFactory } from '@aztec/simulator/server';
29
+ import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
25
30
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
26
- import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/stdlib/hash';
31
+ import { L2BlockHash } from '@aztec/stdlib/block';
32
+ import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
33
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
27
34
  import { tryStop } from '@aztec/stdlib/interfaces/server';
35
+ import { InboxLeaf } from '@aztec/stdlib/messaging';
28
36
  import { P2PClientType } from '@aztec/stdlib/p2p';
29
37
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
30
38
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
39
+ import { getPackageVersion } from '@aztec/stdlib/update-checker';
31
40
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
32
- import { createValidatorClient } from '@aztec/validator-client';
41
+ import { NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient } from '@aztec/validator-client';
33
42
  import { createWorldStateSynchronizer } from '@aztec/world-state';
34
- import { getPackageVersion } from './config.js';
43
+ import { createPublicClient, fallback, http } from 'viem';
44
+ import { createSentinel } from '../sentinel/factory.js';
45
+ import { createKeyStoreForValidator } from './config.js';
35
46
  import { NodeMetrics } from './node_metrics.js';
36
47
  /**
37
48
  * The aztec node.
@@ -42,37 +53,50 @@ import { NodeMetrics } from './node_metrics.js';
42
53
  logsSource;
43
54
  contractDataSource;
44
55
  l1ToL2MessageSource;
45
- nullifierSource;
46
56
  worldStateSynchronizer;
47
57
  sequencer;
58
+ slasherClient;
59
+ validatorsSentinel;
60
+ epochPruneWatcher;
48
61
  l1ChainId;
49
62
  version;
50
63
  globalVariableBuilder;
64
+ epochCache;
65
+ packageVersion;
51
66
  proofVerifier;
52
67
  telemetry;
53
68
  log;
54
- packageVersion;
55
69
  metrics;
70
+ // Prevent two snapshot operations to happen simultaneously
71
+ isUploadingSnapshot;
72
+ // Serial queue to ensure that we only send one tx at a time
73
+ txQueue;
56
74
  tracer;
57
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, nullifierSource, worldStateSynchronizer, sequencer, l1ChainId, version, globalVariableBuilder, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node')){
75
+ constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node')){
58
76
  this.config = config;
59
77
  this.p2pClient = p2pClient;
60
78
  this.blockSource = blockSource;
61
79
  this.logsSource = logsSource;
62
80
  this.contractDataSource = contractDataSource;
63
81
  this.l1ToL2MessageSource = l1ToL2MessageSource;
64
- this.nullifierSource = nullifierSource;
65
82
  this.worldStateSynchronizer = worldStateSynchronizer;
66
83
  this.sequencer = sequencer;
84
+ this.slasherClient = slasherClient;
85
+ this.validatorsSentinel = validatorsSentinel;
86
+ this.epochPruneWatcher = epochPruneWatcher;
67
87
  this.l1ChainId = l1ChainId;
68
88
  this.version = version;
69
89
  this.globalVariableBuilder = globalVariableBuilder;
90
+ this.epochCache = epochCache;
91
+ this.packageVersion = packageVersion;
70
92
  this.proofVerifier = proofVerifier;
71
93
  this.telemetry = telemetry;
72
94
  this.log = log;
73
- this.packageVersion = getPackageVersion();
95
+ this.isUploadingSnapshot = false;
96
+ this.txQueue = new SerialQueue();
74
97
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
75
98
  this.tracer = telemetry.getTracer('AztecNodeService');
99
+ this.txQueue.start();
76
100
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
77
101
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
78
102
  }
@@ -87,59 +111,200 @@ import { NodeMetrics } from './node_metrics.js';
87
111
  * initializes the Aztec Node, wait for component to sync.
88
112
  * @param config - The configuration to be used by the aztec node.
89
113
  * @returns - A fully synced Aztec Node for use in development/testing.
90
- */ static async createAndSync(config, deps = {}, options = {}) {
91
- const telemetry = deps.telemetry ?? getTelemetryClient();
114
+ */ static async createAndSync(inputConfig, deps = {}, options = {}) {
115
+ const config = {
116
+ ...inputConfig
117
+ }; // Copy the config so we dont mutate the input object
92
118
  const log = deps.logger ?? createLogger('node');
119
+ const packageVersion = getPackageVersion() ?? '';
120
+ const telemetry = deps.telemetry ?? getTelemetryClient();
93
121
  const dateProvider = deps.dateProvider ?? new DateProvider();
94
- const blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config);
122
+ const blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config, {
123
+ logger: createLogger('node:blob-sink:client')
124
+ });
95
125
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
96
- //validate that the actual chain id matches that specified in configuration
126
+ // Build a key store from file if given or from environment otherwise
127
+ let keyStoreManager;
128
+ const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
129
+ if (keyStoreProvided) {
130
+ const keyStores = loadKeystores(config.keyStoreDirectory);
131
+ keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
132
+ } else {
133
+ const keyStore = createKeyStoreForValidator(config);
134
+ if (keyStore) {
135
+ keyStoreManager = new KeystoreManager(keyStore);
136
+ }
137
+ }
138
+ await keyStoreManager?.validateSigners();
139
+ // If we are a validator, verify our configuration before doing too much more.
140
+ if (!config.disableValidator) {
141
+ if (keyStoreManager === undefined) {
142
+ throw new Error('Failed to create key store, a requirement for running a validator');
143
+ }
144
+ if (!keyStoreProvided) {
145
+ log.warn('KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS');
146
+ }
147
+ ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
148
+ }
149
+ // validate that the actual chain id matches that specified in configuration
97
150
  if (config.l1ChainId !== ethereumChain.chainInfo.id) {
98
151
  throw new Error(`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`);
99
152
  }
100
- const archiver = await createArchiver(config, blobSinkClient, {
101
- blockUntilSync: true
102
- }, telemetry);
153
+ const publicClient = createPublicClient({
154
+ chain: ethereumChain.chainInfo,
155
+ transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
156
+ pollingInterval: config.viemPollingIntervalMS
157
+ });
158
+ const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
159
+ // Overwrite the passed in vars.
160
+ config.l1Contracts = {
161
+ ...config.l1Contracts,
162
+ ...l1ContractsAddresses
163
+ };
164
+ const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
165
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
166
+ rollupContract.getL1GenesisTime(),
167
+ rollupContract.getSlotDuration(),
168
+ rollupContract.getVersion()
169
+ ]);
170
+ config.rollupVersion ??= Number(rollupVersionFromRollup);
171
+ if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
172
+ log.warn(`Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`);
173
+ }
174
+ // attempt snapshot sync if possible
175
+ await trySnapshotSync(config, log);
176
+ const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
177
+ dateProvider
178
+ });
179
+ const archiver = await createArchiver(config, {
180
+ blobSinkClient,
181
+ epochCache,
182
+ telemetry,
183
+ dateProvider
184
+ }, {
185
+ blockUntilSync: !config.skipArchiverInitialSync
186
+ });
103
187
  // now create the merkle trees and the world state synchronizer
104
188
  const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
105
- const proofVerifier = config.realProofs ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier();
189
+ const circuitVerifier = config.realProofs ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier();
106
190
  if (!config.realProofs) {
107
191
  log.warn(`Aztec node is accepting fake proofs`);
108
192
  }
109
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
110
- dateProvider
111
- });
193
+ const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
112
194
  // create the tx pool and the p2p client, which will need the l2 block source
113
- const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, telemetry);
114
- const slasherClient = createSlasherClient(config, archiver, telemetry);
115
- // start both and wait for them to sync from the block source
116
- await Promise.all([
117
- p2pClient.start(),
118
- worldStateSynchronizer.start(),
119
- slasherClient.start()
120
- ]);
121
- log.verbose(`All Aztec Node subsystems synced`);
195
+ const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
196
+ // We should really not be modifying the config object
197
+ config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
198
+ const blockBuilder = new BlockBuilder({
199
+ ...config,
200
+ l1GenesisTime,
201
+ slotDuration: Number(slotDuration)
202
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry);
203
+ // We'll accumulate sentinel watchers here
204
+ const watchers = [];
205
+ // Create validator client if required
122
206
  const validatorClient = createValidatorClient(config, {
123
207
  p2pClient,
124
208
  telemetry,
125
209
  dateProvider,
126
- epochCache
127
- });
128
- // now create the sequencer
129
- const sequencer = config.disableValidator ? undefined : await SequencerClient.new(config, {
130
- ...deps,
131
- validatorClient,
132
- p2pClient,
133
- worldStateSynchronizer,
134
- slasherClient,
135
- contractDataSource: archiver,
136
- l2BlockSource: archiver,
210
+ epochCache,
211
+ blockBuilder,
212
+ blockSource: archiver,
137
213
  l1ToL2MessageSource: archiver,
138
- telemetry,
139
- dateProvider,
140
- blobSinkClient
214
+ keyStoreManager
141
215
  });
142
- return new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, ethereumChain.chainInfo.id, config.version, new GlobalVariableBuilder(config), proofVerifier, telemetry, log);
216
+ // If we have a validator client, register it as a source of offenses for the slasher,
217
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
218
+ // like attestations or auths will fail.
219
+ if (validatorClient) {
220
+ watchers.push(validatorClient);
221
+ if (!options.dontStartSequencer) {
222
+ await validatorClient.registerHandlers();
223
+ }
224
+ }
225
+ // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
226
+ // create a BlockProposalHandler to reexecute block proposals for monitoring
227
+ if (!validatorClient && config.alwaysReexecuteBlockProposals) {
228
+ log.info('Setting up block proposal reexecution for monitoring');
229
+ createBlockProposalHandler(config, {
230
+ blockBuilder,
231
+ epochCache,
232
+ blockSource: archiver,
233
+ l1ToL2MessageSource: archiver,
234
+ p2pClient,
235
+ dateProvider,
236
+ telemetry
237
+ }).registerForReexecution(p2pClient);
238
+ }
239
+ // Start world state and wait for it to sync to the archiver.
240
+ await worldStateSynchronizer.start();
241
+ // Start p2p. Note that it depends on world state to be running.
242
+ await p2pClient.start();
243
+ const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
244
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
245
+ watchers.push(validatorsSentinel);
246
+ }
247
+ let epochPruneWatcher;
248
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
249
+ epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), blockBuilder, config);
250
+ watchers.push(epochPruneWatcher);
251
+ }
252
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
253
+ let attestationsBlockWatcher;
254
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
255
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
256
+ watchers.push(attestationsBlockWatcher);
257
+ }
258
+ // Start p2p-related services once the archiver has completed sync
259
+ void archiver.waitForInitialSync().then(async ()=>{
260
+ await p2pClient.start();
261
+ await validatorsSentinel?.start();
262
+ await epochPruneWatcher?.start();
263
+ await attestationsBlockWatcher?.start();
264
+ log.info(`All p2p services started`);
265
+ }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
266
+ // Validator enabled, create/start relevant service
267
+ let sequencer;
268
+ let slasherClient;
269
+ if (!config.disableValidator) {
270
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
271
+ // as they are executed when the node is selected as proposer.
272
+ const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
273
+ slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
274
+ await slasherClient.start();
275
+ const l1TxUtils = await createL1TxUtilsWithBlobsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
276
+ ...config,
277
+ scope: 'sequencer'
278
+ }, {
279
+ telemetry,
280
+ logger: log.createChild('l1-tx-utils'),
281
+ dateProvider
282
+ });
283
+ // Create and start the sequencer client
284
+ sequencer = await SequencerClient.new(config, {
285
+ ...deps,
286
+ epochCache,
287
+ l1TxUtils,
288
+ validatorClient,
289
+ p2pClient,
290
+ worldStateSynchronizer,
291
+ slasherClient,
292
+ blockBuilder,
293
+ l2BlockSource: archiver,
294
+ l1ToL2MessageSource: archiver,
295
+ telemetry,
296
+ dateProvider,
297
+ blobSinkClient,
298
+ nodeKeyStore: keyStoreManager
299
+ });
300
+ }
301
+ if (!options.dontStartSequencer && sequencer) {
302
+ await sequencer.start();
303
+ log.verbose(`Sequencer started`);
304
+ } else if (sequencer) {
305
+ log.warn(`Sequencer created but not started`);
306
+ }
307
+ return new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, new GlobalVariableBuilder(config), epochCache, packageVersion, proofVerifier, telemetry, log);
143
308
  }
144
309
  /**
145
310
  * Returns the sequencer client instance.
@@ -165,6 +330,9 @@ import { NodeMetrics } from './node_metrics.js';
165
330
  getEncodedEnr() {
166
331
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
167
332
  }
333
+ async getAllowedPublicSetup() {
334
+ return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
335
+ }
168
336
  /**
169
337
  * Method to determine if the node is ready to accept transactions.
170
338
  * @returns - Flag indicating the readiness for tx submission.
@@ -172,7 +340,7 @@ import { NodeMetrics } from './node_metrics.js';
172
340
  return Promise.resolve(this.p2pClient.isReady() ?? false);
173
341
  }
174
342
  async getNodeInfo() {
175
- const [nodeVersion, protocolVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
343
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
176
344
  this.getNodeVersion(),
177
345
  this.getVersion(),
178
346
  this.getChainId(),
@@ -183,7 +351,7 @@ import { NodeMetrics } from './node_metrics.js';
183
351
  const nodeInfo = {
184
352
  nodeVersion,
185
353
  l1ChainId: chainId,
186
- protocolVersion,
354
+ rollupVersion,
187
355
  enr,
188
356
  l1ContractAddresses: contractAddresses,
189
357
  protocolContractAddresses: protocolContractAddresses
@@ -195,7 +363,24 @@ import { NodeMetrics } from './node_metrics.js';
195
363
  * @param number - The block number being requested.
196
364
  * @returns The requested block.
197
365
  */ async getBlock(number) {
198
- return await this.blockSource.getBlock(number);
366
+ const blockNumber = number === 'latest' ? await this.getBlockNumber() : number;
367
+ return await this.blockSource.getBlock(blockNumber);
368
+ }
369
+ /**
370
+ * Get a block specified by its hash.
371
+ * @param blockHash - The block hash being requested.
372
+ * @returns The requested block.
373
+ */ async getBlockByHash(blockHash) {
374
+ const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
375
+ return publishedBlock?.block;
376
+ }
377
+ /**
378
+ * Get a block specified by its archive root.
379
+ * @param archive - The archive root being requested.
380
+ * @returns The requested block.
381
+ */ async getBlockByArchive(archive) {
382
+ const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
383
+ return publishedBlock?.block;
199
384
  }
200
385
  /**
201
386
  * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
@@ -205,6 +390,9 @@ import { NodeMetrics } from './node_metrics.js';
205
390
  */ async getBlocks(from, limit) {
206
391
  return await this.blockSource.getBlocks(from, limit) ?? [];
207
392
  }
393
+ async getPublishedBlocks(from, limit) {
394
+ return await this.blockSource.getPublishedBlocks(from, limit) ?? [];
395
+ }
208
396
  /**
209
397
  * Method to fetch the current base fees.
210
398
  * @returns The current base fees.
@@ -212,7 +400,7 @@ import { NodeMetrics } from './node_metrics.js';
212
400
  return await this.globalVariableBuilder.getCurrentBaseFees();
213
401
  }
214
402
  /**
215
- * Method to fetch the current block number.
403
+ * Method to fetch the latest block number synchronized by the node.
216
404
  * @returns The block number.
217
405
  */ async getBlockNumber() {
218
406
  return await this.blockSource.getBlockNumber();
@@ -238,25 +426,8 @@ import { NodeMetrics } from './node_metrics.js';
238
426
  */ getChainId() {
239
427
  return Promise.resolve(this.l1ChainId);
240
428
  }
241
- async getContractClass(id) {
242
- const klazz = await this.contractDataSource.getContractClass(id);
243
- // TODO(#10007): Remove this check. This is needed only because we're manually registering
244
- // some contracts in the archiver so they are available to all nodes (see `registerCommonContracts`
245
- // in `archiver/src/factory.ts`), but we still want clients to send the registration tx in order
246
- // to emit the corresponding nullifier, which is now being checked. Note that this method
247
- // is only called by the PXE to check if a contract is publicly registered.
248
- if (klazz) {
249
- const classNullifier = await siloNullifier(AztecAddress.fromNumber(REGISTERER_CONTRACT_ADDRESS), id);
250
- const worldState = await this.#getWorldState('latest');
251
- const [index] = await worldState.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, [
252
- classNullifier.toBuffer()
253
- ]);
254
- this.log.debug(`Registration nullifier ${classNullifier} for contract class ${id} found at index ${index}`);
255
- if (index === undefined) {
256
- return undefined;
257
- }
258
- }
259
- return klazz;
429
+ getContractClass(id) {
430
+ return this.contractDataSource.getContractClass(id);
260
431
  }
261
432
  getContract(address) {
262
433
  return this.contractDataSource.getContract(address);
@@ -272,10 +443,11 @@ import { NodeMetrics } from './node_metrics.js';
272
443
  /**
273
444
  * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
274
445
  * @param tags - The tags to filter the logs by.
446
+ * @param logsPerTag - The maximum number of logs to return for each tag. By default no limit is set
275
447
  * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
276
448
  * that tag.
277
- */ getLogsByTags(tags) {
278
- return this.logsSource.getLogsByTags(tags);
449
+ */ getLogsByTags(tags, logsPerTag) {
450
+ return this.logsSource.getLogsByTags(tags, logsPerTag);
279
451
  }
280
452
  /**
281
453
  * Gets public logs based on the provided filter.
@@ -295,18 +467,19 @@ import { NodeMetrics } from './node_metrics.js';
295
467
  * Method to submit a transaction to the p2p pool.
296
468
  * @param tx - The transaction to be submitted.
297
469
  */ async sendTx(tx) {
470
+ await this.txQueue.put(()=>this.#sendTx(tx));
471
+ }
472
+ async #sendTx(tx) {
298
473
  const timer = new Timer();
299
- const txHash = (await tx.getTxHash()).toString();
474
+ const txHash = tx.getTxHash().toString();
300
475
  const valid = await this.isValidTx(tx);
301
476
  if (valid.result !== 'valid') {
302
477
  const reason = valid.reason.join(', ');
303
478
  this.metrics.receivedTx(timer.ms(), false);
304
- this.log.warn(`Invalid tx ${txHash}: ${reason}`, {
479
+ this.log.warn(`Received invalid tx ${txHash}: ${reason}`, {
305
480
  txHash
306
481
  });
307
- // TODO(#10967): Throw when receiving an invalid tx instead of just returning
308
- // throw new Error(`Invalid tx: ${reason}`);
309
- return;
482
+ throw new Error(`Invalid tx: ${reason}`);
310
483
  }
311
484
  await this.p2pClient.sendTx(tx);
312
485
  this.metrics.receivedTx(timer.ms(), true);
@@ -334,63 +507,99 @@ import { NodeMetrics } from './node_metrics.js';
334
507
  /**
335
508
  * Method to stop the aztec node.
336
509
  */ async stop() {
337
- this.log.info(`Stopping`);
338
- await this.sequencer?.stop();
339
- await this.p2pClient.stop();
340
- await this.worldStateSynchronizer.stop();
510
+ this.log.info(`Stopping Aztec Node`);
511
+ await this.txQueue.end();
512
+ await tryStop(this.validatorsSentinel);
513
+ await tryStop(this.epochPruneWatcher);
514
+ await tryStop(this.slasherClient);
515
+ await tryStop(this.proofVerifier);
516
+ await tryStop(this.sequencer);
517
+ await tryStop(this.p2pClient);
518
+ await tryStop(this.worldStateSynchronizer);
341
519
  await tryStop(this.blockSource);
342
- await this.telemetry.stop();
343
- this.log.info(`Stopped`);
520
+ await tryStop(this.telemetry);
521
+ this.log.info(`Stopped Aztec Node`);
344
522
  }
345
523
  /**
346
524
  * Method to retrieve pending txs.
525
+ * @param limit - The number of items to returns
526
+ * @param after - The last known pending tx. Used for pagination
347
527
  * @returns - The pending txs.
348
- */ getPendingTxs() {
349
- return this.p2pClient.getPendingTxs();
528
+ */ getPendingTxs(limit, after) {
529
+ return this.p2pClient.getPendingTxs(limit, after);
350
530
  }
351
- async getPendingTxCount() {
352
- const pendingTxs = await this.getPendingTxs();
353
- return pendingTxs.length;
531
+ getPendingTxCount() {
532
+ return this.p2pClient.getPendingTxCount();
354
533
  }
355
534
  /**
356
- * Method to retrieve a single tx from the mempool or unfinalised chain.
535
+ * Method to retrieve a single tx from the mempool or unfinalized chain.
357
536
  * @param txHash - The transaction hash to return.
358
537
  * @returns - The tx if it exists.
359
538
  */ getTxByHash(txHash) {
360
539
  return Promise.resolve(this.p2pClient.getTxByHashFromPool(txHash));
361
540
  }
362
541
  /**
363
- * Method to retrieve txs from the mempool or unfinalised chain.
542
+ * Method to retrieve txs from the mempool or unfinalized chain.
364
543
  * @param txHash - The transaction hash to return.
365
544
  * @returns - The txs if it exists.
366
545
  */ async getTxsByHash(txHashes) {
367
546
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
368
547
  }
369
548
  /**
370
- * Find the indexes of the given leaves in the given tree.
371
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data
549
+ * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
550
+ * the leaves were inserted.
551
+ * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
372
552
  * @param treeId - The tree to search in.
373
- * @param leafValue - The values to search for
374
- * @returns The indexes of the given leaves in the given tree or undefined if not found.
553
+ * @param leafValues - The values to search for.
554
+ * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
375
555
  */ async findLeavesIndexes(blockNumber, treeId, leafValues) {
376
556
  const committedDb = await this.#getWorldState(blockNumber);
377
- return await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
378
- }
379
- /**
380
- * Find the block numbers of the given leaf indices in the given tree.
381
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data
382
- * @param treeId - The tree to search in.
383
- * @param leafIndices - The values to search for
384
- * @returns The indexes of the given leaves in the given tree or undefined if not found.
385
- */ async findBlockNumbersForIndexes(blockNumber, treeId, leafIndices) {
386
- const committedDb = await this.#getWorldState(blockNumber);
387
- return await committedDb.getBlockNumbersForLeafIndices(treeId, leafIndices);
388
- }
389
- async findNullifiersIndexesWithBlock(blockNumber, nullifiers) {
390
- if (blockNumber === 'latest') {
391
- blockNumber = await this.getBlockNumber();
557
+ const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
558
+ // We filter out undefined values
559
+ const indices = maybeIndices.filter((x)=>x !== undefined);
560
+ // Now we find the block numbers for the indices
561
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
562
+ // If any of the block numbers are undefined, we throw an error.
563
+ for(let i = 0; i < indices.length; i++){
564
+ if (blockNumbers[i] === undefined) {
565
+ throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
566
+ }
392
567
  }
393
- return this.nullifierSource.findNullifiersIndexesWithBlock(blockNumber, nullifiers);
568
+ // Get unique block numbers in order to optimize num calls to getLeafValue function.
569
+ const uniqueBlockNumbers = [
570
+ ...new Set(blockNumbers.filter((x)=>x !== undefined))
571
+ ];
572
+ // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
573
+ // (note that block number corresponds to the leaf index in the archive tree).
574
+ const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
575
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, blockNumber);
576
+ }));
577
+ // If any of the block hashes are undefined, we throw an error.
578
+ for(let i = 0; i < uniqueBlockNumbers.length; i++){
579
+ if (blockHashes[i] === undefined) {
580
+ throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
581
+ }
582
+ }
583
+ // Create InBlock objects by combining indices, blockNumbers and blockHashes and return them.
584
+ return maybeIndices.map((index, i)=>{
585
+ if (index === undefined) {
586
+ return undefined;
587
+ }
588
+ const blockNumber = blockNumbers[i];
589
+ if (blockNumber === undefined) {
590
+ return undefined;
591
+ }
592
+ const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
593
+ const blockHash = blockHashes[blockHashIndex];
594
+ if (!blockHash) {
595
+ return undefined;
596
+ }
597
+ return {
598
+ l2BlockNumber: Number(blockNumber),
599
+ l2BlockHash: L2BlockHash.fromField(blockHash),
600
+ data: index
601
+ };
602
+ });
394
603
  }
395
604
  /**
396
605
  * Returns a sibling path for the given index in the nullifier tree.
@@ -410,90 +619,58 @@ import { NodeMetrics } from './node_metrics.js';
410
619
  const committedDb = await this.#getWorldState(blockNumber);
411
620
  return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
412
621
  }
622
+ async getArchiveMembershipWitness(blockNumber, archive) {
623
+ const committedDb = await this.#getWorldState(blockNumber);
624
+ const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
625
+ archive
626
+ ]);
627
+ return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
628
+ }
629
+ async getNoteHashMembershipWitness(blockNumber, noteHash) {
630
+ const committedDb = await this.#getWorldState(blockNumber);
631
+ const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
632
+ noteHash
633
+ ]);
634
+ return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
635
+ }
413
636
  /**
414
637
  * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
415
638
  * @param blockNumber - The block number at which to get the data.
416
639
  * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
417
640
  * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
418
641
  */ async getL1ToL2MessageMembershipWitness(blockNumber, l1ToL2Message) {
419
- const index = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
420
- if (index === undefined) {
642
+ const db = await this.#getWorldState(blockNumber);
643
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
644
+ l1ToL2Message
645
+ ]);
646
+ if (!witness) {
421
647
  return undefined;
422
648
  }
423
- const committedDb = await this.#getWorldState(blockNumber);
424
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, index);
649
+ // REFACTOR: Return a MembershipWitness object
425
650
  return [
426
- index,
427
- siblingPath
651
+ witness.index,
652
+ witness.path
428
653
  ];
429
654
  }
655
+ async getL1ToL2MessageBlock(l1ToL2Message) {
656
+ const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
657
+ return messageIndex ? InboxLeaf.l2BlockFromIndex(messageIndex) : undefined;
658
+ }
430
659
  /**
431
660
  * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
432
661
  * @param l1ToL2Message - The L1 to L2 message to check.
433
662
  * @returns Whether the message is synced and ready to be included in a block.
434
663
  */ async isL1ToL2MessageSynced(l1ToL2Message) {
435
- return await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message) !== undefined;
664
+ const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
665
+ return messageIndex !== undefined;
436
666
  }
437
667
  /**
438
- * Returns the index of a l2ToL1Message in a ephemeral l2 to l1 data tree as well as its sibling path.
439
- * @remarks This tree is considered ephemeral because it is created on-demand by: taking all the l2ToL1 messages
440
- * in a single block, and then using them to make a variable depth append-only tree with these messages as leaves.
441
- * The tree is discarded immediately after calculating what we need from it.
442
- * TODO: Handle the case where two messages in the same tx have the same hash.
668
+ * Returns all the L2 to L1 messages in a block.
443
669
  * @param blockNumber - The block number at which to get the data.
444
- * @param l2ToL1Message - The l2ToL1Message get the index / sibling path for.
445
- * @returns A tuple of the index and the sibling path of the L2ToL1Message.
446
- */ async getL2ToL1MessageMembershipWitness(blockNumber, l2ToL1Message) {
670
+ * @returns The L2 to L1 messages (undefined if the block number is not found).
671
+ */ async getL2ToL1Messages(blockNumber) {
447
672
  const block = await this.blockSource.getBlock(blockNumber === 'latest' ? await this.getBlockNumber() : blockNumber);
448
- if (block === undefined) {
449
- throw new Error('Block is not defined');
450
- }
451
- const l2ToL1Messages = block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs);
452
- // Find index of message
453
- let indexOfMsgInSubtree = -1;
454
- const indexOfMsgTx = l2ToL1Messages.findIndex((msgs)=>{
455
- const idx = msgs.findIndex((msg)=>msg.equals(l2ToL1Message));
456
- indexOfMsgInSubtree = Math.max(indexOfMsgInSubtree, idx);
457
- return idx !== -1;
458
- });
459
- if (indexOfMsgTx === -1) {
460
- throw new Error('The L2ToL1Message you are trying to prove inclusion of does not exist');
461
- }
462
- const tempStores = [];
463
- // Construct message subtrees
464
- const l2toL1Subtrees = await Promise.all(l2ToL1Messages.map(async (msgs, i)=>{
465
- const store = openTmpStore(true);
466
- tempStores.push(store);
467
- const treeHeight = msgs.length <= 1 ? 1 : Math.ceil(Math.log2(msgs.length));
468
- const tree = new StandardTree(store, new SHA256Trunc(), `temp_msgs_subtrees_${i}`, treeHeight, 0n, Fr);
469
- await tree.appendLeaves(msgs);
470
- return tree;
471
- }));
472
- // path of the input msg from leaf -> first out hash calculated in base rolllup
473
- const subtreePathOfL2ToL1Message = await l2toL1Subtrees[indexOfMsgTx].getSiblingPath(BigInt(indexOfMsgInSubtree), true);
474
- const numTxs = block.body.txEffects.length;
475
- if (numTxs === 1) {
476
- return [
477
- BigInt(indexOfMsgInSubtree),
478
- subtreePathOfL2ToL1Message
479
- ];
480
- }
481
- const l2toL1SubtreeRoots = l2toL1Subtrees.map((t)=>Fr.fromBuffer(t.getRoot(true)));
482
- const maxTreeHeight = Math.ceil(Math.log2(l2toL1SubtreeRoots.length));
483
- // The root of this tree is the out_hash calculated in Noir => we truncate to match Noir's SHA
484
- const outHashTree = new UnbalancedTree(new SHA256Trunc(), 'temp_outhash_sibling_path', maxTreeHeight, Fr);
485
- await outHashTree.appendLeaves(l2toL1SubtreeRoots);
486
- const pathOfTxInOutHashTree = await outHashTree.getSiblingPath(l2toL1SubtreeRoots[indexOfMsgTx].toBigInt());
487
- // Append subtree path to out hash tree path
488
- const mergedPath = subtreePathOfL2ToL1Message.toBufferArray().concat(pathOfTxInOutHashTree.toBufferArray());
489
- // Append binary index of subtree path to binary index of out hash tree path
490
- const mergedIndex = parseInt(indexOfMsgTx.toString(2).concat(indexOfMsgInSubtree.toString(2).padStart(l2toL1Subtrees[indexOfMsgTx].getDepth(), '0')), 2);
491
- // clear the tmp stores
492
- await Promise.all(tempStores.map((store)=>store.delete()));
493
- return [
494
- BigInt(mergedIndex),
495
- new SiblingPath(mergedPath.length, mergedPath)
496
- ];
673
+ return block?.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs);
497
674
  }
498
675
  /**
499
676
  * Returns a sibling path for a leaf in the committed blocks tree.
@@ -520,22 +697,18 @@ import { NodeMetrics } from './node_metrics.js';
520
697
  * @returns The nullifier membership witness (if found).
521
698
  */ async getNullifierMembershipWitness(blockNumber, nullifier) {
522
699
  const db = await this.#getWorldState(blockNumber);
523
- const index = (await db.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, [
700
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
524
701
  nullifier.toBuffer()
525
- ]))[0];
526
- if (!index) {
702
+ ]);
703
+ if (!witness) {
527
704
  return undefined;
528
705
  }
529
- const leafPreimagePromise = db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
530
- const siblingPathPromise = db.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
531
- const [leafPreimage, siblingPath] = await Promise.all([
532
- leafPreimagePromise,
533
- siblingPathPromise
534
- ]);
706
+ const { index, path } = witness;
707
+ const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
535
708
  if (!leafPreimage) {
536
709
  return undefined;
537
710
  }
538
- return new NullifierMembershipWitness(BigInt(index), leafPreimage, siblingPath);
711
+ return new NullifierMembershipWitness(index, leafPreimage, path);
539
712
  }
540
713
  /**
541
714
  * Returns a low nullifier membership witness for a given nullifier at a given block.
@@ -564,7 +737,7 @@ import { NodeMetrics } from './node_metrics.js';
564
737
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
565
738
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
566
739
  }
567
- async getPublicDataTreeWitness(blockNumber, leafSlot) {
740
+ async getPublicDataWitness(blockNumber, leafSlot) {
568
741
  const committedDb = await this.#getWorldState(blockNumber);
569
742
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
570
743
  if (!lowLeafResult) {
@@ -593,7 +766,7 @@ import { NodeMetrics } from './node_metrics.js';
593
766
  return Fr.ZERO;
594
767
  }
595
768
  const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
596
- return preimage.value;
769
+ return preimage.leaf.value;
597
770
  }
598
771
  /**
599
772
  * Returns the currently committed block header, or the initial header if no blocks have been produced.
@@ -602,26 +775,51 @@ import { NodeMetrics } from './node_metrics.js';
602
775
  return blockNumber === 0 || blockNumber === 'latest' && await this.blockSource.getBlockNumber() === 0 ? this.worldStateSynchronizer.getCommitted().getInitialHeader() : this.blockSource.getBlockHeader(blockNumber);
603
776
  }
604
777
  /**
778
+ * Get a block header specified by its hash.
779
+ * @param blockHash - The block hash being requested.
780
+ * @returns The requested block header.
781
+ */ async getBlockHeaderByHash(blockHash) {
782
+ return await this.blockSource.getBlockHeaderByHash(blockHash);
783
+ }
784
+ /**
785
+ * Get a block header specified by its archive root.
786
+ * @param archive - The archive root being requested.
787
+ * @returns The requested block header.
788
+ */ async getBlockHeaderByArchive(archive) {
789
+ return await this.blockSource.getBlockHeaderByArchive(archive);
790
+ }
791
+ /**
605
792
  * Simulates the public part of a transaction with the current state.
606
793
  * @param tx - The transaction to simulate.
607
794
  **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
608
- const txHash = await tx.getTxHash();
795
+ // Check total gas limit for simulation
796
+ const gasSettings = tx.data.constants.txContext.gasSettings;
797
+ const txGasLimit = gasSettings.gasLimits.l2Gas;
798
+ const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
799
+ if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
800
+ throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
801
+ }
802
+ const txHash = tx.getTxHash();
609
803
  const blockNumber = await this.blockSource.getBlockNumber() + 1;
610
804
  // If sequencer is not initialized, we just set these values to zero for simulation.
611
- const coinbase = this.sequencer?.coinbase || EthAddress.ZERO;
612
- const feeRecipient = this.sequencer?.feeRecipient || AztecAddress.ZERO;
613
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(new Fr(blockNumber), coinbase, feeRecipient);
805
+ const coinbase = EthAddress.ZERO;
806
+ const feeRecipient = AztecAddress.ZERO;
807
+ const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
614
808
  const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry);
615
- const fork = await this.worldStateSynchronizer.fork();
616
809
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
617
810
  globalVariables: newGlobalVariables.toInspect(),
618
811
  txHash,
619
812
  blockNumber
620
813
  });
814
+ const merkleTreeFork = await this.worldStateSynchronizer.fork();
621
815
  try {
622
- const processor = publicProcessorFactory.create(fork, newGlobalVariables, skipFeeEnforcement);
816
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, {
817
+ skipFeeEnforcement,
818
+ clientInitiatedSimulation: true,
819
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
820
+ });
623
821
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
624
- const [processedTxs, failedTxs, returns] = await processor.process([
822
+ const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([
625
823
  tx
626
824
  ]);
627
825
  // REFACTOR: Consider returning the error rather than throwing
@@ -632,30 +830,47 @@ import { NodeMetrics } from './node_metrics.js';
632
830
  throw failedTxs[0].error;
633
831
  }
634
832
  const [processedTx] = processedTxs;
635
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.constants, processedTx.txEffect, returns, processedTx.gasUsed);
833
+ return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed);
636
834
  } finally{
637
- await fork.close();
835
+ await merkleTreeFork.close();
638
836
  }
639
837
  }
640
838
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
641
- const blockNumber = await this.blockSource.getBlockNumber() + 1;
642
839
  const db = this.worldStateSynchronizer.getCommitted();
643
840
  const verifier = isSimulation ? undefined : this.proofVerifier;
841
+ // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
842
+ const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
843
+ const blockNumber = await this.blockSource.getBlockNumber() + 1;
644
844
  const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
845
+ timestamp: nextSlotTimestamp,
645
846
  blockNumber,
646
847
  l1ChainId: this.l1ChainId,
647
- setupAllowList: this.config.allowedInSetup ?? await getDefaultAllowedSetupFunctions(),
848
+ rollupVersion: this.version,
849
+ setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
648
850
  gasFees: await this.getCurrentBaseFees(),
649
- skipFeeEnforcement
851
+ skipFeeEnforcement,
852
+ txsPermitted: !this.config.disableTransactions
650
853
  });
651
854
  return await validator.validateTx(tx);
652
855
  }
856
+ getConfig() {
857
+ const schema = AztecNodeAdminConfigSchema;
858
+ const keys = schema.keyof().options;
859
+ return Promise.resolve(pick(this.config, ...keys));
860
+ }
653
861
  async setConfig(config) {
654
862
  const newConfig = {
655
863
  ...this.config,
656
864
  ...config
657
865
  };
658
- await this.sequencer?.updateSequencerConfig(config);
866
+ this.sequencer?.updateConfig(config);
867
+ this.slasherClient?.updateConfig(config);
868
+ this.validatorsSentinel?.updateConfig(config);
869
+ await this.p2pClient.updateP2PConfig(config);
870
+ const archiver = this.blockSource;
871
+ if ('updateConfig' in archiver) {
872
+ archiver.updateConfig(config);
873
+ }
659
874
  if (newConfig.realProofs !== this.config.realProofs) {
660
875
  this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
661
876
  }
@@ -663,27 +878,120 @@ import { NodeMetrics } from './node_metrics.js';
663
878
  }
664
879
  getProtocolContractAddresses() {
665
880
  return Promise.resolve({
666
- classRegisterer: ProtocolContractAddress.ContractClassRegisterer,
881
+ classRegistry: ProtocolContractAddress.ContractClassRegistry,
667
882
  feeJuice: ProtocolContractAddress.FeeJuice,
668
- instanceDeployer: ProtocolContractAddress.ContractInstanceDeployer,
883
+ instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
669
884
  multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
670
885
  });
671
886
  }
672
- // TODO(#10007): Remove this method
673
- addContractClass(contractClass) {
674
- this.log.info(`Adding contract class via API ${contractClass.id}`);
675
- return this.contractDataSource.addContractClass(contractClass);
887
+ registerContractFunctionSignatures(signatures) {
888
+ return this.contractDataSource.registerContractFunctionSignatures(signatures);
889
+ }
890
+ getValidatorsStats() {
891
+ return this.validatorsSentinel?.computeStats() ?? Promise.resolve({
892
+ stats: {},
893
+ slotWindow: 0
894
+ });
676
895
  }
677
- registerContractFunctionSignatures(_address, signatures) {
678
- return this.contractDataSource.registerContractFunctionSignatures(_address, signatures);
896
+ getValidatorStats(validatorAddress, fromSlot, toSlot) {
897
+ return this.validatorsSentinel?.getValidatorStats(validatorAddress, fromSlot, toSlot) ?? Promise.resolve(undefined);
898
+ }
899
+ async startSnapshotUpload(location) {
900
+ // Note that we are forcefully casting the blocksource as an archiver
901
+ // We break support for archiver running remotely to the node
902
+ const archiver = this.blockSource;
903
+ if (!('backupTo' in archiver)) {
904
+ this.metrics.recordSnapshotError();
905
+ throw new Error('Archiver implementation does not support backups. Cannot generate snapshot.');
906
+ }
907
+ // Test that the archiver has done an initial sync.
908
+ if (!archiver.isInitialSyncComplete()) {
909
+ this.metrics.recordSnapshotError();
910
+ throw new Error(`Archiver initial sync not complete. Cannot start snapshot.`);
911
+ }
912
+ // And it has an L2 block hash
913
+ const l2BlockHash = await archiver.getL2Tips().then((tips)=>tips.latest.hash);
914
+ if (!l2BlockHash) {
915
+ this.metrics.recordSnapshotError();
916
+ throw new Error(`Archiver has no latest L2 block hash downloaded. Cannot start snapshot.`);
917
+ }
918
+ if (this.isUploadingSnapshot) {
919
+ this.metrics.recordSnapshotError();
920
+ throw new Error(`Snapshot upload already in progress. Cannot start another one until complete.`);
921
+ }
922
+ // Do not wait for the upload to be complete to return to the caller, but flag that an operation is in progress
923
+ this.isUploadingSnapshot = true;
924
+ const timer = new Timer();
925
+ void uploadSnapshot(location, this.blockSource, this.worldStateSynchronizer, this.config, this.log).then(()=>{
926
+ this.isUploadingSnapshot = false;
927
+ this.metrics.recordSnapshot(timer.ms());
928
+ }).catch((err)=>{
929
+ this.isUploadingSnapshot = false;
930
+ this.metrics.recordSnapshotError();
931
+ this.log.error(`Error uploading snapshot: ${err}`);
932
+ });
933
+ return Promise.resolve();
679
934
  }
680
- flushTxs() {
681
- if (!this.sequencer) {
682
- throw new Error(`Sequencer is not initialized`);
935
+ async rollbackTo(targetBlock, force) {
936
+ const archiver = this.blockSource;
937
+ if (!('rollbackTo' in archiver)) {
938
+ throw new Error('Archiver implementation does not support rollbacks.');
939
+ }
940
+ const finalizedBlock = await archiver.getL2Tips().then((tips)=>tips.finalized.number);
941
+ if (targetBlock < finalizedBlock) {
942
+ if (force) {
943
+ this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`);
944
+ await this.worldStateSynchronizer.clear();
945
+ await this.p2pClient.clear();
946
+ } else {
947
+ throw new Error(`Cannot rollback to block ${targetBlock} as it is before finalized ${finalizedBlock}`);
948
+ }
949
+ }
950
+ try {
951
+ this.log.info(`Pausing archiver and world state sync to start rollback`);
952
+ await archiver.stop();
953
+ await this.worldStateSynchronizer.stopSync();
954
+ const currentBlock = await archiver.getBlockNumber();
955
+ const blocksToUnwind = currentBlock - targetBlock;
956
+ this.log.info(`Unwinding ${count(blocksToUnwind, 'block')} from L2 block ${currentBlock} to ${targetBlock}`);
957
+ await archiver.rollbackTo(targetBlock);
958
+ this.log.info(`Unwinding complete.`);
959
+ } catch (err) {
960
+ this.log.error(`Error during rollback`, err);
961
+ throw err;
962
+ } finally{
963
+ this.log.info(`Resuming world state and archiver sync.`);
964
+ this.worldStateSynchronizer.resumeSync();
965
+ archiver.resume();
683
966
  }
684
- this.sequencer.flush();
967
+ }
968
+ async pauseSync() {
969
+ this.log.info(`Pausing archiver and world state sync`);
970
+ await this.blockSource.stop();
971
+ await this.worldStateSynchronizer.stopSync();
972
+ }
973
+ resumeSync() {
974
+ this.log.info(`Resuming world state and archiver sync.`);
975
+ this.worldStateSynchronizer.resumeSync();
976
+ this.blockSource.resume();
685
977
  return Promise.resolve();
686
978
  }
979
+ getSlashPayloads() {
980
+ if (!this.slasherClient) {
981
+ throw new Error(`Slasher client not enabled`);
982
+ }
983
+ return this.slasherClient.getSlashPayloads();
984
+ }
985
+ getSlashOffenses(round) {
986
+ if (!this.slasherClient) {
987
+ throw new Error(`Slasher client not enabled`);
988
+ }
989
+ if (round === 'all') {
990
+ return this.slasherClient.getPendingOffenses();
991
+ } else {
992
+ return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
993
+ }
994
+ }
687
995
  /**
688
996
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
689
997
  * @param blockNumber - The block number at which to get the data.
@@ -719,7 +1027,7 @@ import { NodeMetrics } from './node_metrics.js';
719
1027
  }
720
1028
  }
721
1029
  _ts_decorate([
722
- trackSpan('AztecNodeService.simulatePublicCalls', async (tx)=>({
723
- [Attributes.TX_HASH]: (await tx.getTxHash()).toString()
1030
+ trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1031
+ [Attributes.TX_HASH]: tx.getTxHash().toString()
724
1032
  }))
725
1033
  ], AztecNodeService.prototype, "simulatePublicCalls", null);