@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.023c3e5

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 (78) hide show
  1. package/README.md +282 -0
  2. package/dest/block_proposal_handler.d.ts +63 -0
  3. package/dest/block_proposal_handler.d.ts.map +1 -0
  4. package/dest/block_proposal_handler.js +546 -0
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +173 -0
  8. package/dest/config.d.ts +3 -14
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +41 -8
  11. package/dest/duties/validation_service.d.ts +50 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +123 -17
  14. package/dest/factory.d.ts +28 -6
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +13 -6
  17. package/dest/index.d.ts +6 -2
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +5 -1
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +4 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +3 -0
  26. package/dest/key_store/interface.d.ts +85 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/interface.js +3 -3
  29. package/dest/key_store/local_key_store.d.ts +46 -11
  30. package/dest/key_store/local_key_store.d.ts.map +1 -1
  31. package/dest/key_store/local_key_store.js +68 -17
  32. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  33. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  34. package/dest/key_store/node_keystore_adapter.js +330 -0
  35. package/dest/key_store/web3signer_key_store.d.ts +66 -0
  36. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  37. package/dest/key_store/web3signer_key_store.js +156 -0
  38. package/dest/metrics.d.ts +13 -5
  39. package/dest/metrics.d.ts.map +1 -1
  40. package/dest/metrics.js +63 -22
  41. package/dest/tx_validator/index.d.ts +3 -0
  42. package/dest/tx_validator/index.d.ts.map +1 -0
  43. package/dest/tx_validator/index.js +2 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  45. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  46. package/dest/tx_validator/nullifier_cache.js +24 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  48. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  49. package/dest/tx_validator/tx_validator_factory.js +54 -0
  50. package/dest/validator.d.ts +73 -58
  51. package/dest/validator.d.ts.map +1 -1
  52. package/dest/validator.js +559 -166
  53. package/package.json +37 -21
  54. package/src/block_proposal_handler.ts +555 -0
  55. package/src/checkpoint_builder.ts +314 -0
  56. package/src/config.ts +52 -22
  57. package/src/duties/validation_service.ts +193 -19
  58. package/src/factory.ts +65 -11
  59. package/src/index.ts +5 -1
  60. package/src/key_store/ha_key_store.ts +269 -0
  61. package/src/key_store/index.ts +3 -0
  62. package/src/key_store/interface.ts +100 -5
  63. package/src/key_store/local_key_store.ts +77 -18
  64. package/src/key_store/node_keystore_adapter.ts +398 -0
  65. package/src/key_store/web3signer_key_store.ts +205 -0
  66. package/src/metrics.ts +86 -23
  67. package/src/tx_validator/index.ts +2 -0
  68. package/src/tx_validator/nullifier_cache.ts +30 -0
  69. package/src/tx_validator/tx_validator_factory.ts +154 -0
  70. package/src/validator.ts +757 -221
  71. package/dest/errors/index.d.ts +0 -2
  72. package/dest/errors/index.d.ts.map +0 -1
  73. package/dest/errors/index.js +0 -1
  74. package/dest/errors/validator.error.d.ts +0 -29
  75. package/dest/errors/validator.error.d.ts.map +0 -1
  76. package/dest/errors/validator.error.js +0 -45
  77. package/src/errors/index.ts +0 -1
  78. package/src/errors/validator.error.ts +0 -55
package/src/validator.ts CHANGED
@@ -1,337 +1,856 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
+ import { type Blob, getBlobsPerL1Block } from '@aztec/blob-lib';
1
3
  import type { EpochCache } from '@aztec/epoch-cache';
2
- import { Buffer32 } from '@aztec/foundation/buffer';
3
- import type { Fr } from '@aztec/foundation/fields';
4
- import { createLogger } from '@aztec/foundation/log';
4
+ import {
5
+ BlockNumber,
6
+ CheckpointNumber,
7
+ EpochNumber,
8
+ IndexWithinCheckpoint,
9
+ SlotNumber,
10
+ } from '@aztec/foundation/branded-types';
11
+ import { Fr } from '@aztec/foundation/curves/bn254';
12
+ import { TimeoutError } from '@aztec/foundation/error';
13
+ import type { EthAddress } from '@aztec/foundation/eth-address';
14
+ import type { Signature } from '@aztec/foundation/eth-signature';
15
+ import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
16
+ import { retryUntil } from '@aztec/foundation/retry';
5
17
  import { RunningPromise } from '@aztec/foundation/running-promise';
6
18
  import { sleep } from '@aztec/foundation/sleep';
7
- import { DateProvider, type Timer } from '@aztec/foundation/timer';
8
- import type { P2P } from '@aztec/p2p';
9
- import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
10
- import type { L2Block } from '@aztec/stdlib/block';
11
- import type { BlockAttestation, BlockProposal } from '@aztec/stdlib/p2p';
12
- import type { BlockHeader, GlobalVariables, Tx, TxHash } from '@aztec/stdlib/tx';
13
- import { type TelemetryClient, WithTracer, getTelemetryClient } from '@aztec/telemetry-client';
14
-
15
- import type { ValidatorClientConfig } from './config.js';
19
+ import { DateProvider } from '@aztec/foundation/timer';
20
+ import type { KeystoreManager } from '@aztec/node-keystore';
21
+ import type { P2P, PeerId } from '@aztec/p2p';
22
+ import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
23
+ import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
24
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
25
+ import type { CommitteeAttestationsAndSigners, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
26
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
27
+ import type {
28
+ CreateCheckpointProposalLastBlockData,
29
+ ITxProvider,
30
+ Validator,
31
+ ValidatorClientFullConfig,
32
+ WorldStateSynchronizer,
33
+ } from '@aztec/stdlib/interfaces/server';
34
+ import { type L1ToL2MessageSource, accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
35
+ import type {
36
+ BlockProposal,
37
+ BlockProposalOptions,
38
+ CheckpointAttestation,
39
+ CheckpointProposalCore,
40
+ CheckpointProposalOptions,
41
+ } from '@aztec/stdlib/p2p';
42
+ import { CheckpointProposal } from '@aztec/stdlib/p2p';
43
+ import type { CheckpointHeader } from '@aztec/stdlib/rollup';
44
+ import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
45
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
46
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
47
+ import { createHASigner } from '@aztec/validator-ha-signer/factory';
48
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
49
+
50
+ import { EventEmitter } from 'events';
51
+ import type { TypedDataDefinition } from 'viem';
52
+
53
+ import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
54
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
16
55
  import { ValidationService } from './duties/validation_service.js';
17
- import {
18
- AttestationTimeoutError,
19
- BlockBuilderNotProvidedError,
20
- InvalidValidatorPrivateKeyError,
21
- ReExFailedTxsError,
22
- ReExStateMismatchError,
23
- ReExTimeoutError,
24
- TransactionsNotAvailableError,
25
- } from './errors/validator.error.js';
26
- import type { ValidatorKeyStore } from './key_store/interface.js';
27
- import { LocalKeyStore } from './key_store/local_key_store.js';
56
+ import { HAKeyStore } from './key_store/ha_key_store.js';
57
+ import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
58
+ import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
28
59
  import { ValidatorMetrics } from './metrics.js';
29
60
 
30
- /**
31
- * Callback function for building a block
32
- *
33
- * We reuse the sequencer's block building functionality for re-execution
34
- */
35
- type BlockBuilderCallback = (
36
- txs: Iterable<Tx> | AsyncIterableIterator<Tx>,
37
- globalVariables: GlobalVariables,
38
- opts?: { validateOnly?: boolean },
39
- ) => Promise<{
40
- block: L2Block;
41
- publicProcessorDuration: number;
42
- numTxs: number;
43
- numFailedTxs: number;
44
- blockBuildingTimer: Timer;
45
- }>;
46
-
47
- export interface Validator {
48
- start(): Promise<void>;
49
- registerBlockProposalHandler(): void;
50
- registerBlockBuilder(blockBuilder: BlockBuilderCallback): void;
51
-
52
- // Block validation responsibilities
53
- createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal | undefined>;
54
- attestToProposal(proposal: BlockProposal): void;
55
-
56
- broadcastBlockProposal(proposal: BlockProposal): void;
57
- collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]>;
58
- }
61
+ // We maintain a set of proposers who have proposed invalid blocks.
62
+ // Just cap the set to avoid unbounded growth.
63
+ const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
64
+
65
+ // What errors from the block proposal handler result in slashing
66
+ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT: BlockProposalValidationFailureReason[] = [
67
+ 'state_mismatch',
68
+ 'failed_txs',
69
+ ];
59
70
 
60
71
  /**
61
72
  * Validator Client
62
73
  */
63
- export class ValidatorClient extends WithTracer implements Validator {
74
+ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter) implements Validator, Watcher {
75
+ public readonly tracer: Tracer;
64
76
  private validationService: ValidationService;
65
77
  private metrics: ValidatorMetrics;
78
+ private log: Logger;
79
+
80
+ // Whether it has already registered handlers on the p2p client
81
+ private hasRegisteredHandlers = false;
66
82
 
67
83
  // Used to check if we are sending the same proposal twice
68
84
  private previousProposal?: BlockProposal;
69
85
 
70
- // Callback registered to: sequencer.buildBlock
71
- private blockBuilder?: BlockBuilderCallback = undefined;
72
-
86
+ private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
73
87
  private epochCacheUpdateLoop: RunningPromise;
74
88
 
75
- private blockProposalValidator: BlockProposalValidator;
89
+ private proposersOfInvalidBlocks: Set<string> = new Set();
76
90
 
77
- constructor(
78
- private keyStore: ValidatorKeyStore,
91
+ protected constructor(
92
+ private keyStore: ExtendedValidatorKeyStore,
79
93
  private epochCache: EpochCache,
80
94
  private p2pClient: P2P,
81
- private config: ValidatorClientConfig,
95
+ private blockProposalHandler: BlockProposalHandler,
96
+ private blockSource: L2BlockSource,
97
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
98
+ private worldState: WorldStateSynchronizer,
99
+ private l1ToL2MessageSource: L1ToL2MessageSource,
100
+ private config: ValidatorClientFullConfig,
101
+ private blobClient: BlobClientInterface,
82
102
  private dateProvider: DateProvider = new DateProvider(),
83
103
  telemetry: TelemetryClient = getTelemetryClient(),
84
- private log = createLogger('validator'),
104
+ log = createLogger('validator'),
85
105
  ) {
86
- // Instantiate tracer
87
- super(telemetry, 'Validator');
106
+ super();
107
+
108
+ // Create child logger with fisherman prefix if in fisherman mode
109
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
110
+
111
+ this.tracer = telemetry.getTracer('Validator');
88
112
  this.metrics = new ValidatorMetrics(telemetry);
89
113
 
90
- this.validationService = new ValidationService(keyStore);
114
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
91
115
 
92
- this.blockProposalValidator = new BlockProposalValidator(epochCache);
116
+ // Refresh epoch cache every second to trigger alert if participation in committee changes
117
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
93
118
 
94
- // Refresh epoch cache every second to trigger commiteeChanged event
95
- this.epochCacheUpdateLoop = new RunningPromise(
96
- () =>
97
- this.epochCache
98
- .getCommittee()
99
- .then(() => {})
100
- .catch(err => log.error('Error updating validator committee', err)),
101
- log,
102
- 1000,
103
- );
119
+ const myAddresses = this.getValidatorAddresses();
120
+ this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
121
+ }
104
122
 
105
- // Listen to commiteeChanged event to alert operator when their validator has entered the committee
106
- this.epochCache.on('committeeChanged', (newCommittee, epochNumber) => {
107
- const me = this.keyStore.getAddress();
108
- if (newCommittee.some(addr => addr.equals(me))) {
109
- this.log.info(`Validator ${me.toString()} is on the validator committee for epoch ${epochNumber}`);
110
- } else {
111
- this.log.verbose(`Validator ${me.toString()} not on the validator committee for epoch ${epochNumber}`);
123
+ public static validateKeyStoreConfiguration(keyStoreManager: KeystoreManager, logger?: Logger) {
124
+ const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
125
+ const validatorAddresses = validatorKeyStore.getAddresses();
126
+ // Verify that we can retrieve all required data from the key store
127
+ for (const address of validatorAddresses) {
128
+ // Functions throw if required data is not available
129
+ let coinbase: EthAddress;
130
+ let feeRecipient: AztecAddress;
131
+ try {
132
+ coinbase = validatorKeyStore.getCoinbaseAddress(address);
133
+ feeRecipient = validatorKeyStore.getFeeRecipient(address);
134
+ } catch (error) {
135
+ throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
112
136
  }
113
- });
114
137
 
115
- this.log.verbose(`Initialized validator with address ${this.keyStore.getAddress().toString()}`);
138
+ const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
139
+ if (!publisherAddresses.length) {
140
+ throw new Error(`No publisher addresses found for validator address ${address}`);
141
+ }
142
+ logger?.debug(
143
+ `Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map(x => x.toString()).join()}`,
144
+ );
145
+ }
146
+ }
147
+
148
+ private async handleEpochCommitteeUpdate() {
149
+ try {
150
+ const { committee, epoch } = await this.epochCache.getCommittee('next');
151
+ if (!committee) {
152
+ this.log.trace(`No committee found for slot`);
153
+ return;
154
+ }
155
+ if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
156
+ const me = this.getValidatorAddresses();
157
+ const committeeSet = new Set(committee.map(v => v.toString()));
158
+ const inCommittee = me.filter(a => committeeSet.has(a.toString()));
159
+ if (inCommittee.length > 0) {
160
+ this.log.info(
161
+ `Validators ${inCommittee.map(a => a.toString()).join(',')} are on the validator committee for epoch ${epoch}`,
162
+ );
163
+ } else {
164
+ this.log.verbose(
165
+ `Validators ${me.map(a => a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`,
166
+ );
167
+ }
168
+ this.lastEpochForCommitteeUpdateLoop = epoch;
169
+ }
170
+ } catch (err) {
171
+ this.log.error(`Error updating epoch committee`, err);
172
+ }
116
173
  }
117
174
 
118
- static new(
119
- config: ValidatorClientConfig,
175
+ static async new(
176
+ config: ValidatorClientFullConfig,
177
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
178
+ worldState: WorldStateSynchronizer,
120
179
  epochCache: EpochCache,
121
180
  p2pClient: P2P,
181
+ blockSource: L2BlockSource & L2BlockSink,
182
+ l1ToL2MessageSource: L1ToL2MessageSource,
183
+ txProvider: ITxProvider,
184
+ keyStoreManager: KeystoreManager,
185
+ blobClient: BlobClientInterface,
122
186
  dateProvider: DateProvider = new DateProvider(),
123
187
  telemetry: TelemetryClient = getTelemetryClient(),
124
188
  ) {
125
- if (!config.validatorPrivateKey) {
126
- throw new InvalidValidatorPrivateKeyError();
189
+ const metrics = new ValidatorMetrics(telemetry);
190
+ const blockProposalValidator = new BlockProposalValidator(epochCache, {
191
+ txsPermitted: !config.disableTransactions,
192
+ });
193
+ const blockProposalHandler = new BlockProposalHandler(
194
+ checkpointsBuilder,
195
+ worldState,
196
+ blockSource,
197
+ l1ToL2MessageSource,
198
+ txProvider,
199
+ blockProposalValidator,
200
+ epochCache,
201
+ config,
202
+ metrics,
203
+ dateProvider,
204
+ telemetry,
205
+ );
206
+
207
+ let validatorKeyStore: ExtendedValidatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
208
+ if (config.haSigningEnabled) {
209
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
210
+ const haConfig = {
211
+ ...config,
212
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
213
+ };
214
+ const { signer } = await createHASigner(haConfig);
215
+ validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
127
216
  }
128
217
 
129
- const privateKey = validatePrivateKey(config.validatorPrivateKey);
130
- const localKeyStore = new LocalKeyStore(privateKey);
218
+ const validator = new ValidatorClient(
219
+ validatorKeyStore,
220
+ epochCache,
221
+ p2pClient,
222
+ blockProposalHandler,
223
+ blockSource,
224
+ checkpointsBuilder,
225
+ worldState,
226
+ l1ToL2MessageSource,
227
+ config,
228
+ blobClient,
229
+ dateProvider,
230
+ telemetry,
231
+ );
131
232
 
132
- const validator = new ValidatorClient(localKeyStore, epochCache, p2pClient, config, dateProvider, telemetry);
133
- validator.registerBlockProposalHandler();
134
233
  return validator;
135
234
  }
136
235
 
236
+ public getValidatorAddresses() {
237
+ return this.keyStore
238
+ .getAddresses()
239
+ .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
240
+ }
241
+
242
+ public getBlockProposalHandler() {
243
+ return this.blockProposalHandler;
244
+ }
245
+
246
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
247
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
248
+ }
249
+
250
+ public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
251
+ return this.keyStore.getCoinbaseAddress(attestor);
252
+ }
253
+
254
+ public getFeeRecipientForAttestor(attestor: EthAddress): AztecAddress {
255
+ return this.keyStore.getFeeRecipient(attestor);
256
+ }
257
+
258
+ public getConfig(): ValidatorClientFullConfig {
259
+ return this.config;
260
+ }
261
+
262
+ public updateConfig(config: Partial<ValidatorClientFullConfig>) {
263
+ this.config = { ...this.config, ...config };
264
+ }
265
+
137
266
  public async start() {
138
- // Sync the committee from the smart contract
139
- // https://github.com/AztecProtocol/aztec-packages/issues/7962
267
+ if (this.epochCacheUpdateLoop.isRunning()) {
268
+ this.log.warn(`Validator client already started`);
269
+ return;
270
+ }
140
271
 
141
- const me = this.keyStore.getAddress();
142
- const inCommittee = await this.epochCache.isInCommittee(me);
143
- if (inCommittee) {
144
- this.log.info(`Started validator with address ${me.toString()} in current validator committee`);
145
- } else {
146
- this.log.info(`Started validator with address ${me.toString()}`);
272
+ await this.keyStore.start();
273
+
274
+ await this.registerHandlers();
275
+
276
+ const myAddresses = this.getValidatorAddresses();
277
+ const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
278
+ this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
279
+ if (inCommittee.length > 0) {
280
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
147
281
  }
148
282
  this.epochCacheUpdateLoop.start();
283
+
149
284
  return Promise.resolve();
150
285
  }
151
286
 
152
287
  public async stop() {
153
288
  await this.epochCacheUpdateLoop.stop();
289
+ await this.keyStore.stop();
154
290
  }
155
291
 
156
- public registerBlockProposalHandler() {
157
- const handler = (block: BlockProposal): Promise<BlockAttestation | undefined> => {
158
- return this.attestToProposal(block);
159
- };
160
- this.p2pClient.registerBlockProposalHandler(handler);
292
+ /** Register handlers on the p2p client */
293
+ public async registerHandlers() {
294
+ if (!this.hasRegisteredHandlers) {
295
+ this.hasRegisteredHandlers = true;
296
+ this.log.debug(`Registering validator handlers for p2p client`);
297
+
298
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
299
+ const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
300
+ this.validateBlockProposal(block, proposalSender);
301
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
302
+
303
+ // Checkpoint proposal handler - validates and creates attestations
304
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
305
+ // and processed separately via the block handler above.
306
+ const checkpointHandler = (
307
+ checkpoint: CheckpointProposalCore,
308
+ proposalSender: PeerId,
309
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
310
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
311
+
312
+ const myAddresses = this.getValidatorAddresses();
313
+ this.p2pClient.registerThisValidatorAddresses(myAddresses);
314
+
315
+ await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
316
+ }
161
317
  }
162
318
 
163
319
  /**
164
- * Register a callback function for building a block
165
- *
166
- * We reuse the sequencer's block building functionality for re-execution
320
+ * Validate a block proposal from a peer.
321
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
322
+ * @returns true if the proposal is valid, false otherwise
167
323
  */
168
- public registerBlockBuilder(blockBuilder: BlockBuilderCallback) {
169
- this.blockBuilder = blockBuilder;
324
+ async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
325
+ const slotNumber = proposal.slotNumber;
326
+
327
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
328
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
329
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
330
+
331
+ const proposer = proposal.getSender();
332
+
333
+ // Reject proposals with invalid signatures
334
+ if (!proposer) {
335
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
336
+ return false;
337
+ }
338
+
339
+ // Check if we're in the committee (for metrics purposes)
340
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
341
+ const partOfCommittee = inCommittee.length > 0;
342
+
343
+ const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
344
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
345
+ ...proposalInfo,
346
+ txHashes: proposal.txHashes.map(t => t.toString()),
347
+ fishermanMode: this.config.fishermanMode || false,
348
+ });
349
+
350
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
351
+ // In fisherman mode, we always reexecute to validate proposals.
352
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
353
+ this.config;
354
+ const shouldReexecute =
355
+ fishermanMode ||
356
+ (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
357
+ (partOfCommittee && validatorReexecute) ||
358
+ alwaysReexecuteBlockProposals ||
359
+ this.blobClient.canUpload();
360
+
361
+ const validationResult = await this.blockProposalHandler.handleBlockProposal(
362
+ proposal,
363
+ proposalSender,
364
+ !!shouldReexecute && !escapeHatchOpen,
365
+ );
366
+
367
+ if (!validationResult.isValid) {
368
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
369
+
370
+ const reason = validationResult.reason || 'unknown';
371
+ // Classify failure reason: bad proposal vs node issue
372
+ const badProposalReasons: BlockProposalValidationFailureReason[] = [
373
+ 'invalid_proposal',
374
+ 'state_mismatch',
375
+ 'failed_txs',
376
+ 'in_hash_mismatch',
377
+ 'parent_block_wrong_slot',
378
+ ];
379
+
380
+ if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
381
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
382
+ } else {
383
+ // Node issues so we can't validate
384
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
385
+ }
386
+
387
+ // Slash invalid block proposals (can happen even when not in committee)
388
+ if (
389
+ !escapeHatchOpen &&
390
+ validationResult.reason &&
391
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
392
+ slashBroadcastedInvalidBlockPenalty > 0n
393
+ ) {
394
+ this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
395
+ this.slashInvalidBlock(proposal);
396
+ }
397
+ return false;
398
+ }
399
+
400
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
401
+ ...proposalInfo,
402
+ inCommittee: partOfCommittee,
403
+ fishermanMode: this.config.fishermanMode || false,
404
+ escapeHatchOpen,
405
+ });
406
+
407
+ if (escapeHatchOpen) {
408
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
409
+ return false;
410
+ }
411
+
412
+ return true;
170
413
  }
171
414
 
172
- async attestToProposal(proposal: BlockProposal): Promise<BlockAttestation | undefined> {
173
- const slotNumber = proposal.slotNumber.toNumber();
415
+ /**
416
+ * Validate and attest to a checkpoint proposal from a peer.
417
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
418
+ * the lastBlock is extracted and processed separately via the block handler.
419
+ * @returns Checkpoint attestations if valid, undefined otherwise
420
+ */
421
+ async attestToCheckpointProposal(
422
+ proposal: CheckpointProposalCore,
423
+ _proposalSender: PeerId,
424
+ ): Promise<CheckpointAttestation[] | undefined> {
425
+ const slotNumber = proposal.slotNumber;
426
+ const proposer = proposal.getSender();
427
+
428
+ // If escape hatch is open for this slot's epoch, do not attest.
429
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
430
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
431
+ return undefined;
432
+ }
433
+
434
+ // Reject proposals with invalid signatures
435
+ if (!proposer) {
436
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
437
+ return undefined;
438
+ }
439
+
440
+ // Check that I have any address in current committee before attesting
441
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
442
+ const partOfCommittee = inCommittee.length > 0;
443
+
174
444
  const proposalInfo = {
175
445
  slotNumber,
176
- blockNumber: proposal.payload.header.globalVariables.blockNumber.toNumber(),
177
- archive: proposal.payload.archive.toString(),
178
- txCount: proposal.payload.txHashes.length,
179
- txHashes: proposal.payload.txHashes.map(txHash => txHash.toString()),
446
+ archive: proposal.archive.toString(),
447
+ proposer: proposer.toString(),
448
+ txCount: proposal.txHashes.length,
180
449
  };
181
- this.log.verbose(`Received request to attest for slot ${slotNumber}`);
450
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
451
+ ...proposalInfo,
452
+ txHashes: proposal.txHashes.map(t => t.toString()),
453
+ fishermanMode: this.config.fishermanMode || false,
454
+ });
182
455
 
183
- // Check that I am in the committee
184
- if (!(await this.epochCache.isInCommittee(this.keyStore.getAddress()))) {
185
- this.log.verbose(`Not in the committee, skipping attestation`);
186
- return undefined;
456
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
457
+ if (this.config.skipCheckpointProposalValidation) {
458
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
459
+ } else {
460
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
461
+ if (!validationResult.isValid) {
462
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
463
+ return undefined;
464
+ }
187
465
  }
188
466
 
189
- // Check that the proposal is from the current proposer, or the next proposer.
190
- const invalidProposal = await this.blockProposalValidator.validate(proposal);
191
- if (invalidProposal) {
192
- this.log.verbose(`Proposal is not valid, skipping attestation`);
467
+ // Upload blobs to filestore if we can (fire and forget)
468
+ if (this.blobClient.canUpload()) {
469
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
470
+ }
471
+
472
+ // Check that I have any address in current committee before attesting
473
+ // In fisherman mode, we still create attestations for validation even if not in committee
474
+ if (!partOfCommittee && !this.config.fishermanMode) {
475
+ this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
193
476
  return undefined;
194
477
  }
195
478
 
196
- // Check that all of the transactions in the proposal are available in the tx pool before attesting
197
- this.log.verbose(`Processing attestation for slot ${slotNumber}`, proposalInfo);
198
- try {
199
- await this.ensureTransactionsAreAvailable(proposal);
479
+ // Provided all of the above checks pass, we can attest to the proposal
480
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
481
+ ...proposalInfo,
482
+ inCommittee: partOfCommittee,
483
+ fishermanMode: this.config.fishermanMode || false,
484
+ });
200
485
 
201
- if (this.config.validatorReexecute) {
202
- this.log.verbose(`Re-executing transactions in the proposal before attesting`);
203
- await this.reExecuteTransactions(proposal);
204
- }
205
- } catch (error: any) {
206
- // If the transactions are not available, then we should not attempt to attest
207
- if (error instanceof TransactionsNotAvailableError) {
208
- this.log.error(`Transactions not available, skipping attestation`, error, proposalInfo);
209
- } else {
210
- // This branch most commonly be hit if the transactions are available, but the re-execution fails
211
- // Catch all error handler
212
- this.log.error(`Failed to attest to proposal`, error, proposalInfo);
213
- }
486
+ this.metrics.incSuccessfulAttestations(inCommittee.length);
487
+
488
+ // Determine which validators should attest
489
+ let attestors: EthAddress[];
490
+ if (partOfCommittee) {
491
+ attestors = inCommittee;
492
+ } else if (this.config.fishermanMode) {
493
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
494
+ attestors = this.getValidatorAddresses();
495
+ } else {
496
+ attestors = [];
497
+ }
498
+
499
+ // Only create attestations if we have attestors
500
+ if (attestors.length === 0) {
214
501
  return undefined;
215
502
  }
216
503
 
217
- // Provided all of the above checks pass, we can attest to the proposal
218
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
504
+ if (this.config.fishermanMode) {
505
+ // bail out early and don't save attestations to the pool in fisherman mode
506
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
507
+ ...proposalInfo,
508
+ attestors: attestors.map(a => a.toString()),
509
+ });
510
+ return undefined;
511
+ }
512
+
513
+ return this.createCheckpointAttestationsFromProposal(proposal, attestors);
514
+ }
219
515
 
220
- // If the above function does not throw an error, then we can attest to the proposal
221
- return this.validationService.attestToProposal(proposal);
516
+ private async createCheckpointAttestationsFromProposal(
517
+ proposal: CheckpointProposalCore,
518
+ attestors: EthAddress[] = [],
519
+ ): Promise<CheckpointAttestation[]> {
520
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
521
+ await this.p2pClient.addCheckpointAttestations(attestations);
522
+ return attestations;
222
523
  }
223
524
 
224
525
  /**
225
- * Re-execute the transactions in the proposal and check that the state updates match the header state
226
- * @param proposal - The proposal to re-execute
526
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
527
+ * @returns Validation result with isValid flag and reason if invalid.
227
528
  */
228
- async reExecuteTransactions(proposal: BlockProposal) {
229
- const { header, txHashes } = proposal.payload;
230
-
231
- const txs = (await Promise.all(txHashes.map(tx => this.p2pClient.getTxByHash(tx)))).filter(
232
- tx => tx !== undefined,
233
- ) as Tx[];
529
+ private async validateCheckpointProposal(
530
+ proposal: CheckpointProposalCore,
531
+ proposalInfo: LogData,
532
+ ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
533
+ const slot = proposal.slotNumber;
534
+ const timeoutSeconds = 10; // TODO(palla/mbps): This should map to the timetable settings
535
+
536
+ // Wait for last block to sync by archive
537
+ let lastBlockHeader: BlockHeader | undefined;
538
+ try {
539
+ lastBlockHeader = await retryUntil(
540
+ async () => {
541
+ await this.blockSource.syncImmediate();
542
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
543
+ },
544
+ `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
545
+ timeoutSeconds,
546
+ 0.5,
547
+ );
548
+ } catch (err) {
549
+ if (err instanceof TimeoutError) {
550
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
551
+ return { isValid: false, reason: 'last_block_not_found' };
552
+ }
553
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
554
+ return { isValid: false, reason: 'block_fetch_error' };
555
+ }
234
556
 
235
- // If we cannot request all of the transactions, then we should fail
236
- if (txs.length !== txHashes.length) {
237
- throw new TransactionsNotAvailableError(txHashes);
557
+ if (!lastBlockHeader) {
558
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
559
+ return { isValid: false, reason: 'last_block_not_found' };
238
560
  }
239
561
 
240
- // Assertion: This check will fail if re-execution is not enabled
241
- if (this.blockBuilder === undefined) {
242
- throw new BlockBuilderNotProvidedError();
562
+ // Get all full blocks for the slot and checkpoint
563
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
564
+ if (blocks.length === 0) {
565
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
566
+ return { isValid: false, reason: 'no_blocks_for_slot' };
243
567
  }
244
568
 
245
- // Use the sequencer's block building logic to re-execute the transactions
246
- const stopTimer = this.metrics.reExecutionTimer();
247
- const { block, numFailedTxs } = await this.blockBuilder(txs, header.globalVariables, {
248
- validateOnly: true,
569
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
570
+ ...proposalInfo,
571
+ blockNumbers: blocks.map(b => b.number),
249
572
  });
250
- stopTimer();
251
573
 
252
- this.log.verbose(`Transaction re-execution complete`);
574
+ // Get checkpoint constants from first block
575
+ const firstBlock = blocks[0];
576
+ const constants = this.extractCheckpointConstants(firstBlock);
577
+ const checkpointNumber = firstBlock.checkpointNumber;
253
578
 
254
- if (numFailedTxs > 0) {
255
- await this.metrics.recordFailedReexecution(proposal);
256
- throw new ReExFailedTxsError(numFailedTxs);
257
- }
579
+ // Get L1-to-L2 messages for this checkpoint
580
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
258
581
 
259
- if (block.body.txEffects.length !== txHashes.length) {
260
- await this.metrics.recordFailedReexecution(proposal);
261
- throw new ReExTimeoutError();
262
- }
582
+ // Compute the previous checkpoint out hashes for the epoch.
583
+ // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
584
+ // actual checkpoints and the blocks/txs in them.
585
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
586
+ const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch))
587
+ .filter(b => b.number < checkpointNumber)
588
+ .sort((a, b) => a.number - b.number);
589
+ const previousCheckpointOutHashes = previousCheckpoints.map(c => c.getCheckpointOutHash());
590
+
591
+ // Fork world state at the block before the first block
592
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
593
+ const fork = await this.worldState.fork(parentBlockNumber);
594
+
595
+ try {
596
+ // Create checkpoint builder with all existing blocks
597
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
598
+ checkpointNumber,
599
+ constants,
600
+ l1ToL2Messages,
601
+ previousCheckpointOutHashes,
602
+ fork,
603
+ blocks,
604
+ this.log.getBindings(),
605
+ );
606
+
607
+ // Complete the checkpoint to get computed values
608
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
609
+
610
+ // Compare checkpoint header with proposal
611
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
612
+ this.log.warn(`Checkpoint header mismatch`, {
613
+ ...proposalInfo,
614
+ computed: computedCheckpoint.header.toInspect(),
615
+ proposal: proposal.checkpointHeader.toInspect(),
616
+ });
617
+ return { isValid: false, reason: 'checkpoint_header_mismatch' };
618
+ }
263
619
 
264
- // This function will throw an error if state updates do not match
265
- if (!block.archive.root.equals(proposal.archive)) {
266
- await this.metrics.recordFailedReexecution(proposal);
267
- throw new ReExStateMismatchError();
620
+ // Compare archive root with proposal
621
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
622
+ this.log.warn(`Archive root mismatch`, {
623
+ ...proposalInfo,
624
+ computed: computedCheckpoint.archive.root.toString(),
625
+ proposal: proposal.archive.toString(),
626
+ });
627
+ return { isValid: false, reason: 'archive_mismatch' };
628
+ }
629
+
630
+ // Check that the accumulated epoch out hash matches the value in the proposal.
631
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
632
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
633
+ const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
634
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
635
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
636
+ this.log.warn(`Epoch out hash mismatch`, {
637
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
638
+ computedEpochOutHash: computedEpochOutHash.toString(),
639
+ checkpointOutHash: checkpointOutHash.toString(),
640
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
641
+ ...proposalInfo,
642
+ });
643
+ return { isValid: false, reason: 'out_hash_mismatch' };
644
+ }
645
+
646
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
647
+ return { isValid: true };
648
+ } finally {
649
+ await fork.close();
268
650
  }
269
651
  }
270
652
 
271
653
  /**
272
- * Ensure that all of the transactions in the proposal are available in the tx pool before attesting
273
- *
274
- * 1. Check if the local tx pool contains all of the transactions in the proposal
275
- * 2. If any transactions are not in the local tx pool, request them from the network
276
- * 3. If we cannot retrieve them from the network, throw an error
277
- * @param proposal - The proposal to attest to
654
+ * Extract checkpoint global variables from a block.
278
655
  */
279
- async ensureTransactionsAreAvailable(proposal: BlockProposal) {
280
- const txHashes: TxHash[] = proposal.payload.txHashes;
281
- const transactionStatuses = await Promise.all(txHashes.map(txHash => this.p2pClient.getTxStatus(txHash)));
656
+ private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
657
+ const gv = block.header.globalVariables;
658
+ return {
659
+ chainId: gv.chainId,
660
+ version: gv.version,
661
+ slotNumber: gv.slotNumber,
662
+ coinbase: gv.coinbase,
663
+ feeRecipient: gv.feeRecipient,
664
+ gasFees: gv.gasFees,
665
+ };
666
+ }
282
667
 
283
- const missingTxs = txHashes.filter((_, index) => !['pending', 'mined'].includes(transactionStatuses[index] ?? ''));
668
+ /**
669
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
670
+ */
671
+ private async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
672
+ try {
673
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
674
+ if (!lastBlockHeader) {
675
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
676
+ return;
677
+ }
284
678
 
285
- if (missingTxs.length === 0) {
286
- return; // All transactions are available
679
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
680
+ if (blocks.length === 0) {
681
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
682
+ return;
683
+ }
684
+
685
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
686
+ const blobs: Blob[] = getBlobsPerL1Block(blobFields);
687
+ await this.blobClient.sendBlobsToFilestore(blobs);
688
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
689
+ ...proposalInfo,
690
+ numBlobs: blobs.length,
691
+ });
692
+ } catch (err) {
693
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
287
694
  }
695
+ }
288
696
 
289
- this.log.verbose(`Missing ${missingTxs.length} transactions in the tx pool, requesting from the network`);
697
+ private slashInvalidBlock(proposal: BlockProposal) {
698
+ const proposer = proposal.getSender();
290
699
 
291
- const requestedTxs = await this.p2pClient.requestTxs(missingTxs);
292
- if (requestedTxs.some(tx => tx === undefined)) {
293
- throw new TransactionsNotAvailableError(missingTxs);
700
+ // Skip if signature is invalid (shouldn't happen since we validate earlier)
701
+ if (!proposer) {
702
+ this.log.warn(`Cannot slash proposal with invalid signature`);
703
+ return;
294
704
  }
295
- }
296
705
 
297
- async createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal | undefined> {
298
- if (this.previousProposal?.slotNumber.equals(header.globalVariables.slotNumber)) {
299
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
300
- return Promise.resolve(undefined);
706
+ // Trim the set if it's too big.
707
+ if (this.proposersOfInvalidBlocks.size > MAX_PROPOSERS_OF_INVALID_BLOCKS) {
708
+ // remove oldest proposer. `values` is guaranteed to be in insertion order.
709
+ this.proposersOfInvalidBlocks.delete(this.proposersOfInvalidBlocks.values().next().value!);
301
710
  }
302
711
 
303
- const newProposal = await this.validationService.createBlockProposal(header, archive, txs);
712
+ this.proposersOfInvalidBlocks.add(proposer.toString());
713
+
714
+ this.emit(WANT_TO_SLASH_EVENT, [
715
+ {
716
+ validator: proposer,
717
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
718
+ offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
719
+ epochOrSlot: BigInt(proposal.slotNumber),
720
+ },
721
+ ]);
722
+ }
723
+
724
+ async createBlockProposal(
725
+ blockHeader: BlockHeader,
726
+ indexWithinCheckpoint: IndexWithinCheckpoint,
727
+ inHash: Fr,
728
+ archive: Fr,
729
+ txs: Tx[],
730
+ proposerAddress: EthAddress | undefined,
731
+ options: BlockProposalOptions = {},
732
+ ): Promise<BlockProposal> {
733
+ // TODO(palla/mbps): Prevent double proposals properly
734
+ // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
735
+ // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
736
+ // return Promise.resolve(undefined);
737
+ // }
738
+
739
+ this.log.info(
740
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
741
+ );
742
+ const newProposal = await this.validationService.createBlockProposal(
743
+ blockHeader,
744
+ indexWithinCheckpoint,
745
+ inHash,
746
+ archive,
747
+ txs,
748
+ proposerAddress,
749
+ {
750
+ ...options,
751
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
752
+ },
753
+ );
304
754
  this.previousProposal = newProposal;
305
755
  return newProposal;
306
756
  }
307
757
 
308
- broadcastBlockProposal(proposal: BlockProposal): void {
309
- this.p2pClient.broadcastProposal(proposal);
758
+ async createCheckpointProposal(
759
+ checkpointHeader: CheckpointHeader,
760
+ archive: Fr,
761
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
762
+ proposerAddress: EthAddress | undefined,
763
+ options: CheckpointProposalOptions = {},
764
+ ): Promise<CheckpointProposal> {
765
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
766
+ return await this.validationService.createCheckpointProposal(
767
+ checkpointHeader,
768
+ archive,
769
+ lastBlockInfo,
770
+ proposerAddress,
771
+ options,
772
+ );
773
+ }
774
+
775
+ async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
776
+ await this.p2pClient.broadcastProposal(proposal);
777
+ }
778
+
779
+ async signAttestationsAndSigners(
780
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
781
+ proposer: EthAddress,
782
+ slot: SlotNumber,
783
+ blockNumber: BlockNumber | CheckpointNumber,
784
+ ): Promise<Signature> {
785
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
310
786
  }
311
787
 
312
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7962)
313
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
314
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
315
- const slot = proposal.payload.header.globalVariables.slotNumber.toBigInt();
788
+ async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
789
+ const slot = proposal.slotNumber;
790
+ const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
791
+ this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
792
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
793
+
794
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
795
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
796
+ // due to inactivity for missed attestations.
797
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
798
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
799
+ });
800
+ return attestations;
801
+ }
802
+
803
+ async collectAttestations(
804
+ proposal: CheckpointProposal,
805
+ required: number,
806
+ deadline: Date,
807
+ ): Promise<CheckpointAttestation[]> {
808
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
809
+ const slot = proposal.slotNumber;
316
810
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
317
811
 
318
812
  if (+deadline < this.dateProvider.now()) {
319
813
  this.log.error(
320
814
  `Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`,
321
815
  );
322
- throw new AttestationTimeoutError(required, slot);
816
+ throw new AttestationTimeoutError(0, required, slot);
323
817
  }
324
818
 
819
+ await this.collectOwnAttestations(proposal);
820
+
325
821
  const proposalId = proposal.archive.toString();
326
- const myAttestation = await this.validationService.attestToProposal(proposal);
822
+ const myAddresses = this.getValidatorAddresses();
327
823
 
328
- let attestations: BlockAttestation[] = [];
824
+ let attestations: CheckpointAttestation[] = [];
329
825
  while (true) {
330
- const collectedAttestations = [myAttestation, ...(await this.p2pClient.getAttestationsForSlot(slot, proposalId))];
331
- const oldSenders = await Promise.all(attestations.map(attestation => attestation.getSender()));
826
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
827
+ // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
828
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
829
+ attestation => {
830
+ if (!attestation.archive.equals(proposal.archive)) {
831
+ this.log.warn(
832
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
833
+ { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
834
+ );
835
+ return false;
836
+ }
837
+ return true;
838
+ },
839
+ );
840
+
841
+ // Log new attestations we collected
842
+ const oldSenders = attestations.map(attestation => attestation.getSender());
332
843
  for (const collected of collectedAttestations) {
333
- const collectedSender = await collected.getSender();
334
- if (!oldSenders.some(sender => sender.equals(collectedSender))) {
844
+ const collectedSender = collected.getSender();
845
+ // Skip attestations with invalid signatures
846
+ if (!collectedSender) {
847
+ this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
848
+ continue;
849
+ }
850
+ if (
851
+ !myAddresses.some(address => address.equals(collectedSender)) &&
852
+ !oldSenders.some(sender => sender?.equals(collectedSender))
853
+ ) {
335
854
  this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
336
855
  }
337
856
  }
@@ -344,19 +863,36 @@ export class ValidatorClient extends WithTracer implements Validator {
344
863
 
345
864
  if (+deadline < this.dateProvider.now()) {
346
865
  this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
347
- throw new AttestationTimeoutError(required, slot);
866
+ throw new AttestationTimeoutError(attestations.length, required, slot);
348
867
  }
349
868
 
350
- this.log.debug(`Collected ${attestations.length} attestations so far`);
869
+ this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
351
870
  await sleep(this.config.attestationPollingIntervalMs);
352
871
  }
353
872
  }
354
- }
355
873
 
356
- function validatePrivateKey(privateKey: string): Buffer32 {
357
- try {
358
- return Buffer32.fromString(privateKey);
359
- } catch (error) {
360
- throw new InvalidValidatorPrivateKeyError();
874
+ private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
875
+ const authRequest = AuthRequest.fromBuffer(msg);
876
+ const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
877
+ if (statusMessage === undefined) {
878
+ return Buffer.alloc(0);
879
+ }
880
+
881
+ // Find a validator address that is in the set
882
+ const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
883
+ const addressToUse = this.getValidatorAddresses().find(
884
+ address => allRegisteredValidators.find(v => v.equals(address)) !== undefined,
885
+ );
886
+ if (addressToUse === undefined) {
887
+ // We don't have a registered address
888
+ return Buffer.alloc(0);
889
+ }
890
+
891
+ const payloadToSign = authRequest.getPayloadToSign();
892
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
893
+ const context: SigningContext = { dutyType: DutyType.AUTH_REQUEST };
894
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
895
+ const authResponse = new AuthResponse(statusMessage, signature);
896
+ return authResponse.toBuffer();
361
897
  }
362
898
  }