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

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 (48) hide show
  1. package/dest/aztec-node/config.d.ts +18 -10
  2. package/dest/aztec-node/config.d.ts.map +1 -1
  3. package/dest/aztec-node/config.js +81 -14
  4. package/dest/aztec-node/node_metrics.d.ts +5 -1
  5. package/dest/aztec-node/node_metrics.d.ts.map +1 -1
  6. package/dest/aztec-node/node_metrics.js +17 -7
  7. package/dest/aztec-node/server.d.ts +123 -86
  8. package/dest/aztec-node/server.d.ts.map +1 -1
  9. package/dest/aztec-node/server.js +994 -250
  10. package/dest/bin/index.d.ts +1 -1
  11. package/dest/bin/index.js +4 -2
  12. package/dest/index.d.ts +1 -2
  13. package/dest/index.d.ts.map +1 -1
  14. package/dest/index.js +0 -1
  15. package/dest/sentinel/config.d.ts +8 -0
  16. package/dest/sentinel/config.d.ts.map +1 -0
  17. package/dest/sentinel/config.js +29 -0
  18. package/dest/sentinel/factory.d.ts +9 -0
  19. package/dest/sentinel/factory.d.ts.map +1 -0
  20. package/dest/sentinel/factory.js +17 -0
  21. package/dest/sentinel/index.d.ts +3 -0
  22. package/dest/sentinel/index.d.ts.map +1 -0
  23. package/dest/sentinel/index.js +1 -0
  24. package/dest/sentinel/sentinel.d.ts +93 -0
  25. package/dest/sentinel/sentinel.d.ts.map +1 -0
  26. package/dest/sentinel/sentinel.js +403 -0
  27. package/dest/sentinel/store.d.ts +35 -0
  28. package/dest/sentinel/store.d.ts.map +1 -0
  29. package/dest/sentinel/store.js +170 -0
  30. package/dest/test/index.d.ts +31 -0
  31. package/dest/test/index.d.ts.map +1 -0
  32. package/dest/test/index.js +1 -0
  33. package/package.json +45 -35
  34. package/src/aztec-node/config.ts +132 -25
  35. package/src/aztec-node/node_metrics.ts +24 -14
  36. package/src/aztec-node/server.ts +809 -330
  37. package/src/bin/index.ts +4 -2
  38. package/src/index.ts +0 -1
  39. package/src/sentinel/config.ts +37 -0
  40. package/src/sentinel/factory.ts +36 -0
  41. package/src/sentinel/index.ts +8 -0
  42. package/src/sentinel/sentinel.ts +510 -0
  43. package/src/sentinel/store.ts +185 -0
  44. package/src/test/index.ts +32 -0
  45. package/dest/aztec-node/http_rpc_server.d.ts +0 -8
  46. package/dest/aztec-node/http_rpc_server.d.ts.map +0 -1
  47. package/dest/aztec-node/http_rpc_server.js +0 -9
  48. package/src/aztec-node/http_rpc_server.ts +0 -11
@@ -1,38 +1,423 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
369
+ }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
6
372
  }
373
+ var _dec, _initProto;
7
374
  import { createArchiver } from '@aztec/archiver';
8
- import { BBCircuitVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
9
- import { createBlobSinkClient } from '@aztec/blob-sink/client';
10
- import { INITIAL_L2_BLOCK_NUM, REGISTERER_CONTRACT_ADDRESS } from '@aztec/constants';
375
+ import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
376
+ import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
377
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
11
378
  import { EpochCache } from '@aztec/epoch-cache';
12
- import { createEthereumChain } from '@aztec/ethereum';
13
- import { compactArray } from '@aztec/foundation/collection';
379
+ import { createEthereumChain } from '@aztec/ethereum/chain';
380
+ import { getPublicClient } from '@aztec/ethereum/client';
381
+ import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
382
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
383
+ import { compactArray, pick } from '@aztec/foundation/collection';
384
+ import { Fr } from '@aztec/foundation/curves/bn254';
14
385
  import { EthAddress } from '@aztec/foundation/eth-address';
15
- import { Fr } from '@aztec/foundation/fields';
386
+ import { BadRequestError } from '@aztec/foundation/json-rpc';
16
387
  import { createLogger } from '@aztec/foundation/log';
388
+ import { count } from '@aztec/foundation/string';
17
389
  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';
390
+ import { MembershipWitness } from '@aztec/foundation/trees';
391
+ import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
392
+ import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
393
+ import { createForwarderL1TxUtilsFromEthSigner, createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
394
+ import { createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
22
395
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
23
- import { GlobalVariableBuilder, SequencerClient, createSlasherClient, createValidatorForAcceptingTxs, getDefaultAllowedSetupFunctions } from '@aztec/sequencer-client';
396
+ import { BlockBuilder, GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
24
397
  import { PublicProcessorFactory } from '@aztec/simulator/server';
398
+ import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
399
+ import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
25
400
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
26
- import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/stdlib/hash';
401
+ import { L2BlockHash } from '@aztec/stdlib/block';
402
+ import { GasFees } from '@aztec/stdlib/gas';
403
+ import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
404
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
27
405
  import { tryStop } from '@aztec/stdlib/interfaces/server';
406
+ import { InboxLeaf } from '@aztec/stdlib/messaging';
28
407
  import { P2PClientType } from '@aztec/stdlib/p2p';
29
408
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
30
409
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
410
+ import { getPackageVersion } from '@aztec/stdlib/update-checker';
31
411
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
32
- import { createValidatorClient } from '@aztec/validator-client';
412
+ import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient, createValidatorForAcceptingTxs } from '@aztec/validator-client';
33
413
  import { createWorldStateSynchronizer } from '@aztec/world-state';
34
- import { getPackageVersion } from './config.js';
414
+ import { createPublicClient, fallback, http } from 'viem';
415
+ import { createSentinel } from '../sentinel/factory.js';
416
+ import { createKeyStoreForValidator } from './config.js';
35
417
  import { NodeMetrics } from './node_metrics.js';
418
+ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
419
+ [Attributes.TX_HASH]: tx.getTxHash().toString()
420
+ }));
36
421
  /**
37
422
  * The aztec node.
38
423
  */ export class AztecNodeService {
@@ -42,35 +427,55 @@ import { NodeMetrics } from './node_metrics.js';
42
427
  logsSource;
43
428
  contractDataSource;
44
429
  l1ToL2MessageSource;
45
- nullifierSource;
46
430
  worldStateSynchronizer;
47
431
  sequencer;
432
+ slasherClient;
433
+ validatorsSentinel;
434
+ epochPruneWatcher;
48
435
  l1ChainId;
49
436
  version;
50
437
  globalVariableBuilder;
438
+ epochCache;
439
+ packageVersion;
51
440
  proofVerifier;
52
441
  telemetry;
53
442
  log;
54
- packageVersion;
443
+ blobClient;
444
+ static{
445
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
446
+ [
447
+ _dec,
448
+ 2,
449
+ "simulatePublicCalls"
450
+ ]
451
+ ], []));
452
+ }
55
453
  metrics;
454
+ // Prevent two snapshot operations to happen simultaneously
455
+ isUploadingSnapshot;
56
456
  tracer;
57
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, nullifierSource, worldStateSynchronizer, sequencer, l1ChainId, version, globalVariableBuilder, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node')){
457
+ constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient){
58
458
  this.config = config;
59
459
  this.p2pClient = p2pClient;
60
460
  this.blockSource = blockSource;
61
461
  this.logsSource = logsSource;
62
462
  this.contractDataSource = contractDataSource;
63
463
  this.l1ToL2MessageSource = l1ToL2MessageSource;
64
- this.nullifierSource = nullifierSource;
65
464
  this.worldStateSynchronizer = worldStateSynchronizer;
66
465
  this.sequencer = sequencer;
466
+ this.slasherClient = slasherClient;
467
+ this.validatorsSentinel = validatorsSentinel;
468
+ this.epochPruneWatcher = epochPruneWatcher;
67
469
  this.l1ChainId = l1ChainId;
68
470
  this.version = version;
69
471
  this.globalVariableBuilder = globalVariableBuilder;
472
+ this.epochCache = epochCache;
473
+ this.packageVersion = packageVersion;
70
474
  this.proofVerifier = proofVerifier;
71
475
  this.telemetry = telemetry;
72
476
  this.log = log;
73
- this.packageVersion = getPackageVersion();
477
+ this.blobClient = blobClient;
478
+ this.isUploadingSnapshot = (_initProto(this), false);
74
479
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
75
480
  this.tracer = telemetry.getTracer('AztecNodeService');
76
481
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
@@ -87,59 +492,228 @@ import { NodeMetrics } from './node_metrics.js';
87
492
  * initializes the Aztec Node, wait for component to sync.
88
493
  * @param config - The configuration to be used by the aztec node.
89
494
  * @returns - A fully synced Aztec Node for use in development/testing.
90
- */ static async createAndSync(config, deps = {}, options = {}) {
91
- const telemetry = deps.telemetry ?? getTelemetryClient();
495
+ */ static async createAndSync(inputConfig, deps = {}, options = {}) {
496
+ const config = {
497
+ ...inputConfig
498
+ }; // Copy the config so we dont mutate the input object
92
499
  const log = deps.logger ?? createLogger('node');
500
+ const packageVersion = getPackageVersion() ?? '';
501
+ const telemetry = deps.telemetry ?? getTelemetryClient();
93
502
  const dateProvider = deps.dateProvider ?? new DateProvider();
94
- const blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config);
95
503
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
96
- //validate that the actual chain id matches that specified in configuration
504
+ // Build a key store from file if given or from environment otherwise
505
+ let keyStoreManager;
506
+ const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
507
+ if (keyStoreProvided) {
508
+ const keyStores = loadKeystores(config.keyStoreDirectory);
509
+ keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
510
+ } else {
511
+ const keyStore = createKeyStoreForValidator(config);
512
+ if (keyStore) {
513
+ keyStoreManager = new KeystoreManager(keyStore);
514
+ }
515
+ }
516
+ await keyStoreManager?.validateSigners();
517
+ // If we are a validator, verify our configuration before doing too much more.
518
+ if (!config.disableValidator) {
519
+ if (keyStoreManager === undefined) {
520
+ throw new Error('Failed to create key store, a requirement for running a validator');
521
+ }
522
+ if (!keyStoreProvided) {
523
+ log.warn('KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS');
524
+ }
525
+ ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
526
+ }
527
+ // validate that the actual chain id matches that specified in configuration
97
528
  if (config.l1ChainId !== ethereumChain.chainInfo.id) {
98
529
  throw new Error(`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`);
99
530
  }
100
- const archiver = await createArchiver(config, blobSinkClient, {
101
- blockUntilSync: true
102
- }, telemetry);
531
+ const publicClient = createPublicClient({
532
+ chain: ethereumChain.chainInfo,
533
+ transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
534
+ batch: false
535
+ }))),
536
+ pollingInterval: config.viemPollingIntervalMS
537
+ });
538
+ const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
539
+ // Overwrite the passed in vars.
540
+ config.l1Contracts = {
541
+ ...config.l1Contracts,
542
+ ...l1ContractsAddresses
543
+ };
544
+ const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
545
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
546
+ rollupContract.getL1GenesisTime(),
547
+ rollupContract.getSlotDuration(),
548
+ rollupContract.getVersion()
549
+ ]);
550
+ config.rollupVersion ??= Number(rollupVersionFromRollup);
551
+ if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
552
+ 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}).`);
553
+ }
554
+ const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
555
+ // attempt snapshot sync if possible
556
+ await trySnapshotSync(config, log);
557
+ const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
558
+ dateProvider
559
+ });
560
+ const archiver = await createArchiver(config, {
561
+ blobClient,
562
+ epochCache,
563
+ telemetry,
564
+ dateProvider
565
+ }, {
566
+ blockUntilSync: !config.skipArchiverInitialSync
567
+ });
103
568
  // now create the merkle trees and the world state synchronizer
104
569
  const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
105
- const proofVerifier = config.realProofs ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier();
570
+ const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
106
571
  if (!config.realProofs) {
107
572
  log.warn(`Aztec node is accepting fake proofs`);
108
573
  }
109
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
110
- dateProvider
111
- });
574
+ const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
112
575
  // 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`);
576
+ const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
577
+ // We should really not be modifying the config object
578
+ config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
579
+ // Create BlockBuilder for EpochPruneWatcher (slasher functionality)
580
+ const blockBuilder = new BlockBuilder({
581
+ ...config,
582
+ l1GenesisTime,
583
+ slotDuration: Number(slotDuration)
584
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry);
585
+ // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
586
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
587
+ ...config,
588
+ l1GenesisTime,
589
+ slotDuration: Number(slotDuration)
590
+ }, archiver, dateProvider, telemetry);
591
+ // We'll accumulate sentinel watchers here
592
+ const watchers = [];
593
+ // Create validator client if required
122
594
  const validatorClient = createValidatorClient(config, {
595
+ checkpointsBuilder: validatorCheckpointsBuilder,
596
+ worldState: worldStateSynchronizer,
123
597
  p2pClient,
124
598
  telemetry,
125
599
  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,
600
+ epochCache,
601
+ blockSource: archiver,
137
602
  l1ToL2MessageSource: archiver,
138
- telemetry,
139
- dateProvider,
140
- blobSinkClient
603
+ keyStoreManager,
604
+ blobClient
141
605
  });
142
- return new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, ethereumChain.chainInfo.id, config.version, new GlobalVariableBuilder(config), proofVerifier, telemetry, log);
606
+ // If we have a validator client, register it as a source of offenses for the slasher,
607
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
608
+ // like attestations or auths will fail.
609
+ if (validatorClient) {
610
+ watchers.push(validatorClient);
611
+ if (!options.dontStartSequencer) {
612
+ await validatorClient.registerHandlers();
613
+ }
614
+ }
615
+ // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
616
+ // create a BlockProposalHandler to reexecute block proposals for monitoring
617
+ if (!validatorClient && config.alwaysReexecuteBlockProposals) {
618
+ log.info('Setting up block proposal reexecution for monitoring');
619
+ createBlockProposalHandler(config, {
620
+ checkpointsBuilder: validatorCheckpointsBuilder,
621
+ worldState: worldStateSynchronizer,
622
+ epochCache,
623
+ blockSource: archiver,
624
+ l1ToL2MessageSource: archiver,
625
+ p2pClient,
626
+ dateProvider,
627
+ telemetry
628
+ }).registerForReexecution(p2pClient);
629
+ }
630
+ // Start world state and wait for it to sync to the archiver.
631
+ await worldStateSynchronizer.start();
632
+ // Start p2p. Note that it depends on world state to be running.
633
+ await p2pClient.start();
634
+ const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
635
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
636
+ watchers.push(validatorsSentinel);
637
+ }
638
+ let epochPruneWatcher;
639
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
640
+ epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), blockBuilder, config);
641
+ watchers.push(epochPruneWatcher);
642
+ }
643
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
644
+ let attestationsBlockWatcher;
645
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
646
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
647
+ watchers.push(attestationsBlockWatcher);
648
+ }
649
+ // Start p2p-related services once the archiver has completed sync
650
+ void archiver.waitForInitialSync().then(async ()=>{
651
+ await p2pClient.start();
652
+ await validatorsSentinel?.start();
653
+ await epochPruneWatcher?.start();
654
+ await attestationsBlockWatcher?.start();
655
+ log.info(`All p2p services started`);
656
+ }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
657
+ // Validator enabled, create/start relevant service
658
+ let sequencer;
659
+ let slasherClient;
660
+ if (!config.disableValidator && validatorClient) {
661
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
662
+ // as they are executed when the node is selected as proposer.
663
+ const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
664
+ slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
665
+ await slasherClient.start();
666
+ const l1TxUtils = config.publisherForwarderAddress ? await createForwarderL1TxUtilsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.publisherForwarderAddress, {
667
+ ...config,
668
+ scope: 'sequencer'
669
+ }, {
670
+ telemetry,
671
+ logger: log.createChild('l1-tx-utils'),
672
+ dateProvider
673
+ }) : await createL1TxUtilsWithBlobsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
674
+ ...config,
675
+ scope: 'sequencer'
676
+ }, {
677
+ telemetry,
678
+ logger: log.createChild('l1-tx-utils'),
679
+ dateProvider
680
+ });
681
+ // Create and start the sequencer client
682
+ const checkpointsBuilder = new CheckpointsBuilder({
683
+ ...config,
684
+ l1GenesisTime,
685
+ slotDuration: Number(slotDuration)
686
+ }, archiver, dateProvider, telemetry);
687
+ sequencer = await SequencerClient.new(config, {
688
+ ...deps,
689
+ epochCache,
690
+ l1TxUtils,
691
+ validatorClient,
692
+ p2pClient,
693
+ worldStateSynchronizer,
694
+ slasherClient,
695
+ checkpointsBuilder,
696
+ l2BlockSource: archiver,
697
+ l1ToL2MessageSource: archiver,
698
+ telemetry,
699
+ dateProvider,
700
+ blobClient,
701
+ nodeKeyStore: keyStoreManager
702
+ });
703
+ }
704
+ if (!options.dontStartSequencer && sequencer) {
705
+ await sequencer.start();
706
+ log.verbose(`Sequencer started`);
707
+ } else if (sequencer) {
708
+ log.warn(`Sequencer created but not started`);
709
+ }
710
+ const globalVariableBuilder = new GlobalVariableBuilder({
711
+ ...config,
712
+ rollupVersion: BigInt(config.rollupVersion),
713
+ l1GenesisTime,
714
+ slotDuration: Number(slotDuration)
715
+ });
716
+ return new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry, log, blobClient);
143
717
  }
144
718
  /**
145
719
  * Returns the sequencer client instance.
@@ -165,6 +739,9 @@ import { NodeMetrics } from './node_metrics.js';
165
739
  getEncodedEnr() {
166
740
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
167
741
  }
742
+ async getAllowedPublicSetup() {
743
+ return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
744
+ }
168
745
  /**
169
746
  * Method to determine if the node is ready to accept transactions.
170
747
  * @returns - Flag indicating the readiness for tx submission.
@@ -172,7 +749,7 @@ import { NodeMetrics } from './node_metrics.js';
172
749
  return Promise.resolve(this.p2pClient.isReady() ?? false);
173
750
  }
174
751
  async getNodeInfo() {
175
- const [nodeVersion, protocolVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
752
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
176
753
  this.getNodeVersion(),
177
754
  this.getVersion(),
178
755
  this.getChainId(),
@@ -183,7 +760,7 @@ import { NodeMetrics } from './node_metrics.js';
183
760
  const nodeInfo = {
184
761
  nodeVersion,
185
762
  l1ChainId: chainId,
186
- protocolVersion,
763
+ rollupVersion,
187
764
  enr,
188
765
  l1ContractAddresses: contractAddresses,
189
766
  protocolContractAddresses: protocolContractAddresses
@@ -195,7 +772,24 @@ import { NodeMetrics } from './node_metrics.js';
195
772
  * @param number - The block number being requested.
196
773
  * @returns The requested block.
197
774
  */ async getBlock(number) {
198
- return await this.blockSource.getBlock(number);
775
+ const blockNumber = number === 'latest' ? await this.getBlockNumber() : number;
776
+ return await this.blockSource.getBlock(blockNumber);
777
+ }
778
+ /**
779
+ * Get a block specified by its hash.
780
+ * @param blockHash - The block hash being requested.
781
+ * @returns The requested block.
782
+ */ async getBlockByHash(blockHash) {
783
+ const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
784
+ return publishedBlock?.block;
785
+ }
786
+ /**
787
+ * Get a block specified by its archive root.
788
+ * @param archive - The archive root being requested.
789
+ * @returns The requested block.
790
+ */ async getBlockByArchive(archive) {
791
+ const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
792
+ return publishedBlock?.block;
199
793
  }
200
794
  /**
201
795
  * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
@@ -205,14 +799,35 @@ import { NodeMetrics } from './node_metrics.js';
205
799
  */ async getBlocks(from, limit) {
206
800
  return await this.blockSource.getBlocks(from, limit) ?? [];
207
801
  }
802
+ async getPublishedBlocks(from, limit) {
803
+ return await this.blockSource.getPublishedBlocks(from, limit) ?? [];
804
+ }
805
+ async getPublishedCheckpoints(from, limit) {
806
+ return await this.blockSource.getPublishedCheckpoints(from, limit) ?? [];
807
+ }
808
+ async getL2BlocksNew(from, limit) {
809
+ return await this.blockSource.getL2BlocksNew(from, limit) ?? [];
810
+ }
811
+ async getCheckpointedBlocks(from, limit, proven) {
812
+ return await this.blockSource.getCheckpointedBlocks(from, limit, proven) ?? [];
813
+ }
208
814
  /**
209
- * Method to fetch the current base fees.
210
- * @returns The current base fees.
211
- */ async getCurrentBaseFees() {
212
- return await this.globalVariableBuilder.getCurrentBaseFees();
815
+ * Method to fetch the current min L2 fees.
816
+ * @returns The current min L2 fees.
817
+ */ async getCurrentMinFees() {
818
+ return await this.globalVariableBuilder.getCurrentMinFees();
819
+ }
820
+ async getMaxPriorityFees() {
821
+ for await (const tx of this.p2pClient.iteratePendingTxs()){
822
+ return tx.getGasSettings().maxPriorityFeesPerGas;
823
+ }
824
+ return GasFees.from({
825
+ feePerDaGas: 0n,
826
+ feePerL2Gas: 0n
827
+ });
213
828
  }
214
829
  /**
215
- * Method to fetch the current block number.
830
+ * Method to fetch the latest block number synchronized by the node.
216
831
  * @returns The block number.
217
832
  */ async getBlockNumber() {
218
833
  return await this.blockSource.getBlockNumber();
@@ -238,44 +853,17 @@ import { NodeMetrics } from './node_metrics.js';
238
853
  */ getChainId() {
239
854
  return Promise.resolve(this.l1ChainId);
240
855
  }
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;
856
+ getContractClass(id) {
857
+ return this.contractDataSource.getContractClass(id);
260
858
  }
261
859
  getContract(address) {
262
860
  return this.contractDataSource.getContract(address);
263
861
  }
264
- /**
265
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
266
- * @param from - The block number from which to begin retrieving logs.
267
- * @param limit - The maximum number of blocks to retrieve logs from.
268
- * @returns An array of private logs from the specified range of blocks.
269
- */ getPrivateLogs(from, limit) {
270
- return this.logsSource.getPrivateLogs(from, limit);
862
+ getPrivateLogsByTags(tags) {
863
+ return this.logsSource.getPrivateLogsByTags(tags);
271
864
  }
272
- /**
273
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
274
- * @param tags - The tags to filter the logs by.
275
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
276
- * that tag.
277
- */ getLogsByTags(tags) {
278
- return this.logsSource.getLogsByTags(tags);
865
+ getPublicLogsByTagsFromContract(contractAddress, tags) {
866
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags);
279
867
  }
280
868
  /**
281
869
  * Gets public logs based on the provided filter.
@@ -295,18 +883,19 @@ import { NodeMetrics } from './node_metrics.js';
295
883
  * Method to submit a transaction to the p2p pool.
296
884
  * @param tx - The transaction to be submitted.
297
885
  */ async sendTx(tx) {
886
+ await this.#sendTx(tx);
887
+ }
888
+ async #sendTx(tx) {
298
889
  const timer = new Timer();
299
- const txHash = (await tx.getTxHash()).toString();
890
+ const txHash = tx.getTxHash().toString();
300
891
  const valid = await this.isValidTx(tx);
301
892
  if (valid.result !== 'valid') {
302
893
  const reason = valid.reason.join(', ');
303
894
  this.metrics.receivedTx(timer.ms(), false);
304
- this.log.warn(`Invalid tx ${txHash}: ${reason}`, {
895
+ this.log.warn(`Received invalid tx ${txHash}: ${reason}`, {
305
896
  txHash
306
897
  });
307
- // TODO(#10967): Throw when receiving an invalid tx instead of just returning
308
- // throw new Error(`Invalid tx: ${reason}`);
309
- return;
898
+ throw new Error(`Invalid tx: ${reason}`);
310
899
  }
311
900
  await this.p2pClient.sendTx(tx);
312
901
  this.metrics.receivedTx(timer.ms(), true);
@@ -334,63 +923,105 @@ import { NodeMetrics } from './node_metrics.js';
334
923
  /**
335
924
  * Method to stop the aztec node.
336
925
  */ async stop() {
337
- this.log.info(`Stopping`);
338
- await this.sequencer?.stop();
339
- await this.p2pClient.stop();
340
- await this.worldStateSynchronizer.stop();
926
+ this.log.info(`Stopping Aztec Node`);
927
+ await tryStop(this.validatorsSentinel);
928
+ await tryStop(this.epochPruneWatcher);
929
+ await tryStop(this.slasherClient);
930
+ await tryStop(this.proofVerifier);
931
+ await tryStop(this.sequencer);
932
+ await tryStop(this.p2pClient);
933
+ await tryStop(this.worldStateSynchronizer);
341
934
  await tryStop(this.blockSource);
342
- await this.telemetry.stop();
343
- this.log.info(`Stopped`);
935
+ await tryStop(this.blobClient);
936
+ await tryStop(this.telemetry);
937
+ this.log.info(`Stopped Aztec Node`);
938
+ }
939
+ /**
940
+ * Returns the blob client used by this node.
941
+ * @internal - Exposed for testing purposes only.
942
+ */ getBlobClient() {
943
+ return this.blobClient;
344
944
  }
345
945
  /**
346
946
  * Method to retrieve pending txs.
947
+ * @param limit - The number of items to returns
948
+ * @param after - The last known pending tx. Used for pagination
347
949
  * @returns - The pending txs.
348
- */ getPendingTxs() {
349
- return this.p2pClient.getPendingTxs();
950
+ */ getPendingTxs(limit, after) {
951
+ return this.p2pClient.getPendingTxs(limit, after);
350
952
  }
351
- async getPendingTxCount() {
352
- const pendingTxs = await this.getPendingTxs();
353
- return pendingTxs.length;
953
+ getPendingTxCount() {
954
+ return this.p2pClient.getPendingTxCount();
354
955
  }
355
956
  /**
356
- * Method to retrieve a single tx from the mempool or unfinalised chain.
957
+ * Method to retrieve a single tx from the mempool or unfinalized chain.
357
958
  * @param txHash - The transaction hash to return.
358
959
  * @returns - The tx if it exists.
359
960
  */ getTxByHash(txHash) {
360
961
  return Promise.resolve(this.p2pClient.getTxByHashFromPool(txHash));
361
962
  }
362
963
  /**
363
- * Method to retrieve txs from the mempool or unfinalised chain.
964
+ * Method to retrieve txs from the mempool or unfinalized chain.
364
965
  * @param txHash - The transaction hash to return.
365
966
  * @returns - The txs if it exists.
366
967
  */ async getTxsByHash(txHashes) {
367
968
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
368
969
  }
369
970
  /**
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
971
+ * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
972
+ * the leaves were inserted.
973
+ * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
372
974
  * @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.
975
+ * @param leafValues - The values to search for.
976
+ * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
375
977
  */ async findLeavesIndexes(blockNumber, treeId, leafValues) {
376
978
  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();
979
+ const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
980
+ // We filter out undefined values
981
+ const indices = maybeIndices.filter((x)=>x !== undefined);
982
+ // Now we find the block numbers for the indices
983
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
984
+ // If any of the block numbers are undefined, we throw an error.
985
+ for(let i = 0; i < indices.length; i++){
986
+ if (blockNumbers[i] === undefined) {
987
+ throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
988
+ }
989
+ }
990
+ // Get unique block numbers in order to optimize num calls to getLeafValue function.
991
+ const uniqueBlockNumbers = [
992
+ ...new Set(blockNumbers.filter((x)=>x !== undefined))
993
+ ];
994
+ // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
995
+ // (note that block number corresponds to the leaf index in the archive tree).
996
+ const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
997
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
998
+ }));
999
+ // If any of the block hashes are undefined, we throw an error.
1000
+ for(let i = 0; i < uniqueBlockNumbers.length; i++){
1001
+ if (blockHashes[i] === undefined) {
1002
+ throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1003
+ }
392
1004
  }
393
- return this.nullifierSource.findNullifiersIndexesWithBlock(blockNumber, nullifiers);
1005
+ // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1006
+ return maybeIndices.map((index, i)=>{
1007
+ if (index === undefined) {
1008
+ return undefined;
1009
+ }
1010
+ const blockNumber = blockNumbers[i];
1011
+ if (blockNumber === undefined) {
1012
+ return undefined;
1013
+ }
1014
+ const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1015
+ const blockHash = blockHashes[blockHashIndex];
1016
+ if (!blockHash) {
1017
+ return undefined;
1018
+ }
1019
+ return {
1020
+ l2BlockNumber: BlockNumber(Number(blockNumber)),
1021
+ l2BlockHash: L2BlockHash.fromField(blockHash),
1022
+ data: index
1023
+ };
1024
+ });
394
1025
  }
395
1026
  /**
396
1027
  * Returns a sibling path for the given index in the nullifier tree.
@@ -410,90 +1041,71 @@ import { NodeMetrics } from './node_metrics.js';
410
1041
  const committedDb = await this.#getWorldState(blockNumber);
411
1042
  return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
412
1043
  }
1044
+ async getArchiveMembershipWitness(blockNumber, archive) {
1045
+ const committedDb = await this.#getWorldState(blockNumber);
1046
+ const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1047
+ archive
1048
+ ]);
1049
+ return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1050
+ }
1051
+ async getNoteHashMembershipWitness(blockNumber, noteHash) {
1052
+ const committedDb = await this.#getWorldState(blockNumber);
1053
+ const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1054
+ noteHash
1055
+ ]);
1056
+ return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1057
+ }
413
1058
  /**
414
1059
  * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
415
1060
  * @param blockNumber - The block number at which to get the data.
416
1061
  * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
417
1062
  * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
418
1063
  */ async getL1ToL2MessageMembershipWitness(blockNumber, l1ToL2Message) {
419
- const index = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
420
- if (index === undefined) {
1064
+ const db = await this.#getWorldState(blockNumber);
1065
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1066
+ l1ToL2Message
1067
+ ]);
1068
+ if (!witness) {
421
1069
  return undefined;
422
1070
  }
423
- const committedDb = await this.#getWorldState(blockNumber);
424
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, index);
1071
+ // REFACTOR: Return a MembershipWitness object
425
1072
  return [
426
- index,
427
- siblingPath
1073
+ witness.index,
1074
+ witness.path
428
1075
  ];
429
1076
  }
1077
+ async getL1ToL2MessageBlock(l1ToL2Message) {
1078
+ const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1079
+ return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
1080
+ }
430
1081
  /**
431
1082
  * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
432
1083
  * @param l1ToL2Message - The L1 to L2 message to check.
433
1084
  * @returns Whether the message is synced and ready to be included in a block.
434
1085
  */ async isL1ToL2MessageSynced(l1ToL2Message) {
435
- return await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message) !== undefined;
1086
+ const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1087
+ return messageIndex !== undefined;
436
1088
  }
437
1089
  /**
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.
443
- * @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) {
447
- 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
- ];
1090
+ * Returns all the L2 to L1 messages in an epoch.
1091
+ * @param epoch - The epoch at which to get the data.
1092
+ * @returns The L2 to L1 messages (empty array if the epoch is not found).
1093
+ */ async getL2ToL1Messages(epoch) {
1094
+ // Assumes `getBlocksForEpoch` returns blocks in ascending order of block number.
1095
+ const blocks = await this.blockSource.getBlocksForEpoch(epoch);
1096
+ const blocksInCheckpoints = [];
1097
+ let previousSlotNumber = SlotNumber.ZERO;
1098
+ let checkpointIndex = -1;
1099
+ for (const block of blocks){
1100
+ const slotNumber = block.header.globalVariables.slotNumber;
1101
+ if (slotNumber !== previousSlotNumber) {
1102
+ checkpointIndex++;
1103
+ blocksInCheckpoints.push([]);
1104
+ previousSlotNumber = slotNumber;
1105
+ }
1106
+ blocksInCheckpoints[checkpointIndex].push(block);
480
1107
  }
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
- ];
1108
+ return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
497
1109
  }
498
1110
  /**
499
1111
  * Returns a sibling path for a leaf in the committed blocks tree.
@@ -520,22 +1132,18 @@ import { NodeMetrics } from './node_metrics.js';
520
1132
  * @returns The nullifier membership witness (if found).
521
1133
  */ async getNullifierMembershipWitness(blockNumber, nullifier) {
522
1134
  const db = await this.#getWorldState(blockNumber);
523
- const index = (await db.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, [
1135
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
524
1136
  nullifier.toBuffer()
525
- ]))[0];
526
- if (!index) {
1137
+ ]);
1138
+ if (!witness) {
527
1139
  return undefined;
528
1140
  }
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
- ]);
1141
+ const { index, path } = witness;
1142
+ const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
535
1143
  if (!leafPreimage) {
536
1144
  return undefined;
537
1145
  }
538
- return new NullifierMembershipWitness(BigInt(index), leafPreimage, siblingPath);
1146
+ return new NullifierMembershipWitness(index, leafPreimage, path);
539
1147
  }
540
1148
  /**
541
1149
  * Returns a low nullifier membership witness for a given nullifier at a given block.
@@ -564,7 +1172,7 @@ import { NodeMetrics } from './node_metrics.js';
564
1172
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
565
1173
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
566
1174
  }
567
- async getPublicDataTreeWitness(blockNumber, leafSlot) {
1175
+ async getPublicDataWitness(blockNumber, leafSlot) {
568
1176
  const committedDb = await this.#getWorldState(blockNumber);
569
1177
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
570
1178
  if (!lowLeafResult) {
@@ -593,35 +1201,66 @@ import { NodeMetrics } from './node_metrics.js';
593
1201
  return Fr.ZERO;
594
1202
  }
595
1203
  const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
596
- return preimage.value;
1204
+ return preimage.leaf.value;
597
1205
  }
598
1206
  /**
599
1207
  * Returns the currently committed block header, or the initial header if no blocks have been produced.
600
1208
  * @returns The current committed block header.
601
1209
  */ async getBlockHeader(blockNumber = 'latest') {
602
- return blockNumber === 0 || blockNumber === 'latest' && await this.blockSource.getBlockNumber() === 0 ? this.worldStateSynchronizer.getCommitted().getInitialHeader() : this.blockSource.getBlockHeader(blockNumber);
1210
+ return blockNumber === BlockNumber.ZERO || blockNumber === 'latest' && await this.blockSource.getBlockNumber() === BlockNumber.ZERO ? this.worldStateSynchronizer.getCommitted().getInitialHeader() : this.blockSource.getBlockHeader(blockNumber === 'latest' ? blockNumber : blockNumber);
1211
+ }
1212
+ /**
1213
+ * Get a block header specified by its hash.
1214
+ * @param blockHash - The block hash being requested.
1215
+ * @returns The requested block header.
1216
+ */ async getBlockHeaderByHash(blockHash) {
1217
+ return await this.blockSource.getBlockHeaderByHash(blockHash);
1218
+ }
1219
+ /**
1220
+ * Get a block header specified by its archive root.
1221
+ * @param archive - The archive root being requested.
1222
+ * @returns The requested block header.
1223
+ */ async getBlockHeaderByArchive(archive) {
1224
+ return await this.blockSource.getBlockHeaderByArchive(archive);
603
1225
  }
604
1226
  /**
605
1227
  * Simulates the public part of a transaction with the current state.
606
1228
  * @param tx - The transaction to simulate.
607
1229
  **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
608
- const txHash = await tx.getTxHash();
609
- const blockNumber = await this.blockSource.getBlockNumber() + 1;
1230
+ // Check total gas limit for simulation
1231
+ const gasSettings = tx.data.constants.txContext.gasSettings;
1232
+ const txGasLimit = gasSettings.gasLimits.l2Gas;
1233
+ const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1234
+ if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1235
+ throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1236
+ }
1237
+ const txHash = tx.getTxHash();
1238
+ const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
610
1239
  // 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);
1240
+ const coinbase = EthAddress.ZERO;
1241
+ const feeRecipient = AztecAddress.ZERO;
1242
+ const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
614
1243
  const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry);
615
- const fork = await this.worldStateSynchronizer.fork();
616
1244
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
617
1245
  globalVariables: newGlobalVariables.toInspect(),
618
1246
  txHash,
619
1247
  blockNumber
620
1248
  });
1249
+ const merkleTreeFork = await this.worldStateSynchronizer.fork();
621
1250
  try {
622
- const processor = publicProcessorFactory.create(fork, newGlobalVariables, skipFeeEnforcement);
1251
+ const config = PublicSimulatorConfig.from({
1252
+ skipFeeEnforcement,
1253
+ collectDebugLogs: true,
1254
+ collectHints: false,
1255
+ collectCallMetadata: true,
1256
+ collectStatistics: false,
1257
+ collectionLimits: CollectionLimitsConfig.from({
1258
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1259
+ })
1260
+ });
1261
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
623
1262
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
624
- const [processedTxs, failedTxs, returns] = await processor.process([
1263
+ const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([
625
1264
  tx
626
1265
  ]);
627
1266
  // REFACTOR: Consider returning the error rather than throwing
@@ -632,30 +1271,47 @@ import { NodeMetrics } from './node_metrics.js';
632
1271
  throw failedTxs[0].error;
633
1272
  }
634
1273
  const [processedTx] = processedTxs;
635
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.constants, processedTx.txEffect, returns, processedTx.gasUsed);
1274
+ return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed);
636
1275
  } finally{
637
- await fork.close();
1276
+ await merkleTreeFork.close();
638
1277
  }
639
1278
  }
640
1279
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
641
- const blockNumber = await this.blockSource.getBlockNumber() + 1;
642
1280
  const db = this.worldStateSynchronizer.getCommitted();
643
1281
  const verifier = isSimulation ? undefined : this.proofVerifier;
1282
+ // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1283
+ const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1284
+ const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
644
1285
  const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1286
+ timestamp: nextSlotTimestamp,
645
1287
  blockNumber,
646
1288
  l1ChainId: this.l1ChainId,
647
- setupAllowList: this.config.allowedInSetup ?? await getDefaultAllowedSetupFunctions(),
648
- gasFees: await this.getCurrentBaseFees(),
649
- skipFeeEnforcement
1289
+ rollupVersion: this.version,
1290
+ setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
1291
+ gasFees: await this.getCurrentMinFees(),
1292
+ skipFeeEnforcement,
1293
+ txsPermitted: !this.config.disableTransactions
650
1294
  });
651
1295
  return await validator.validateTx(tx);
652
1296
  }
1297
+ getConfig() {
1298
+ const schema = AztecNodeAdminConfigSchema;
1299
+ const keys = schema.keyof().options;
1300
+ return Promise.resolve(pick(this.config, ...keys));
1301
+ }
653
1302
  async setConfig(config) {
654
1303
  const newConfig = {
655
1304
  ...this.config,
656
1305
  ...config
657
1306
  };
658
- await this.sequencer?.updateSequencerConfig(config);
1307
+ this.sequencer?.updateConfig(config);
1308
+ this.slasherClient?.updateConfig(config);
1309
+ this.validatorsSentinel?.updateConfig(config);
1310
+ await this.p2pClient.updateP2PConfig(config);
1311
+ const archiver = this.blockSource;
1312
+ if ('updateConfig' in archiver) {
1313
+ archiver.updateConfig(config);
1314
+ }
659
1315
  if (newConfig.realProofs !== this.config.realProofs) {
660
1316
  this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
661
1317
  }
@@ -663,27 +1319,120 @@ import { NodeMetrics } from './node_metrics.js';
663
1319
  }
664
1320
  getProtocolContractAddresses() {
665
1321
  return Promise.resolve({
666
- classRegisterer: ProtocolContractAddress.ContractClassRegisterer,
1322
+ classRegistry: ProtocolContractAddress.ContractClassRegistry,
667
1323
  feeJuice: ProtocolContractAddress.FeeJuice,
668
- instanceDeployer: ProtocolContractAddress.ContractInstanceDeployer,
1324
+ instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
669
1325
  multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
670
1326
  });
671
1327
  }
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);
1328
+ registerContractFunctionSignatures(signatures) {
1329
+ return this.contractDataSource.registerContractFunctionSignatures(signatures);
676
1330
  }
677
- registerContractFunctionSignatures(_address, signatures) {
678
- return this.contractDataSource.registerContractFunctionSignatures(_address, signatures);
1331
+ getValidatorsStats() {
1332
+ return this.validatorsSentinel?.computeStats() ?? Promise.resolve({
1333
+ stats: {},
1334
+ slotWindow: 0
1335
+ });
679
1336
  }
680
- flushTxs() {
681
- if (!this.sequencer) {
682
- throw new Error(`Sequencer is not initialized`);
1337
+ getValidatorStats(validatorAddress, fromSlot, toSlot) {
1338
+ return this.validatorsSentinel?.getValidatorStats(validatorAddress, fromSlot, toSlot) ?? Promise.resolve(undefined);
1339
+ }
1340
+ async startSnapshotUpload(location) {
1341
+ // Note that we are forcefully casting the blocksource as an archiver
1342
+ // We break support for archiver running remotely to the node
1343
+ const archiver = this.blockSource;
1344
+ if (!('backupTo' in archiver)) {
1345
+ this.metrics.recordSnapshotError();
1346
+ throw new Error('Archiver implementation does not support backups. Cannot generate snapshot.');
1347
+ }
1348
+ // Test that the archiver has done an initial sync.
1349
+ if (!archiver.isInitialSyncComplete()) {
1350
+ this.metrics.recordSnapshotError();
1351
+ throw new Error(`Archiver initial sync not complete. Cannot start snapshot.`);
1352
+ }
1353
+ // And it has an L2 block hash
1354
+ const l2BlockHash = await archiver.getL2Tips().then((tips)=>tips.proposed.hash);
1355
+ if (!l2BlockHash) {
1356
+ this.metrics.recordSnapshotError();
1357
+ throw new Error(`Archiver has no latest L2 block hash downloaded. Cannot start snapshot.`);
683
1358
  }
684
- this.sequencer.flush();
1359
+ if (this.isUploadingSnapshot) {
1360
+ this.metrics.recordSnapshotError();
1361
+ throw new Error(`Snapshot upload already in progress. Cannot start another one until complete.`);
1362
+ }
1363
+ // Do not wait for the upload to be complete to return to the caller, but flag that an operation is in progress
1364
+ this.isUploadingSnapshot = true;
1365
+ const timer = new Timer();
1366
+ void uploadSnapshot(location, this.blockSource, this.worldStateSynchronizer, this.config, this.log).then(()=>{
1367
+ this.isUploadingSnapshot = false;
1368
+ this.metrics.recordSnapshot(timer.ms());
1369
+ }).catch((err)=>{
1370
+ this.isUploadingSnapshot = false;
1371
+ this.metrics.recordSnapshotError();
1372
+ this.log.error(`Error uploading snapshot: ${err}`);
1373
+ });
685
1374
  return Promise.resolve();
686
1375
  }
1376
+ async rollbackTo(targetBlock, force) {
1377
+ const archiver = this.blockSource;
1378
+ if (!('rollbackTo' in archiver)) {
1379
+ throw new Error('Archiver implementation does not support rollbacks.');
1380
+ }
1381
+ const finalizedBlock = await archiver.getL2Tips().then((tips)=>tips.finalized.block.number);
1382
+ if (targetBlock < finalizedBlock) {
1383
+ if (force) {
1384
+ this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`);
1385
+ await this.worldStateSynchronizer.clear();
1386
+ await this.p2pClient.clear();
1387
+ } else {
1388
+ throw new Error(`Cannot rollback to block ${targetBlock} as it is before finalized ${finalizedBlock}`);
1389
+ }
1390
+ }
1391
+ try {
1392
+ this.log.info(`Pausing archiver and world state sync to start rollback`);
1393
+ await archiver.stop();
1394
+ await this.worldStateSynchronizer.stopSync();
1395
+ const currentBlock = await archiver.getBlockNumber();
1396
+ const blocksToUnwind = currentBlock - targetBlock;
1397
+ this.log.info(`Unwinding ${count(blocksToUnwind, 'block')} from L2 block ${currentBlock} to ${targetBlock}`);
1398
+ await archiver.rollbackTo(targetBlock);
1399
+ this.log.info(`Unwinding complete.`);
1400
+ } catch (err) {
1401
+ this.log.error(`Error during rollback`, err);
1402
+ throw err;
1403
+ } finally{
1404
+ this.log.info(`Resuming world state and archiver sync.`);
1405
+ this.worldStateSynchronizer.resumeSync();
1406
+ archiver.resume();
1407
+ }
1408
+ }
1409
+ async pauseSync() {
1410
+ this.log.info(`Pausing archiver and world state sync`);
1411
+ await this.blockSource.stop();
1412
+ await this.worldStateSynchronizer.stopSync();
1413
+ }
1414
+ resumeSync() {
1415
+ this.log.info(`Resuming world state and archiver sync.`);
1416
+ this.worldStateSynchronizer.resumeSync();
1417
+ this.blockSource.resume();
1418
+ return Promise.resolve();
1419
+ }
1420
+ getSlashPayloads() {
1421
+ if (!this.slasherClient) {
1422
+ throw new Error(`Slasher client not enabled`);
1423
+ }
1424
+ return this.slasherClient.getSlashPayloads();
1425
+ }
1426
+ getSlashOffenses(round) {
1427
+ if (!this.slasherClient) {
1428
+ throw new Error(`Slasher client not enabled`);
1429
+ }
1430
+ if (round === 'all') {
1431
+ return this.slasherClient.getPendingOffenses();
1432
+ } else {
1433
+ return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1434
+ }
1435
+ }
687
1436
  /**
688
1437
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
689
1438
  * @param blockNumber - The block number at which to get the data.
@@ -692,7 +1441,7 @@ import { NodeMetrics } from './node_metrics.js';
692
1441
  if (typeof blockNumber === 'number' && blockNumber < INITIAL_L2_BLOCK_NUM - 1) {
693
1442
  throw new Error('Invalid block number to get world state for: ' + blockNumber);
694
1443
  }
695
- let blockSyncedTo = 0;
1444
+ let blockSyncedTo = BlockNumber.ZERO;
696
1445
  try {
697
1446
  // Attempt to sync the world state if necessary
698
1447
  blockSyncedTo = await this.#syncWorldState();
@@ -715,11 +1464,6 @@ import { NodeMetrics } from './node_metrics.js';
715
1464
  * @returns A promise that fulfils once the world state is synced
716
1465
  */ async #syncWorldState() {
717
1466
  const blockSourceHeight = await this.blockSource.getBlockNumber();
718
- return this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1467
+ return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
719
1468
  }
720
1469
  }
721
- _ts_decorate([
722
- trackSpan('AztecNodeService.simulatePublicCalls', async (tx)=>({
723
- [Attributes.TX_HASH]: (await tx.getTxHash()).toString()
724
- }))
725
- ], AztecNodeService.prototype, "simulatePublicCalls", null);