@aztec-labs/validator-client 6.0.0-nightly.20260829

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 (62) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +92 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +272 -0
  5. package/dest/config.d.ts +17 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +102 -0
  8. package/dest/duties/validation_service.d.ts +65 -0
  9. package/dest/duties/validation_service.d.ts.map +1 -0
  10. package/dest/duties/validation_service.js +128 -0
  11. package/dest/factory.d.ts +41 -0
  12. package/dest/factory.d.ts.map +1 -0
  13. package/dest/factory.js +19 -0
  14. package/dest/index.d.ts +7 -0
  15. package/dest/index.d.ts.map +1 -0
  16. package/dest/index.js +6 -0
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +6 -0
  21. package/dest/key_store/index.d.ts.map +1 -0
  22. package/dest/key_store/index.js +5 -0
  23. package/dest/key_store/interface.d.ts +104 -0
  24. package/dest/key_store/interface.d.ts.map +1 -0
  25. package/dest/key_store/interface.js +4 -0
  26. package/dest/key_store/local_key_store.d.ts +63 -0
  27. package/dest/key_store/local_key_store.d.ts.map +1 -0
  28. package/dest/key_store/local_key_store.js +83 -0
  29. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  30. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  31. package/dest/key_store/node_keystore_adapter.js +330 -0
  32. package/dest/key_store/web3signer_key_store.d.ts +74 -0
  33. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  34. package/dest/key_store/web3signer_key_store.js +147 -0
  35. package/dest/metrics.d.ts +31 -0
  36. package/dest/metrics.d.ts.map +1 -0
  37. package/dest/metrics.js +101 -0
  38. package/dest/proposal_handler.d.ts +188 -0
  39. package/dest/proposal_handler.d.ts.map +1 -0
  40. package/dest/proposal_handler.js +1438 -0
  41. package/dest/streaming_inbox_checks.d.ts +103 -0
  42. package/dest/streaming_inbox_checks.d.ts.map +1 -0
  43. package/dest/streaming_inbox_checks.js +112 -0
  44. package/dest/validator.d.ts +137 -0
  45. package/dest/validator.d.ts.map +1 -0
  46. package/dest/validator.js +771 -0
  47. package/package.json +110 -0
  48. package/src/checkpoint_builder.ts +449 -0
  49. package/src/config.ts +130 -0
  50. package/src/duties/validation_service.ts +224 -0
  51. package/src/factory.ts +95 -0
  52. package/src/index.ts +6 -0
  53. package/src/key_store/ha_key_store.ts +268 -0
  54. package/src/key_store/index.ts +5 -0
  55. package/src/key_store/interface.ts +120 -0
  56. package/src/key_store/local_key_store.ts +104 -0
  57. package/src/key_store/node_keystore_adapter.ts +397 -0
  58. package/src/key_store/web3signer_key_store.ts +188 -0
  59. package/src/metrics.ts +150 -0
  60. package/src/proposal_handler.ts +1598 -0
  61. package/src/streaming_inbox_checks.ts +198 -0
  62. package/src/validator.ts +1125 -0
@@ -0,0 +1,1125 @@
1
+ import type { BlobClientInterface } from '@aztec-labs/blob-client/client';
2
+ import { type Blob, getBlobsPerL1Block } from '@aztec-labs/blob-lib';
3
+ import type { EpochCache } from '@aztec-labs/epoch-cache';
4
+ import { CheckpointNumber, EpochNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec-labs/foundation/branded-types';
5
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
6
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
7
+ import { Signature } from '@aztec-labs/foundation/eth-signature';
8
+ import { FifoSet } from '@aztec-labs/foundation/fifo-set';
9
+ import { type LogData, type Logger, createLogger } from '@aztec-labs/foundation/log';
10
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
11
+ import { sleep } from '@aztec-labs/foundation/sleep';
12
+ import { DateProvider } from '@aztec-labs/foundation/timer';
13
+ import type { KeystoreManager } from '@aztec-labs/node-keystore';
14
+ import type {
15
+ DuplicateAttestationInfo,
16
+ DuplicateProposalInfo,
17
+ OversizedProposalInfo,
18
+ P2P,
19
+ PeerId,
20
+ } from '@aztec-labs/p2p';
21
+ import { AuthRequest, AuthResponse, ReqRespSubProtocol } from '@aztec-labs/p2p';
22
+ import {
23
+ OffenseType,
24
+ WANT_TO_CLEAR_SLASH_EVENT,
25
+ WANT_TO_SLASH_EVENT,
26
+ type Watcher,
27
+ type WatcherEmitter,
28
+ getOffenseTypeName,
29
+ } from '@aztec-labs/slasher';
30
+ import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
31
+ import type { CommitteeAttestationsAndSigners, L2BlockSink, L2BlockSource } from '@aztec-labs/stdlib/block';
32
+ import type { CheckpointReexecutionTracker } from '@aztec-labs/stdlib/checkpoint';
33
+ import { getEpochAtSlot } from '@aztec-labs/stdlib/epoch-helpers';
34
+ import type {
35
+ ITxProvider,
36
+ Validator,
37
+ ValidatorClientFullConfig,
38
+ WorldStateSynchronizer,
39
+ } from '@aztec-labs/stdlib/interfaces/server';
40
+ import type { InboxBucketRef, L1ToL2MessageSource } from '@aztec-labs/stdlib/messaging';
41
+ import {
42
+ type BlockProposal,
43
+ type BlockProposalOptions,
44
+ CheckpointAttestation,
45
+ CheckpointProposal,
46
+ type CheckpointProposalCore,
47
+ type CheckpointProposalOptions,
48
+ type CoordinationSignatureContext,
49
+ type ValidatedBlockProposal,
50
+ type ValidatedCheckpointProposalCore,
51
+ } from '@aztec-labs/stdlib/p2p';
52
+ import type { CheckpointHeader } from '@aztec-labs/stdlib/rollup';
53
+ import { ConsensusTimetable } from '@aztec-labs/stdlib/timetable';
54
+ import type { BlockHeader, Tx } from '@aztec-labs/stdlib/tx';
55
+ import { AttestationTimeoutError } from '@aztec-labs/stdlib/validators';
56
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec-labs/telemetry-client';
57
+ import {
58
+ createHASigner,
59
+ createLocalSignerWithProtection,
60
+ createSignerFromSharedDb,
61
+ } from '@aztec-labs/validator-ha-signer/factory';
62
+ import { DutyType, type SigningContext, type SlashingProtectionDatabase } from '@aztec-labs/validator-ha-signer/types';
63
+ import type { ValidatorHASigner } from '@aztec-labs/validator-ha-signer/validator-ha-signer';
64
+ import { EventEmitter } from 'events';
65
+ import type { TypedDataDefinition } from 'viem';
66
+
67
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
68
+ import { ValidationService } from './duties/validation_service.js';
69
+ import { HAKeyStore } from './key_store/ha_key_store.js';
70
+ import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
71
+ import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
72
+ import { ValidatorMetrics } from './metrics.js';
73
+ import {
74
+ type BlockProposalValidationFailureReason,
75
+ type CheckpointProposalValidationFailureResult,
76
+ ProposalHandler,
77
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT,
78
+ SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT,
79
+ } from './proposal_handler.js';
80
+
81
+ // We maintain a set of proposers who have proposed invalid blocks.
82
+ // Just cap the set to avoid unbounded growth.
83
+ const MAX_PROPOSERS_OF_INVALID_BLOCKS = 1000;
84
+ const MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS = 1000;
85
+ const MAX_TRACKED_BAD_ATTESTATIONS = 10_000;
86
+
87
+ /**
88
+ * Validator Client
89
+ */
90
+ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter) implements Validator, Watcher {
91
+ public readonly tracer: Tracer;
92
+ private validationService: ValidationService;
93
+ private metrics: ValidatorMetrics;
94
+ private log: Logger;
95
+ // Whether it has already registered handlers on the p2p client
96
+ private hasRegisteredHandlers = false;
97
+
98
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
99
+ private lastProposedBlock?: BlockProposal;
100
+
101
+ /** Tracks the last checkpoint proposal we created. */
102
+ private lastProposedCheckpoint?: CheckpointProposal;
103
+
104
+ private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
105
+ private epochCacheUpdateLoop: RunningPromise;
106
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */
107
+ private lastAttestedEpochByAttester: Map<string, EpochNumber> = new Map();
108
+
109
+ private proposersOfInvalidBlocks = FifoSet.withLimit<string>(MAX_PROPOSERS_OF_INVALID_BLOCKS);
110
+ private invalidCheckpointProposalOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS);
111
+ private oversizedProposalOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_INVALID_CHECKPOINT_PROPOSALS);
112
+ private badAttestationOffenseKeys = FifoSet.withLimit<string>(MAX_TRACKED_BAD_ATTESTATIONS);
113
+
114
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
115
+ private lastAttestedProposal?: CheckpointProposalCore;
116
+
117
+ protected constructor(
118
+ private keyStore: ExtendedValidatorKeyStore,
119
+ private epochCache: EpochCache,
120
+ private p2pClient: P2P,
121
+ private proposalHandler: ProposalHandler,
122
+ private blockSource: L2BlockSource,
123
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
124
+ private worldState: WorldStateSynchronizer,
125
+ private l1ToL2MessageSource: L1ToL2MessageSource,
126
+ private config: ValidatorClientFullConfig,
127
+ private blobClient: BlobClientInterface,
128
+ private slashingProtectionSigner: ValidatorHASigner,
129
+ private dateProvider: DateProvider = new DateProvider(),
130
+ telemetry: TelemetryClient = getTelemetryClient(),
131
+ log = createLogger('validator'),
132
+ ) {
133
+ super();
134
+
135
+ // Create child logger with fisherman prefix if in fisherman mode
136
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
137
+
138
+ this.tracer = telemetry.getTracer('Validator');
139
+ this.metrics = new ValidatorMetrics(telemetry);
140
+
141
+ this.validationService = new ValidationService(
142
+ keyStore,
143
+ this.getSignatureContext(),
144
+ this.log.createChild('validation-service'),
145
+ );
146
+ this.proposalHandler.setCheckpointProposalValidationFailureCallback((proposal, result, proposalInfo) =>
147
+ this.handleInvalidCheckpointProposal(proposal, result, proposalInfo),
148
+ );
149
+
150
+ // Refresh epoch cache every second to trigger alert if participation in committee changes
151
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
152
+ const myAddresses = this.getValidatorAddresses();
153
+ this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
154
+ }
155
+
156
+ public static validateKeyStoreConfiguration(keyStoreManager: KeystoreManager, logger?: Logger) {
157
+ const validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
158
+ const validatorAddresses = validatorKeyStore.getAddresses();
159
+ // Verify that we can retrieve all required data from the key store
160
+ for (const address of validatorAddresses) {
161
+ // Functions throw if required data is not available
162
+ let coinbase: EthAddress;
163
+ let feeRecipient: AztecAddress;
164
+ try {
165
+ coinbase = validatorKeyStore.getCoinbaseAddress(address);
166
+ feeRecipient = validatorKeyStore.getFeeRecipient(address);
167
+ } catch (error) {
168
+ throw new Error(`Failed to retrieve required data for validator address ${address}, error: ${error}`);
169
+ }
170
+
171
+ const publisherAddresses = validatorKeyStore.getPublisherAddresses(address);
172
+ if (!publisherAddresses.length) {
173
+ throw new Error(`No publisher addresses found for validator address ${address}`);
174
+ }
175
+ logger?.debug(
176
+ `Validator ${address.toString()} configured with coinbase ${coinbase.toString()}, feeRecipient ${feeRecipient.toString()} and publishers ${publisherAddresses.map(x => x.toString()).join()}`,
177
+ );
178
+ }
179
+ }
180
+
181
+ private async handleEpochCommitteeUpdate() {
182
+ try {
183
+ const { committee, epoch } = await this.epochCache.getCommittee('next');
184
+ if (!committee) {
185
+ this.log.trace(`No committee found for slot`);
186
+ return;
187
+ }
188
+ this.metrics.setCurrentEpoch(epoch);
189
+ if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
190
+ const me = this.getValidatorAddresses();
191
+ const committeeSet = new Set(committee.map(v => v.toString()));
192
+ const inCommittee = me.filter(a => committeeSet.has(a.toString()));
193
+ if (inCommittee.length > 0) {
194
+ this.log.info(
195
+ `Validators ${inCommittee.map(a => a.toString()).join(',')} are on the validator committee for epoch ${epoch}`,
196
+ );
197
+ } else {
198
+ this.log.verbose(
199
+ `Validators ${me.map(a => a.toString()).join(', ')} are not on the validator committee for epoch ${epoch}`,
200
+ );
201
+ }
202
+ this.lastEpochForCommitteeUpdateLoop = epoch;
203
+ }
204
+ } catch (err) {
205
+ this.log.error(`Error updating epoch committee`, err);
206
+ }
207
+ }
208
+
209
+ static async new(
210
+ config: ValidatorClientFullConfig,
211
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
212
+ worldState: WorldStateSynchronizer,
213
+ epochCache: EpochCache,
214
+ p2pClient: P2P,
215
+ blockSource: L2BlockSource & L2BlockSink,
216
+ l1ToL2MessageSource: L1ToL2MessageSource,
217
+ txProvider: ITxProvider,
218
+ keyStoreManager: KeystoreManager,
219
+ blobClient: BlobClientInterface,
220
+ reexecutionTracker: CheckpointReexecutionTracker,
221
+ dateProvider: DateProvider = new DateProvider(),
222
+ telemetry: TelemetryClient = getTelemetryClient(),
223
+ slashingProtectionDb?: SlashingProtectionDatabase,
224
+ ) {
225
+ const metrics = new ValidatorMetrics(telemetry);
226
+ const consensusTimetable = new ConsensusTimetable({
227
+ l1Constants: epochCache.getL1Constants(),
228
+ blockDuration: config.blockDurationMs / 1000,
229
+ });
230
+ const proposalHandler = new ProposalHandler(
231
+ checkpointsBuilder,
232
+ worldState,
233
+ blockSource,
234
+ l1ToL2MessageSource,
235
+ txProvider,
236
+ epochCache,
237
+ consensusTimetable,
238
+ config,
239
+ blobClient,
240
+ reexecutionTracker,
241
+ metrics,
242
+ dateProvider,
243
+ telemetry,
244
+ undefined,
245
+ );
246
+
247
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
248
+ let slashingProtectionSigner: ValidatorHASigner;
249
+ if (slashingProtectionDb) {
250
+ // Shared database mode: use a pre-existing database (e.g. for testing HA setups).
251
+ ({ signer: slashingProtectionSigner } = createSignerFromSharedDb(slashingProtectionDb, config, {
252
+ telemetryClient: telemetry,
253
+ dateProvider,
254
+ }));
255
+ } else if (config.haSigningEnabled) {
256
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
257
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
258
+ const haConfig = {
259
+ ...config,
260
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
261
+ };
262
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
263
+ telemetryClient: telemetry,
264
+ dateProvider,
265
+ }));
266
+ } else {
267
+ // Single-node mode: use LMDB-backed local signing protection.
268
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
269
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
270
+ telemetryClient: telemetry,
271
+ dateProvider,
272
+ }));
273
+ }
274
+ const validatorKeyStore: ExtendedValidatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
275
+
276
+ const validator = new ValidatorClient(
277
+ validatorKeyStore,
278
+ epochCache,
279
+ p2pClient,
280
+ proposalHandler,
281
+ blockSource,
282
+ checkpointsBuilder,
283
+ worldState,
284
+ l1ToL2MessageSource,
285
+ config,
286
+ blobClient,
287
+ slashingProtectionSigner,
288
+ dateProvider,
289
+ telemetry,
290
+ );
291
+
292
+ return validator;
293
+ }
294
+
295
+ public getValidatorAddresses() {
296
+ return this.keyStore
297
+ .getAddresses()
298
+ .filter(addr => !this.config.disabledValidators.some(disabled => disabled.equals(addr)));
299
+ }
300
+
301
+ public getProposalHandler() {
302
+ return this.proposalHandler;
303
+ }
304
+
305
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
306
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
307
+ }
308
+
309
+ private getSignatureContext(): CoordinationSignatureContext {
310
+ return {
311
+ chainId: this.config.l1ChainId,
312
+ rollupAddress: this.config.rollupAddress,
313
+ };
314
+ }
315
+
316
+ public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
317
+ return this.keyStore.getCoinbaseAddress(attestor);
318
+ }
319
+
320
+ public getFeeRecipientForAttestor(attestor: EthAddress): AztecAddress {
321
+ return this.keyStore.getFeeRecipient(attestor);
322
+ }
323
+
324
+ public getConfig(): ValidatorClientFullConfig {
325
+ return this.config;
326
+ }
327
+
328
+ public hasProposalEquivocation(slotNumber: SlotNumber): boolean {
329
+ return this.proposalHandler.hasProposalEquivocation(slotNumber);
330
+ }
331
+
332
+ public hasInvalidProposals(slotNumber: SlotNumber): boolean {
333
+ return this.proposalHandler.hasInvalidProposals(slotNumber);
334
+ }
335
+
336
+ public updateConfig(config: Partial<ValidatorClientFullConfig>) {
337
+ this.config = { ...this.config, ...config };
338
+ this.proposalHandler.updateConfig(config);
339
+ }
340
+
341
+ public reloadKeystore(newManager: KeystoreManager): void {
342
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
343
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
344
+ this.validationService = new ValidationService(
345
+ this.keyStore,
346
+ this.getSignatureContext(),
347
+ this.log.createChild('validation-service'),
348
+ );
349
+ }
350
+
351
+ public async start() {
352
+ if (this.epochCacheUpdateLoop.isRunning()) {
353
+ this.log.warn(`Validator client already started`);
354
+ return;
355
+ }
356
+
357
+ await this.keyStore.start();
358
+
359
+ await this.registerHandlers();
360
+
361
+ const myAddresses = this.getValidatorAddresses();
362
+ const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
363
+ this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
364
+ if (inCommittee.length > 0) {
365
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
366
+ }
367
+ this.epochCacheUpdateLoop.start();
368
+
369
+ return Promise.resolve();
370
+ }
371
+
372
+ public async stop() {
373
+ await this.epochCacheUpdateLoop.stop();
374
+ await this.keyStore.stop();
375
+ }
376
+
377
+ /** Register handlers on the p2p client */
378
+ public async registerHandlers() {
379
+ if (!this.hasRegisteredHandlers) {
380
+ this.hasRegisteredHandlers = true;
381
+ this.log.debug(`Registering validator handlers for p2p client`);
382
+
383
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
384
+ const blockHandler = (block: ValidatedBlockProposal, proposalSender: PeerId): Promise<boolean> =>
385
+ this.validateBlockProposal(block, proposalSender);
386
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
387
+
388
+ // Checkpoint proposal handler - validates and creates attestations
389
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
390
+ // and processed separately via the block handler above.
391
+ const checkpointHandler = (
392
+ checkpoint: ValidatedCheckpointProposalCore,
393
+ proposalSender: PeerId,
394
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
395
+ this.p2pClient.registerValidatorCheckpointProposalHandler(checkpointHandler);
396
+
397
+ // Duplicate proposal handler - triggers slashing for equivocation
398
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
399
+ this.handleDuplicateProposal(info);
400
+ });
401
+
402
+ // Oversized proposal handler - triggers slashing for proposals beyond the per-checkpoint block limit
403
+ this.p2pClient.registerOversizedProposalCallback((info: OversizedProposalInfo) => {
404
+ this.handleOversizedProposal(info);
405
+ });
406
+
407
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
408
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
409
+ this.handleDuplicateAttestation(info);
410
+ });
411
+
412
+ this.p2pClient.registerCheckpointAttestationCallback((attestation: CheckpointAttestation) => {
413
+ this.handleCheckpointAttestation(attestation);
414
+ });
415
+
416
+ const myAddresses = this.getValidatorAddresses();
417
+ this.p2pClient.registerThisValidatorAddresses(myAddresses);
418
+
419
+ await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Validate a block proposal from a peer.
425
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
426
+ * @returns true if the proposal is valid, false otherwise
427
+ */
428
+ async validateBlockProposal(proposal: ValidatedBlockProposal, proposalSender: PeerId): Promise<boolean> {
429
+ const slotNumber = proposal.slotNumber;
430
+
431
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
432
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
433
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
434
+
435
+ const proposer = proposal.getSender();
436
+
437
+ // Reject proposals with invalid signatures
438
+ if (!proposer) {
439
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
440
+ return false;
441
+ }
442
+
443
+ // Log self-proposals from HA peers (same validator key on different nodes)
444
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
445
+ this.log.verbose(`Processing block proposal from HA peer for slot ${slotNumber}`, {
446
+ proposer: proposer.toString(),
447
+ slotNumber,
448
+ });
449
+ }
450
+
451
+ // Check if we're in the committee (for metrics purposes)
452
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
453
+ const partOfCommittee = inCommittee.length > 0;
454
+
455
+ const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
456
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
457
+ ...proposalInfo,
458
+ txHashes: proposal.txHashes.map(t => t.toString()),
459
+ fishermanMode: this.config.fishermanMode || false,
460
+ });
461
+
462
+ // Reexecute outside the escape hatch so slashing observers can detect invalid proposals even when penalties are 0.
463
+ const validationResult = await this.proposalHandler.handleBlockProposal(proposal, proposalSender, !escapeHatchOpen);
464
+
465
+ if (!validationResult.isValid) {
466
+ const reason = validationResult.reason || 'unknown';
467
+
468
+ this.log.warn(`Block proposal validation failed: ${reason}`, proposalInfo);
469
+
470
+ // Classify failure reason: bad proposal vs node issue
471
+ const badProposalReasons: BlockProposalValidationFailureReason[] = [
472
+ 'invalid_proposal',
473
+ 'state_mismatch',
474
+ 'failed_txs',
475
+ 'parent_block_wrong_slot',
476
+ 'duplicate_txs',
477
+ 'invalid_embedded_txs',
478
+ ];
479
+
480
+ if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
481
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
482
+ } else {
483
+ // Node issues so we can't validate
484
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
485
+ }
486
+
487
+ if (
488
+ !escapeHatchOpen &&
489
+ validationResult.reason &&
490
+ SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason)
491
+ ) {
492
+ this.log.info(`Detected invalid block proposal offense`, {
493
+ ...proposalInfo,
494
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
495
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL),
496
+ });
497
+ this.slashInvalidBlock(proposal);
498
+ this.markInvalidProposalSlot(proposal.slotNumber);
499
+ }
500
+ return false;
501
+ }
502
+
503
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
504
+ ...proposalInfo,
505
+ inCommittee: partOfCommittee,
506
+ fishermanMode: this.config.fishermanMode || false,
507
+ escapeHatchOpen,
508
+ });
509
+
510
+ if (escapeHatchOpen) {
511
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
512
+ return false;
513
+ }
514
+
515
+ return true;
516
+ }
517
+
518
+ /**
519
+ * Validate and attest to a checkpoint proposal from a peer.
520
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
521
+ * the lastBlock is extracted and processed separately via the block handler.
522
+ * @returns Checkpoint attestations if valid, undefined otherwise
523
+ */
524
+ async attestToCheckpointProposal(
525
+ proposal: ValidatedCheckpointProposalCore,
526
+ _proposalSender: PeerId,
527
+ ): Promise<CheckpointAttestation[] | undefined> {
528
+ const proposalSlotNumber = proposal.slotNumber;
529
+ const proposer = proposal.getSender();
530
+
531
+ // If escape hatch is open for this slot's epoch, do not attest.
532
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposalSlotNumber)) {
533
+ this.log.warn(`Escape hatch open for slot ${proposalSlotNumber}, skipping checkpoint attestation handling`);
534
+ return undefined;
535
+ }
536
+
537
+ // Early-out for equivocation: refuses if we've already attested to a higher slot.
538
+ if (!this.shouldAttestToSlot(proposalSlotNumber)) {
539
+ return undefined;
540
+ }
541
+
542
+ // Ignore proposals from ourselves (may happen in HA setups)
543
+ if (proposer && this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
544
+ this.log.debug(`Not attesting to block proposal from self for slot ${proposalSlotNumber}`, {
545
+ proposer: proposer.toString(),
546
+ proposalSlotNumber,
547
+ });
548
+ return undefined;
549
+ }
550
+
551
+ // Check that I have any address in the committee where this checkpoint will land before attesting
552
+ const inCommittee = await this.epochCache.filterInCommittee(proposalSlotNumber, this.getValidatorAddresses());
553
+ const partOfCommittee = inCommittee.length > 0;
554
+
555
+ const proposalInfo = {
556
+ proposalSlotNumber,
557
+ archive: proposal.archive.toString(),
558
+ proposer: proposer?.toString(),
559
+ };
560
+ this.log.info(`Received checkpoint proposal for slot ${proposalSlotNumber}`, {
561
+ ...proposalInfo,
562
+ fishermanMode: this.config.fishermanMode || false,
563
+ });
564
+
565
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set).
566
+ // Uses the cached result from the all-nodes callback if available (avoids double validation).
567
+ let checkpointNumber: CheckpointNumber;
568
+ if (this.config.skipCheckpointProposalValidation) {
569
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposalSlotNumber}`, proposalInfo);
570
+ checkpointNumber = CheckpointNumber(0);
571
+ } else {
572
+ const validationResult = await this.proposalHandler.handleCheckpointProposal(proposal, proposalInfo);
573
+ if (!validationResult.isValid) {
574
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
575
+ return undefined;
576
+ }
577
+ checkpointNumber = validationResult.checkpointNumber;
578
+ }
579
+
580
+ // Check that I have any address in current committee before attesting
581
+ // In fisherman mode, we still create attestations for validation even if not in committee
582
+ if (!partOfCommittee && !this.config.fishermanMode) {
583
+ this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
584
+ return undefined;
585
+ }
586
+
587
+ // Provided all of the above checks pass, we can attest to the proposal
588
+ this.log.info(
589
+ `${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${proposalSlotNumber}`,
590
+ {
591
+ ...proposalInfo,
592
+ inCommittee: partOfCommittee,
593
+ fishermanMode: this.config.fishermanMode || false,
594
+ },
595
+ );
596
+
597
+ this.metrics.incSuccessfulAttestations(inCommittee.length);
598
+
599
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
600
+ const proposalEpoch = getEpochAtSlot(proposalSlotNumber, this.epochCache.getL1Constants());
601
+ for (const attester of inCommittee) {
602
+ const key = attester.toString();
603
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
604
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
605
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
606
+ this.metrics.incAttestedEpochCount(attester);
607
+ }
608
+ }
609
+
610
+ // Determine which validators should attest
611
+ let attestors: EthAddress[];
612
+ if (partOfCommittee) {
613
+ attestors = inCommittee;
614
+ } else if (this.config.fishermanMode) {
615
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
616
+ attestors = this.getValidatorAddresses();
617
+ } else {
618
+ attestors = [];
619
+ }
620
+
621
+ // Only create attestations if we have attestors
622
+ if (attestors.length === 0) {
623
+ return undefined;
624
+ }
625
+
626
+ if (this.config.fishermanMode) {
627
+ // bail out early and don't save attestations to the pool in fisherman mode
628
+ this.log.info(`Creating checkpoint attestations for slot ${proposalSlotNumber}`, {
629
+ ...proposalInfo,
630
+ attestors: attestors.map(a => a.toString()),
631
+ });
632
+ return undefined;
633
+ }
634
+
635
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors, checkpointNumber);
636
+ }
637
+
638
+ /**
639
+ * Checks if we should attest to a slot based on equivocation prevention rules.
640
+ * @returns true if we should attest, false if we should skip
641
+ */
642
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
643
+ // If attestToEquivocatedProposals is true, always allow
644
+ if (this.config.attestToEquivocatedProposals) {
645
+ return true;
646
+ }
647
+
648
+ // Check if incoming slot is strictly greater than last attested
649
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
650
+ this.log.warn(
651
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
652
+ );
653
+ return false;
654
+ }
655
+
656
+ return true;
657
+ }
658
+
659
+ private async createCheckpointAttestationsFromProposal(
660
+ proposal: CheckpointProposalCore,
661
+ attestors: EthAddress[] = [],
662
+ checkpointNumber: CheckpointNumber,
663
+ ): Promise<CheckpointAttestation[] | undefined> {
664
+ // Equivocation check: must happen right before signing to minimize the race window
665
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
666
+ return undefined;
667
+ }
668
+
669
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors, checkpointNumber);
670
+
671
+ // Track the proposal we attested to (to prevent equivocation)
672
+ this.lastAttestedProposal = proposal;
673
+
674
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
675
+ return attestations;
676
+ }
677
+
678
+ /**
679
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
680
+ */
681
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
682
+ try {
683
+ const lastBlockHeader = (await this.blockSource.getBlockData({ archive: proposal.archive }))?.header;
684
+ if (!lastBlockHeader) {
685
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
686
+ return;
687
+ }
688
+
689
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
690
+ if (blocks.length === 0) {
691
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
692
+ return;
693
+ }
694
+
695
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
696
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
697
+ await this.blobClient.sendBlobsToFilestore(blobs);
698
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
699
+ ...proposalInfo,
700
+ numBlobs: blobs.length,
701
+ });
702
+ } catch (err) {
703
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
704
+ }
705
+ }
706
+
707
+ private slashInvalidBlock(proposal: BlockProposal) {
708
+ const proposer = proposal.getSender();
709
+
710
+ // Skip if signature is invalid (shouldn't happen since we validate earlier)
711
+ if (!proposer) {
712
+ this.log.warn(`Cannot slash proposal with invalid signature`);
713
+ return;
714
+ }
715
+
716
+ this.proposersOfInvalidBlocks.add(proposer.toString());
717
+
718
+ this.emit(WANT_TO_SLASH_EVENT, [
719
+ {
720
+ validator: proposer,
721
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
722
+ offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
723
+ epochOrSlot: BigInt(proposal.slotNumber),
724
+ },
725
+ ]);
726
+ }
727
+
728
+ private handleInvalidCheckpointProposal(
729
+ proposal: CheckpointProposalCore,
730
+ result: CheckpointProposalValidationFailureResult,
731
+ proposalInfo: LogData,
732
+ ): void {
733
+ if (!SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
734
+ return;
735
+ }
736
+
737
+ // The slot is already marked invalid by the all-nodes checkpoint handler that invokes this callback,
738
+ // so we only emit the proposer slash event here.
739
+ if (this.slashInvalidCheckpointProposal(proposal)) {
740
+ this.log.info(`Detected invalid checkpoint proposal offense`, {
741
+ ...proposalInfo,
742
+ reason: result.reason,
743
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
744
+ offenseType: getOffenseTypeName(OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL),
745
+ });
746
+ }
747
+ }
748
+
749
+ private slashInvalidCheckpointProposal(proposal: CheckpointProposalCore): boolean {
750
+ const proposer = proposal.getSender();
751
+ if (!proposer) {
752
+ this.log.warn(`Cannot slash checkpoint proposal with invalid signature`, {
753
+ slotNumber: proposal.slotNumber,
754
+ archive: proposal.archive.toString(),
755
+ });
756
+ return false;
757
+ }
758
+
759
+ const offenseType = OffenseType.BROADCASTED_INVALID_CHECKPOINT_PROPOSAL;
760
+ const offenseKey = `${proposer.toString()}:${offenseType}:${proposal.slotNumber}`;
761
+ if (!this.invalidCheckpointProposalOffenseKeys.addIfAbsent(offenseKey)) {
762
+ return false;
763
+ }
764
+
765
+ this.emit(WANT_TO_SLASH_EVENT, [
766
+ {
767
+ validator: proposer,
768
+ amount: this.config.slashBroadcastedInvalidCheckpointProposalPenalty,
769
+ offenseType,
770
+ epochOrSlot: BigInt(proposal.slotNumber),
771
+ },
772
+ ]);
773
+ return true;
774
+ }
775
+
776
+ private markInvalidProposalSlot(slotNumber: SlotNumber): void {
777
+ this.proposalHandler.markInvalidProposalSlot(slotNumber);
778
+ }
779
+
780
+ private handleCheckpointAttestation(attestation: CheckpointAttestation): void {
781
+ const slotNumber = attestation.slotNumber;
782
+ if (
783
+ !this.proposalHandler.hasInvalidProposals(slotNumber) ||
784
+ this.proposalHandler.hasProposalEquivocation(slotNumber)
785
+ ) {
786
+ return;
787
+ }
788
+
789
+ const attester = attestation.getSender();
790
+ if (!attester) {
791
+ this.log.warn(`Cannot slash checkpoint attestation with invalid signature`, {
792
+ slotNumber,
793
+ archive: attestation.archive.toString(),
794
+ });
795
+ return;
796
+ }
797
+
798
+ this.slashAttestedToInvalidCheckpointProposal(slotNumber, attester);
799
+ }
800
+
801
+ private slashAttestedToInvalidCheckpointProposal(slotNumber: SlotNumber, attester: EthAddress): void {
802
+ const offenseKey = `${attester.toString()}:${OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL}:${slotNumber}`;
803
+ if (!this.badAttestationOffenseKeys.addIfAbsent(offenseKey)) {
804
+ return;
805
+ }
806
+
807
+ this.log.info(`Detected attestation to invalid checkpoint proposal offense`, {
808
+ attester: attester.toString(),
809
+ slotNumber,
810
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
811
+ offenseType: getOffenseTypeName(OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL),
812
+ });
813
+
814
+ this.emit(WANT_TO_SLASH_EVENT, [
815
+ {
816
+ validator: attester,
817
+ amount: this.config.slashAttestInvalidCheckpointProposalPenalty,
818
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
819
+ epochOrSlot: BigInt(slotNumber),
820
+ },
821
+ ]);
822
+ }
823
+
824
+ /**
825
+ * Handle detection of an oversized block proposal: one whose index within its checkpoint lands at or
826
+ * beyond the consensus per-checkpoint block limit. A single signed proposal at an illegal index is
827
+ * self-contained evidence, so emit an invalid-block-proposal slash event for the proposer, deduped per
828
+ * (proposer, slot) since the p2p layer reports every oversized proposal it stores.
829
+ */
830
+ private handleOversizedProposal(info: OversizedProposalInfo): void {
831
+ const { slot, proposer } = info;
832
+ const offenseType = OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL;
833
+ if (!this.oversizedProposalOffenseKeys.addIfAbsent(`${proposer.toString()}:${offenseType}:${slot}`)) {
834
+ return;
835
+ }
836
+
837
+ this.log.info(`Detected oversized block proposal offense from ${proposer.toString()} at slot ${slot}`, {
838
+ proposer: proposer.toString(),
839
+ slot,
840
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
841
+ offenseType: getOffenseTypeName(offenseType),
842
+ });
843
+
844
+ this.emit(WANT_TO_SLASH_EVENT, [
845
+ {
846
+ validator: proposer,
847
+ amount: this.config.slashBroadcastedInvalidBlockPenalty,
848
+ offenseType,
849
+ epochOrSlot: BigInt(slot),
850
+ },
851
+ ]);
852
+ }
853
+
854
+ /**
855
+ * Handle detection of a duplicate proposal (equivocation).
856
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
857
+ */
858
+ private handleDuplicateProposal(info: DuplicateProposalInfo): void {
859
+ const { slot, proposer, type } = info;
860
+ this.proposalHandler.markProposalEquivocation(slot);
861
+
862
+ this.log.info(`Detected duplicate ${type} proposal offense from ${proposer.toString()} at slot ${slot}`, {
863
+ proposer: proposer.toString(),
864
+ slot,
865
+ type,
866
+ amount: this.config.slashDuplicateProposalPenalty,
867
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_PROPOSAL),
868
+ });
869
+
870
+ this.emit(WANT_TO_SLASH_EVENT, [
871
+ {
872
+ validator: proposer,
873
+ amount: this.config.slashDuplicateProposalPenalty,
874
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
875
+ epochOrSlot: BigInt(slot),
876
+ },
877
+ ]);
878
+
879
+ this.emit(WANT_TO_CLEAR_SLASH_EVENT, [
880
+ {
881
+ offenseType: OffenseType.ATTESTED_TO_INVALID_CHECKPOINT_PROPOSAL,
882
+ epochOrSlot: BigInt(slot),
883
+ },
884
+ ]);
885
+ }
886
+
887
+ /**
888
+ * Handle detection of a duplicate attestation (equivocation).
889
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
890
+ */
891
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
892
+ const { slot, attester } = info;
893
+
894
+ this.log.info(`Detected duplicate attestation offense from ${attester.toString()} at slot ${slot}`, {
895
+ attester: attester.toString(),
896
+ slot,
897
+ amount: this.config.slashDuplicateAttestationPenalty,
898
+ offenseType: getOffenseTypeName(OffenseType.DUPLICATE_ATTESTATION),
899
+ });
900
+
901
+ this.emit(WANT_TO_SLASH_EVENT, [
902
+ {
903
+ validator: attester,
904
+ amount: this.config.slashDuplicateAttestationPenalty,
905
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
906
+ epochOrSlot: BigInt(slot),
907
+ },
908
+ ]);
909
+ }
910
+
911
+ async createBlockProposal(
912
+ blockHeader: BlockHeader,
913
+ checkpointNumber: CheckpointNumber,
914
+ indexWithinCheckpoint: IndexWithinCheckpoint,
915
+ archive: Fr,
916
+ txs: Tx[],
917
+ proposerAddress: EthAddress | undefined,
918
+ options: BlockProposalOptions = {},
919
+ bucketRef?: InboxBucketRef,
920
+ ): Promise<BlockProposal> {
921
+ // Validate that we're not creating a proposal for an older or equal position
922
+ if (this.lastProposedBlock) {
923
+ const lastSlot = this.lastProposedBlock.slotNumber;
924
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
925
+ const newSlot = blockHeader.globalVariables.slotNumber;
926
+
927
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
928
+ throw new Error(
929
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
930
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
931
+ );
932
+ }
933
+ }
934
+
935
+ this.log.info(
936
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
937
+ );
938
+ const newProposal = await this.validationService.createBlockProposal(
939
+ blockHeader,
940
+ checkpointNumber,
941
+ indexWithinCheckpoint,
942
+ archive,
943
+ txs,
944
+ proposerAddress,
945
+ {
946
+ ...options,
947
+ broadcastInvalidBlockProposal:
948
+ options.broadcastInvalidBlockProposal || this.config.broadcastInvalidBlockProposal,
949
+ },
950
+ bucketRef,
951
+ );
952
+ this.lastProposedBlock = newProposal;
953
+ return newProposal;
954
+ }
955
+
956
+ async createCheckpointProposal(
957
+ checkpointHeader: CheckpointHeader,
958
+ archive: Fr,
959
+ checkpointNumber: CheckpointNumber,
960
+ feeAssetPriceModifier: bigint,
961
+ lastBlockProposal: BlockProposal | undefined,
962
+ proposerAddress: EthAddress | undefined,
963
+ options: CheckpointProposalOptions = {},
964
+ ): Promise<CheckpointProposal> {
965
+ // Validate that we're not creating a proposal for an older or equal slot
966
+ if (this.lastProposedCheckpoint) {
967
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
968
+ const newSlot = checkpointHeader.slotNumber;
969
+
970
+ if (newSlot <= lastSlot) {
971
+ throw new Error(
972
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
973
+ `already proposed checkpoint for slot ${lastSlot}`,
974
+ );
975
+ }
976
+ }
977
+
978
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
979
+ const newProposal = await this.validationService.createCheckpointProposal(
980
+ checkpointHeader,
981
+ archive,
982
+ checkpointNumber,
983
+ feeAssetPriceModifier,
984
+ lastBlockProposal,
985
+ proposerAddress,
986
+ options,
987
+ );
988
+ this.lastProposedCheckpoint = newProposal;
989
+ // Self-record this slot's outcome on the re-execution tracker. Proposers don't run their
990
+ // own proposals through `handleCheckpointProposal`, so without this call the proposer's
991
+ // sentinel would see no outcome for slots it proposed and would mis-attribute itself as
992
+ // inactive. We pass the locally-computed `archive` (not `newProposal.archive`, which may
993
+ // be intentionally corrupted under test-only flags); from the proposer's local-view
994
+ // perspective the work it just completed is valid by definition.
995
+ this.proposalHandler.recordOwnCheckpointProposalAsValid(checkpointHeader.slotNumber, archive, checkpointNumber);
996
+ return newProposal;
997
+ }
998
+
999
+ async broadcastBlockProposal(proposal: BlockProposal): Promise<void> {
1000
+ await this.p2pClient.broadcastProposal(proposal);
1001
+ }
1002
+
1003
+ async signAttestationsAndSigners(
1004
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
1005
+ proposer: EthAddress,
1006
+ slot: SlotNumber,
1007
+ checkpointNumber: CheckpointNumber,
1008
+ ): Promise<Signature> {
1009
+ return await this.validationService.signAttestationsAndSigners(
1010
+ attestationsAndSigners,
1011
+ proposer,
1012
+ slot,
1013
+ checkpointNumber,
1014
+ );
1015
+ }
1016
+
1017
+ async collectOwnAttestations(
1018
+ proposal: CheckpointProposal,
1019
+ checkpointNumber: CheckpointNumber,
1020
+ ): Promise<CheckpointAttestation[]> {
1021
+ const slot = proposal.slotNumber;
1022
+ const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
1023
+ this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
1024
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee, checkpointNumber);
1025
+
1026
+ if (!attestations) {
1027
+ return [];
1028
+ }
1029
+
1030
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
1031
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
1032
+ // due to inactivity for missed attestations.
1033
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
1034
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
1035
+ });
1036
+ return attestations;
1037
+ }
1038
+
1039
+ async collectAttestations(
1040
+ proposal: CheckpointProposal,
1041
+ required: number,
1042
+ deadline: Date,
1043
+ checkpointNumber: CheckpointNumber,
1044
+ ): Promise<CheckpointAttestation[]> {
1045
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
1046
+ const slot = proposal.slotNumber;
1047
+ this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
1048
+
1049
+ if (+deadline < this.dateProvider.now()) {
1050
+ this.log.error(
1051
+ `Deadline ${deadline.toISOString()} for collecting ${required} attestations for slot ${slot} is in the past`,
1052
+ );
1053
+ throw new AttestationTimeoutError(0, required, slot);
1054
+ }
1055
+
1056
+ await this.collectOwnAttestations(proposal, checkpointNumber);
1057
+
1058
+ const proposalPayloadHash = proposal.getPayloadHash();
1059
+ const myAddresses = this.getValidatorAddresses();
1060
+
1061
+ let attestations: CheckpointAttestation[] = [];
1062
+ while (true) {
1063
+ // The pool already filters by proposal payload hash; if any attestation slips through with a
1064
+ // mismatched payload hash, drop it defensively. Equivocations are emitted as separate slash
1065
+ // events from libp2p_service.
1066
+ const collectedAttestations = await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
1067
+
1068
+ // Log new attestations we collected
1069
+ const oldSenders = attestations.map(attestation => attestation.getSender());
1070
+ for (const collected of collectedAttestations) {
1071
+ const collectedSender = collected.getSender();
1072
+ // Skip attestations with invalid signatures. Should not happen as we don't add invalid attestations to our pool.
1073
+ if (!collectedSender) {
1074
+ this.log.warn(`Skipping attestation with invalid signature for slot ${slot}`);
1075
+ continue;
1076
+ }
1077
+ if (
1078
+ !myAddresses.some(address => address.equals(collectedSender)) &&
1079
+ !oldSenders.some(sender => sender?.equals(collectedSender))
1080
+ ) {
1081
+ this.log.debug(`Received attestation for slot ${slot} from ${collectedSender.toString()}`);
1082
+ }
1083
+ }
1084
+ attestations = collectedAttestations;
1085
+
1086
+ if (attestations.length >= required) {
1087
+ this.log.verbose(`Collected all ${required} attestations for slot ${slot}`);
1088
+ return attestations;
1089
+ }
1090
+
1091
+ if (+deadline < this.dateProvider.now()) {
1092
+ this.log.error(`Timeout ${deadline.toISOString()} waiting for ${required} attestations for slot ${slot}`);
1093
+ throw new AttestationTimeoutError(attestations.length, required, slot);
1094
+ }
1095
+
1096
+ this.log.debug(`Collected ${attestations.length} of ${required} attestations so far`);
1097
+ await sleep(this.config.attestationPollingIntervalMs);
1098
+ }
1099
+ }
1100
+
1101
+ private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
1102
+ const authRequest = AuthRequest.fromBuffer(msg);
1103
+ const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
1104
+ if (statusMessage === undefined) {
1105
+ return Buffer.alloc(0);
1106
+ }
1107
+
1108
+ // Find a validator address that is in the set
1109
+ const allRegisteredValidators = await this.epochCache.getRegisteredValidators();
1110
+ const addressToUse = this.getValidatorAddresses().find(
1111
+ address => allRegisteredValidators.find(v => v.equals(address)) !== undefined,
1112
+ );
1113
+ if (addressToUse === undefined) {
1114
+ // We don't have a registered address
1115
+ return Buffer.alloc(0);
1116
+ }
1117
+
1118
+ const payloadToSign = authRequest.getPayloadToSign();
1119
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
1120
+ const context: SigningContext = { dutyType: DutyType.AUTH_REQUEST };
1121
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
1122
+ const authResponse = new AuthResponse(statusMessage, signature);
1123
+ return authResponse.toBuffer();
1124
+ }
1125
+ }