-
Notifications
You must be signed in to change notification settings - Fork 593
Expand file tree
/
Copy pathserver.ts
More file actions
1841 lines (1634 loc) · 70.2 KB
/
server.ts
File metadata and controls
1841 lines (1634 loc) · 70.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Archiver, createArchiver } from '@aztec/archiver';
import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
import { TestCircuitVerifier } from '@aztec/bb-prover/test';
import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
import { Blob } from '@aztec/blob-lib';
import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
import { createEthereumChain } from '@aztec/ethereum/chain';
import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
import { EthCheatCodes } from '@aztec/ethereum/test';
import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
import { Fr } from '@aztec/foundation/curves/bn254';
import { EthAddress } from '@aztec/foundation/eth-address';
import { BadRequestError } from '@aztec/foundation/json-rpc';
import { type Logger, createLogger } from '@aztec/foundation/log';
import { retryUntil } from '@aztec/foundation/retry';
import { count } from '@aztec/foundation/string';
import { DateProvider, Timer } from '@aztec/foundation/timer';
import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
import {
type P2P,
type P2PClientDeps,
createP2PClient,
createTxValidatorForAcceptingTxsOverRPC,
getDefaultAllowedSetupFunctions,
} from '@aztec/p2p';
import { ProtocolContractAddress } from '@aztec/protocol-contracts';
import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
import { createKeyStoreForProver } from '@aztec/prover-node/config';
import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
import { PublicProcessorFactory } from '@aztec/simulator/server';
import {
AttestationsBlockWatcher,
EpochPruneWatcher,
type SlasherClientInterface,
type Watcher,
createSlasher,
} from '@aztec/slasher';
import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
import { AztecAddress } from '@aztec/stdlib/aztec-address';
import {
type BlockData,
BlockHash,
type BlockParameter,
type DataInBlock,
L2Block,
type L2BlockSource,
} from '@aztec/stdlib/block';
import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
import type {
ContractClassPublic,
ContractDataSource,
ContractInstanceWithAddress,
NodeInfo,
ProtocolContractAddresses,
} from '@aztec/stdlib/contract';
import { getSlotAtTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
import { GasFees } from '@aztec/stdlib/gas';
import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
import {
type AztecNode,
type AztecNodeAdmin,
type AztecNodeAdminConfig,
AztecNodeAdminConfigSchema,
type AztecNodeDebug,
type GetContractClassLogsResponse,
type GetPublicLogsResponse,
} from '@aztec/stdlib/interfaces/client';
import {
type AllowedElement,
type ClientProtocolCircuitVerifier,
type L2LogsSource,
type Service,
type WorldStateSyncStatus,
type WorldStateSynchronizer,
tryStop,
} from '@aztec/stdlib/interfaces/server';
import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
import {
type BlockHeader,
type GlobalVariableBuilder as GlobalVariableBuilderInterface,
type IndexedTxEffect,
PublicSimulationOutput,
Tx,
type TxHash,
TxReceipt,
TxStatus,
type TxValidationResult,
} from '@aztec/stdlib/tx';
import { getPackageVersion } from '@aztec/stdlib/update-checker';
import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
import {
Attributes,
type TelemetryClient,
type Traceable,
type Tracer,
getTelemetryClient,
trackSpan,
} from '@aztec/telemetry-client';
import {
FullNodeCheckpointsBuilder as CheckpointsBuilder,
FullNodeCheckpointsBuilder,
NodeKeystoreAdapter,
ValidatorClient,
createProposalHandler,
createValidatorClient,
} from '@aztec/validator-client';
import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
import { createWorldStateSynchronizer } from '@aztec/world-state';
import { createPublicClient } from 'viem';
import { createSentinel } from '../sentinel/factory.js';
import { Sentinel } from '../sentinel/sentinel.js';
import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
import { NodeMetrics } from './node_metrics.js';
/**
* The aztec node.
*/
export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
private metrics: NodeMetrics;
private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
private ethCheatCodes: EthCheatCodes | undefined;
// Prevent two snapshot operations to happen simultaneously
private isUploadingSnapshot = false;
public readonly tracer: Tracer;
constructor(
protected config: AztecNodeConfig,
protected readonly p2pClient: P2P,
protected readonly blockSource: L2BlockSource & Partial<Service>,
protected readonly logsSource: L2LogsSource,
protected readonly contractDataSource: ContractDataSource,
protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
protected readonly worldStateSynchronizer: WorldStateSynchronizer,
protected readonly sequencer: SequencerClient | undefined,
protected readonly proverNode: ProverNode | undefined,
protected readonly slasherClient: SlasherClientInterface | undefined,
protected readonly validatorsSentinel: Sentinel | undefined,
protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
protected readonly l1ChainId: number,
protected readonly version: number,
protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
protected readonly epochCache: EpochCacheInterface,
protected readonly packageVersion: string,
private peerProofVerifier: ClientProtocolCircuitVerifier,
private rpcProofVerifier: ClientProtocolCircuitVerifier,
private dateProvider: DateProvider,
private telemetry: TelemetryClient = getTelemetryClient(),
private log = createLogger('node'),
private blobClient?: BlobClientInterface,
private validatorClient?: ValidatorClient,
private keyStoreManager?: KeystoreManager,
private debugLogStore: DebugLogStore = new NullDebugLogStore(),
) {
this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
this.tracer = telemetry.getTracer('AztecNodeService');
this.log.info(`Aztec Node version: ${this.packageVersion}`);
this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
// A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
// never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
// memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
if (debugLogStore.isEnabled && config.realProofs) {
throw new Error('debugLogStore should never be enabled when realProofs are set');
}
}
/** @internal Exposed for testing — returns the RPC proof verifier. */
public getProofVerifier(): ClientProtocolCircuitVerifier {
return this.rpcProofVerifier;
}
public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
const status = await this.worldStateSynchronizer.status();
return status.syncSummary;
}
public getL2Tips() {
return this.blockSource.getL2Tips();
}
/**
* initializes the Aztec Node, wait for component to sync.
* @param config - The configuration to be used by the aztec node.
* @returns - A fully synced Aztec Node for use in development/testing.
*/
public static async createAndSync(
inputConfig: AztecNodeConfig,
deps: {
telemetry?: TelemetryClient;
logger?: Logger;
publisher?: SequencerPublisher;
dateProvider?: DateProvider;
p2pClientDeps?: P2PClientDeps;
proverNodeDeps?: Partial<ProverNodeDeps>;
slashingProtectionDb?: SlashingProtectionDatabase;
} = {},
options: {
prefilledPublicData?: PublicDataTreeLeaf[];
dontStartSequencer?: boolean;
dontStartProverNode?: boolean;
} = {},
): Promise<AztecNodeService> {
const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
const log = deps.logger ?? createLogger('node');
const packageVersion = getPackageVersion() ?? '';
const telemetry = deps.telemetry ?? getTelemetryClient();
const dateProvider = deps.dateProvider ?? new DateProvider();
const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
// Build a key store from file if given or from environment otherwise.
// We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
let keyStoreManager: KeystoreManager | undefined;
const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
if (keyStoreProvided) {
const keyStores = loadKeystores(config.keyStoreDirectory!);
keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
} else {
const rawKeyStores: KeyStore[] = [];
const validatorKeyStore = createKeyStoreForValidator(config);
if (validatorKeyStore) {
rawKeyStores.push(validatorKeyStore);
}
if (config.enableProverNode) {
const proverKeyStore = createKeyStoreForProver(config);
if (proverKeyStore) {
rawKeyStores.push(proverKeyStore);
}
}
if (rawKeyStores.length > 0) {
keyStoreManager = new KeystoreManager(
rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
);
}
}
await keyStoreManager?.validateSigners();
// If we are a validator, verify our configuration before doing too much more.
if (!config.disableValidator) {
if (keyStoreManager === undefined) {
throw new Error('Failed to create key store, a requirement for running a validator');
}
if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
}
ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
}
// validate that the actual chain id matches that specified in configuration
if (config.l1ChainId !== ethereumChain.chainInfo.id) {
throw new Error(
`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`,
);
}
const publicClient = createPublicClient({
chain: ethereumChain.chainInfo,
transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
pollingInterval: config.viemPollingIntervalMS,
});
const l1ContractsAddresses = await RegistryContract.collectAddresses(
publicClient,
config.l1Contracts.registryAddress,
config.rollupVersion ?? 'canonical',
);
// Overwrite the passed in vars.
config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
rollupContract.getL1GenesisTime(),
rollupContract.getSlotDuration(),
rollupContract.getVersion(),
rollupContract.getManaLimit().then(Number),
] as const);
config.rollupVersion ??= Number(rollupVersionFromRollup);
if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
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}).`,
);
}
const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
// attempt snapshot sync if possible
await trySnapshotSync(config, log);
const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
const archiver = await createArchiver(
config,
{ blobClient, epochCache, telemetry, dateProvider },
{ blockUntilSync: !config.skipArchiverInitialSync },
);
// now create the merkle trees and the world state synchronizer
const worldStateSynchronizer = await createWorldStateSynchronizer(
config,
archiver,
options.prefilledPublicData,
telemetry,
);
const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
let peerProofVerifier: ClientProtocolCircuitVerifier;
let rpcProofVerifier: ClientProtocolCircuitVerifier;
if (useRealVerifiers) {
peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
const rpcVerifier = await BBCircuitVerifier.new(config);
rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
} else {
peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
}
let debugLogStore: DebugLogStore;
if (!config.realProofs) {
log.warn(`Aztec node is accepting fake proofs`);
debugLogStore = new InMemoryDebugLogStore();
log.info(
'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
);
} else {
debugLogStore = new NullDebugLogStore();
}
const proverOnly = config.enableProverNode && config.disableValidator;
if (proverOnly) {
log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
}
// create the tx pool and the p2p client, which will need the l2 block source
const p2pClient = await createP2PClient(
config,
archiver,
peerProofVerifier,
worldStateSynchronizer,
epochCache,
packageVersion,
dateProvider,
telemetry,
deps.p2pClientDeps,
);
// We'll accumulate sentinel watchers here
const watchers: Watcher[] = [];
// Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
// Override maxTxsPerCheckpoint with the validator-specific limit if set.
const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
{
...config,
l1GenesisTime,
slotDuration: Number(slotDuration),
rollupManaLimit,
maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
},
worldStateSynchronizer,
archiver,
dateProvider,
telemetry,
);
let validatorClient: ValidatorClient | undefined;
if (!proverOnly) {
// Create validator client if required
validatorClient = await createValidatorClient(config, {
checkpointsBuilder: validatorCheckpointsBuilder,
worldState: worldStateSynchronizer,
p2pClient,
telemetry,
dateProvider,
epochCache,
blockSource: archiver,
l1ToL2MessageSource: archiver,
keyStoreManager,
blobClient,
slashingProtectionDb: deps.slashingProtectionDb,
});
// If we have a validator client, register it as a source of offenses for the slasher,
// and have it register callbacks on the p2p client *before* we start it, otherwise messages
// like attestations or auths will fail.
if (validatorClient) {
watchers.push(validatorClient);
const vc = validatorClient;
const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
if (!options.dontStartSequencer) {
await validatorClient.registerHandlers();
}
}
}
// If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
// for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
// while non-reexecution is used for validating the proposals and collecting their txs.
// Checkpoint proposals rebuild blobs if the blob client can upload blobs.
if (!validatorClient) {
const reexecute = !!config.alwaysReexecuteBlockProposals;
log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
createProposalHandler(config, {
checkpointsBuilder: validatorCheckpointsBuilder,
worldState: worldStateSynchronizer,
epochCache,
blockSource: archiver,
l1ToL2MessageSource: archiver,
p2pClient,
blobClient,
dateProvider,
telemetry,
}).register(p2pClient, reexecute, archiver);
}
// Start world state and wait for it to sync to the archiver.
await worldStateSynchronizer.start();
// Start p2p. Note that it depends on world state to be running.
await p2pClient.start();
let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
let epochPruneWatcher: EpochPruneWatcher | undefined;
let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
if (!proverOnly) {
validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
watchers.push(validatorsSentinel);
}
if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
epochPruneWatcher = new EpochPruneWatcher(
archiver,
archiver,
epochCache,
p2pClient.getTxProvider(),
validatorCheckpointsBuilder,
config,
);
watchers.push(epochPruneWatcher);
}
// We assume we want to slash for invalid attestations unless all max penalties are set to 0
if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
watchers.push(attestationsBlockWatcher);
}
}
// Start p2p-related services once the archiver has completed sync
void archiver
.waitForInitialSync()
.then(async () => {
await p2pClient.start();
await validatorsSentinel?.start();
await epochPruneWatcher?.start();
await attestationsBlockWatcher?.start();
log.info(`All p2p services started`);
})
.catch(err => log.error('Failed to start p2p services after archiver sync', err));
const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, {
l1Contracts: config.l1Contracts,
ethereumSlotDuration: config.ethereumSlotDuration,
rollupVersion: BigInt(config.rollupVersion),
l1GenesisTime,
slotDuration: Number(slotDuration),
});
// Validator enabled, create/start relevant service
let sequencer: SequencerClient | undefined;
let slasherClient: SlasherClientInterface | undefined;
if (!config.disableValidator && validatorClient) {
// We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
// as they are executed when the node is selected as proposer.
const validatorAddresses = keyStoreManager
? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
: [];
slasherClient = await createSlasher(
config,
config.l1Contracts,
getPublicClient(config),
watchers,
dateProvider,
epochCache,
validatorAddresses,
undefined, // logger
);
await slasherClient.start();
const l1TxUtils = config.sequencerPublisherForwarderAddress
? await createForwarderL1TxUtilsFromSigners(
publicClient,
keyStoreManager!.createAllValidatorPublisherSigners(),
config.sequencerPublisherForwarderAddress,
{ ...config, scope: 'sequencer' },
{ telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
)
: await createL1TxUtilsFromSigners(
publicClient,
keyStoreManager!.createAllValidatorPublisherSigners(),
{ ...config, scope: 'sequencer' },
{ telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
);
// Create a funder L1TxUtils from the keystore funding account (if configured)
const fundingSigner = keyStoreManager?.createFundingSigner();
let funderL1TxUtils: L1TxUtils | undefined;
if (fundingSigner) {
const [funder] = await createL1TxUtilsFromSigners(
publicClient,
[fundingSigner],
{ ...config, scope: 'sequencer' },
{ telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
);
funderL1TxUtils = funder;
}
// Create and start the sequencer client
const checkpointsBuilder = new CheckpointsBuilder(
{ ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
worldStateSynchronizer,
archiver,
dateProvider,
telemetry,
debugLogStore,
);
sequencer = await SequencerClient.new(config, {
...deps,
epochCache,
l1TxUtils,
funderL1TxUtils,
validatorClient,
p2pClient,
worldStateSynchronizer,
slasherClient,
checkpointsBuilder,
l2BlockSource: archiver,
l1ToL2MessageSource: archiver,
telemetry,
dateProvider,
blobClient,
nodeKeyStore: keyStoreManager!,
globalVariableBuilder,
});
}
if (!options.dontStartSequencer && sequencer) {
await sequencer.start();
log.verbose(`Sequencer started`);
} else if (sequencer) {
log.warn(`Sequencer created but not started`);
}
// Create prover node subsystem if enabled
let proverNode: ProverNode | undefined;
if (config.enableProverNode) {
proverNode = await createProverNode(config, {
...deps.proverNodeDeps,
telemetry,
dateProvider,
archiver,
worldStateSynchronizer,
p2pClient,
epochCache,
blobClient,
keyStoreManager,
});
if (!options.dontStartProverNode) {
await proverNode.start();
log.info(`Prover node subsystem started`);
} else {
log.info(`Prover node subsystem created but not started`);
}
}
const node = new AztecNodeService(
config,
p2pClient,
archiver,
archiver,
archiver,
archiver,
worldStateSynchronizer,
sequencer,
proverNode,
slasherClient,
validatorsSentinel,
epochPruneWatcher,
ethereumChain.chainInfo.id,
config.rollupVersion,
globalVariableBuilder,
epochCache,
packageVersion,
peerProofVerifier,
rpcProofVerifier,
dateProvider,
telemetry,
log,
blobClient,
validatorClient,
keyStoreManager,
debugLogStore,
);
return node;
}
/**
* Returns the sequencer client instance.
* @returns The sequencer client instance.
*/
public getSequencer(): SequencerClient | undefined {
return this.sequencer;
}
/** Returns the prover node subsystem, if enabled. */
public getProverNode(): ProverNode | undefined {
return this.proverNode;
}
public getBlockSource(): L2BlockSource {
return this.blockSource;
}
public getContractDataSource(): ContractDataSource {
return this.contractDataSource;
}
public getP2P(): P2P {
return this.p2pClient;
}
/**
* Method to return the currently deployed L1 contract addresses.
* @returns - The currently deployed L1 contract addresses.
*/
public getL1ContractAddresses(): Promise<L1ContractAddresses> {
return Promise.resolve(this.config.l1Contracts);
}
public getEncodedEnr(): Promise<string | undefined> {
return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
}
public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
}
/**
* Method to determine if the node is ready to accept transactions.
* @returns - Flag indicating the readiness for tx submission.
*/
public isReady() {
return Promise.resolve(this.p2pClient.isReady() ?? false);
}
public async getNodeInfo(): Promise<NodeInfo> {
const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
this.getNodeVersion(),
this.getVersion(),
this.getChainId(),
this.getEncodedEnr(),
this.getL1ContractAddresses(),
this.getProtocolContractAddresses(),
]);
const nodeInfo: NodeInfo = {
nodeVersion,
l1ChainId: chainId,
rollupVersion,
enr,
l1ContractAddresses: contractAddresses,
protocolContractAddresses: protocolContractAddresses,
realProofs: !!this.config.realProofs,
};
return nodeInfo;
}
/**
* Get a block specified by its block number, block hash, or 'latest'.
* @param block - The block parameter (block number, block hash, or 'latest').
* @returns The requested block.
*/
public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
if (BlockHash.isBlockHash(block)) {
return this.getBlockByHash(block);
}
const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
if (blockNumber === BlockNumber.ZERO) {
return this.buildInitialBlock();
}
return await this.blockSource.getL2Block(blockNumber);
}
/**
* Get a block specified by its hash.
* @param blockHash - The block hash being requested.
* @returns The requested block.
*/
public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
const initialBlockHash = await this.#getInitialHeaderHash();
if (blockHash.equals(initialBlockHash)) {
return this.buildInitialBlock();
}
return await this.blockSource.getL2BlockByHash(blockHash);
}
private buildInitialBlock(): L2Block {
const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
return L2Block.empty(initialHeader);
}
/**
* Get a block specified by its archive root.
* @param archive - The archive root being requested.
* @returns The requested block.
*/
public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
return await this.blockSource.getL2BlockByArchive(archive);
}
/**
* Method to request blocks. Will attempt to return all requested blocks but will return only those available.
* @param from - The start of the range of blocks to return.
* @param limit - The maximum number of blocks to obtain.
* @returns The blocks requested.
*/
public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
}
public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
}
public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
}
public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
}
/**
* Method to fetch the current min L2 fees.
* @returns The current min L2 fees.
*/
public async getCurrentMinFees(): Promise<GasFees> {
return await this.globalVariableBuilder.getCurrentMinFees();
}
public async getMaxPriorityFees(): Promise<GasFees> {
for await (const tx of this.p2pClient.iteratePendingTxs()) {
return tx.getGasSettings().maxPriorityFeesPerGas;
}
return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
}
/**
* Method to fetch the latest block number synchronized by the node.
* @returns The block number.
*/
public async getBlockNumber(): Promise<BlockNumber> {
return await this.blockSource.getBlockNumber();
}
public async getProvenBlockNumber(): Promise<BlockNumber> {
return await this.blockSource.getProvenBlockNumber();
}
public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
return await this.blockSource.getCheckpointedL2BlockNumber();
}
public getCheckpointNumber(): Promise<CheckpointNumber> {
return this.blockSource.getCheckpointNumber();
}
/**
* Method to fetch the version of the package.
* @returns The node package version
*/
public getNodeVersion(): Promise<string> {
return Promise.resolve(this.packageVersion);
}
/**
* Method to fetch the version of the rollup the node is connected to.
* @returns The rollup version.
*/
public getVersion(): Promise<number> {
return Promise.resolve(this.version);
}
/**
* Method to fetch the chain id of the base-layer for the rollup.
* @returns The chain id.
*/
public getChainId(): Promise<number> {
return Promise.resolve(this.l1ChainId);
}
public getContractClass(id: Fr): Promise<ContractClassPublic | undefined> {
return this.contractDataSource.getContractClass(id);
}
public getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
return this.contractDataSource.getContract(address);
}
public async getPrivateLogsByTags(
tags: SiloedTag[],
page?: number,
referenceBlock?: BlockHash,
): Promise<TxScopedL2Log[][]> {
let upToBlockNumber: BlockNumber | undefined;
if (referenceBlock) {
const initialBlockHash = await this.#getInitialHeaderHash();
if (referenceBlock.equals(initialBlockHash)) {
upToBlockNumber = BlockNumber(0);
} else {
const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
if (!header) {
throw new Error(
`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
);
}
upToBlockNumber = header.globalVariables.blockNumber;
}
}
return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
}
public async getPublicLogsByTagsFromContract(
contractAddress: AztecAddress,
tags: Tag[],
page?: number,
referenceBlock?: BlockHash,
): Promise<TxScopedL2Log[][]> {
let upToBlockNumber: BlockNumber | undefined;
if (referenceBlock) {
const initialBlockHash = await this.#getInitialHeaderHash();
if (referenceBlock.equals(initialBlockHash)) {
upToBlockNumber = BlockNumber(0);
} else {
const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
if (!header) {
throw new Error(
`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
);
}
upToBlockNumber = header.globalVariables.blockNumber;
}
}
return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
}
/**
* Gets public logs based on the provided filter.
* @param filter - The filter to apply to the logs.
* @returns The requested logs.
*/
getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
return this.logsSource.getPublicLogs(filter);
}
/**
* Gets contract class logs based on the provided filter.
* @param filter - The filter to apply to the logs.
* @returns The requested logs.
*/
getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
return this.logsSource.getContractClassLogs(filter);
}
/**
* Method to submit a transaction to the p2p pool.
* @param tx - The transaction to be submitted.
*/
public async sendTx(tx: Tx) {
await this.#sendTx(tx);
}
async #sendTx(tx: Tx) {
const timer = new Timer();
const txHash = tx.getTxHash().toString();
const valid = await this.isValidTx(tx);
if (valid.result !== 'valid') {
const reason = valid.reason.join(', ');
this.metrics.receivedTx(timer.ms(), false);
this.log.warn(`Received invalid tx ${txHash}: ${reason}`, { txHash });
throw new Error(`Invalid tx: ${reason}`);
}
await this.p2pClient!.sendTx(tx);
const duration = timer.ms();
this.metrics.receivedTx(duration, true);
this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
}
public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
// Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
// as a fallback if we don't find a settled receipt in the archiver.
const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
// Then get the actual tx from the archiver, which tracks every tx in a mined block.
const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
let receipt: TxReceipt;
if (settledTxReceipt) {
receipt = settledTxReceipt;
} else if (isKnownToPool) {
// If the tx is in the pool but not in the archiver, it's pending.
// This handles race conditions between archiver and p2p, where the archiver
// has pruned the block in which a tx was mined, but p2p has not caught up yet.
receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
} else {
// Otherwise, if we don't know the tx, we consider it dropped.
receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
}
this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
return receipt;
}
public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
return this.blockSource.getTxEffect(txHash);
}
/**
* Method to stop the aztec node.
*/
public async stop() {
this.log.info(`Stopping Aztec Node`);
await tryStop(this.validatorsSentinel);
await tryStop(this.epochPruneWatcher);
await tryStop(this.slasherClient);
await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
await tryStop(this.sequencer);
await tryStop(this.proverNode);
await tryStop(this.p2pClient);
await tryStop(this.worldStateSynchronizer);
await tryStop(this.blockSource);
await tryStop(this.blobClient);
await tryStop(this.telemetry);
this.log.info(`Stopped Aztec Node`);
}
/**
* Returns the blob client used by this node.
* @internal - Exposed for testing purposes only.
*/
public getBlobClient(): BlobClientInterface | undefined {
return this.blobClient;
}
/**
* Method to retrieve pending txs.
* @param limit - The number of items to returns
* @param after - The last known pending tx. Used for pagination
* @returns - The pending txs.
*/
public getPendingTxs(limit?: number, after?: TxHash): Promise<Tx[]> {
return this.p2pClient!.getPendingTxs(limit, after);
}