@aztec/validator-client 0.0.1-fake-c83136db25 → 0.0.1-private.d0bedffd

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 (57) hide show
  1. package/README.md +327 -0
  2. package/dest/block_proposal_handler.d.ts +26 -15
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +374 -109
  5. package/dest/checkpoint_builder.d.ts +76 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +228 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +41 -7
  11. package/dest/duties/validation_service.d.ts +42 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +107 -31
  14. package/dest/factory.d.ts +13 -8
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +4 -3
  17. package/dest/index.d.ts +2 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +1 -0
  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 +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +9 -5
  31. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  32. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  33. package/dest/key_store/node_keystore_adapter.js +18 -4
  34. package/dest/key_store/web3signer_key_store.d.ts +10 -11
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +13 -10
  37. package/dest/metrics.d.ts +12 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +52 -34
  40. package/dest/validator.d.ts +77 -22
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +537 -82
  43. package/package.json +24 -14
  44. package/src/block_proposal_handler.ts +298 -87
  45. package/src/checkpoint_builder.ts +390 -0
  46. package/src/config.ts +41 -6
  47. package/src/duties/validation_service.ts +158 -38
  48. package/src/factory.ts +18 -8
  49. package/src/index.ts +1 -0
  50. package/src/key_store/ha_key_store.ts +269 -0
  51. package/src/key_store/index.ts +1 -0
  52. package/src/key_store/interface.ts +44 -5
  53. package/src/key_store/local_key_store.ts +14 -5
  54. package/src/key_store/node_keystore_adapter.ts +28 -5
  55. package/src/key_store/web3signer_key_store.ts +22 -12
  56. package/src/metrics.ts +65 -33
  57. package/src/validator.ts +705 -115
package/src/validator.ts CHANGED
@@ -1,30 +1,63 @@
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';
4
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
5
+ import {
6
+ BlockNumber,
7
+ CheckpointNumber,
8
+ EpochNumber,
9
+ IndexWithinCheckpoint,
10
+ SlotNumber,
11
+ } from '@aztec/foundation/branded-types';
12
+ import { Fr } from '@aztec/foundation/curves/bn254';
13
+ import { TimeoutError } from '@aztec/foundation/error';
2
14
  import type { EthAddress } from '@aztec/foundation/eth-address';
3
15
  import type { Signature } from '@aztec/foundation/eth-signature';
4
- import { Fr } from '@aztec/foundation/fields';
5
- import { type Logger, createLogger } from '@aztec/foundation/log';
16
+ import { type LogData, type Logger, createLogger } from '@aztec/foundation/log';
17
+ import { retryUntil } from '@aztec/foundation/retry';
6
18
  import { RunningPromise } from '@aztec/foundation/running-promise';
7
19
  import { sleep } from '@aztec/foundation/sleep';
8
20
  import { DateProvider } from '@aztec/foundation/timer';
9
21
  import type { KeystoreManager } from '@aztec/node-keystore';
10
- import type { P2P, PeerId, TxProvider } from '@aztec/p2p';
22
+ import type { DuplicateAttestationInfo, DuplicateProposalInfo, P2P, PeerId } from '@aztec/p2p';
11
23
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
12
24
  import { OffenseType, WANT_TO_SLASH_EVENT, type Watcher, type WatcherEmitter } from '@aztec/slasher';
13
25
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
14
- import type { CommitteeAttestationsAndSigners, L2BlockSource } from '@aztec/stdlib/block';
15
- import type { IFullNodeBlockBuilder, Validator, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
16
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
17
- import type { BlockAttestation, BlockProposal, BlockProposalOptions } from '@aztec/stdlib/p2p';
26
+ import type { CommitteeAttestationsAndSigners, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
27
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
28
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
29
+ import type {
30
+ CreateCheckpointProposalLastBlockData,
31
+ ITxProvider,
32
+ Validator,
33
+ ValidatorClientFullConfig,
34
+ WorldStateSynchronizer,
35
+ } from '@aztec/stdlib/interfaces/server';
36
+ import { type L1ToL2MessageSource, accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
37
+ import {
38
+ type BlockProposal,
39
+ type BlockProposalOptions,
40
+ type CheckpointAttestation,
41
+ CheckpointProposal,
42
+ type CheckpointProposalCore,
43
+ type CheckpointProposalOptions,
44
+ } from '@aztec/stdlib/p2p';
18
45
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
19
- import type { StateReference, Tx } from '@aztec/stdlib/tx';
46
+ import type { BlockHeader, CheckpointGlobalVariables, Tx } from '@aztec/stdlib/tx';
20
47
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
21
48
  import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
49
+ import { createHASigner, createLocalSignerWithProtection } from '@aztec/validator-ha-signer/factory';
50
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
51
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
22
52
 
23
53
  import { EventEmitter } from 'events';
24
54
  import type { TypedDataDefinition } from 'viem';
25
55
 
26
56
  import { BlockProposalHandler, type BlockProposalValidationFailureReason } from './block_proposal_handler.js';
57
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
27
58
  import { ValidationService } from './duties/validation_service.js';
59
+ import { HAKeyStore } from './key_store/ha_key_store.js';
60
+ import type { ExtendedValidatorKeyStore } from './key_store/interface.js';
28
61
  import { NodeKeystoreAdapter } from './key_store/node_keystore_adapter.js';
29
62
  import { ValidatorMetrics } from './metrics.js';
30
63
 
@@ -45,36 +78,54 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
45
78
  public readonly tracer: Tracer;
46
79
  private validationService: ValidationService;
47
80
  private metrics: ValidatorMetrics;
48
-
81
+ private log: Logger;
49
82
  // Whether it has already registered handlers on the p2p client
50
83
  private hasRegisteredHandlers = false;
51
84
 
52
- // Used to check if we are sending the same proposal twice
53
- private previousProposal?: BlockProposal;
85
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */
86
+ private lastProposedBlock?: BlockProposal;
87
+
88
+ /** Tracks the last checkpoint proposal we created. */
89
+ private lastProposedCheckpoint?: CheckpointProposal;
54
90
 
55
- private lastEpochForCommitteeUpdateLoop: bigint | undefined;
91
+ private lastEpochForCommitteeUpdateLoop: EpochNumber | undefined;
56
92
  private epochCacheUpdateLoop: RunningPromise;
93
+ /** Tracks the last epoch in which each attester successfully submitted at least one attestation. */
94
+ private lastAttestedEpochByAttester: Map<string, EpochNumber> = new Map();
57
95
 
58
96
  private proposersOfInvalidBlocks: Set<string> = new Set();
59
97
 
98
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */
99
+ private lastAttestedProposal?: CheckpointProposalCore;
100
+
60
101
  protected constructor(
61
- private keyStore: NodeKeystoreAdapter,
102
+ private keyStore: ExtendedValidatorKeyStore,
62
103
  private epochCache: EpochCache,
63
104
  private p2pClient: P2P,
64
105
  private blockProposalHandler: BlockProposalHandler,
106
+ private blockSource: L2BlockSource,
107
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
108
+ private worldState: WorldStateSynchronizer,
109
+ private l1ToL2MessageSource: L1ToL2MessageSource,
65
110
  private config: ValidatorClientFullConfig,
111
+ private blobClient: BlobClientInterface,
112
+ private slashingProtectionSigner: ValidatorHASigner,
66
113
  private dateProvider: DateProvider = new DateProvider(),
67
114
  telemetry: TelemetryClient = getTelemetryClient(),
68
- private log = createLogger('validator'),
115
+ log = createLogger('validator'),
69
116
  ) {
70
117
  super();
118
+
119
+ // Create child logger with fisherman prefix if in fisherman mode
120
+ this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
121
+
71
122
  this.tracer = telemetry.getTracer('Validator');
72
123
  this.metrics = new ValidatorMetrics(telemetry);
73
124
 
74
- this.validationService = new ValidationService(keyStore, log.createChild('validation-service'));
125
+ this.validationService = new ValidationService(keyStore, this.log.createChild('validation-service'));
75
126
 
76
127
  // Refresh epoch cache every second to trigger alert if participation in committee changes
77
- this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), log, 1000);
128
+ this.epochCacheUpdateLoop = new RunningPromise(this.handleEpochCommitteeUpdate.bind(this), this.log, 1000);
78
129
 
79
130
  const myAddresses = this.getValidatorAddresses();
80
131
  this.log.verbose(`Initialized validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
@@ -112,6 +163,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
112
163
  this.log.trace(`No committee found for slot`);
113
164
  return;
114
165
  }
166
+ this.metrics.setCurrentEpoch(epoch);
115
167
  if (epoch !== this.lastEpochForCommitteeUpdateLoop) {
116
168
  const me = this.getValidatorAddresses();
117
169
  const committeeSet = new Set(committee.map(v => v.toString()));
@@ -132,40 +184,74 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
132
184
  }
133
185
  }
134
186
 
135
- static new(
187
+ static async new(
136
188
  config: ValidatorClientFullConfig,
137
- blockBuilder: IFullNodeBlockBuilder,
189
+ checkpointsBuilder: FullNodeCheckpointsBuilder,
190
+ worldState: WorldStateSynchronizer,
138
191
  epochCache: EpochCache,
139
192
  p2pClient: P2P,
140
- blockSource: L2BlockSource,
193
+ blockSource: L2BlockSource & L2BlockSink,
141
194
  l1ToL2MessageSource: L1ToL2MessageSource,
142
- txProvider: TxProvider,
195
+ txProvider: ITxProvider,
143
196
  keyStoreManager: KeystoreManager,
197
+ blobClient: BlobClientInterface,
144
198
  dateProvider: DateProvider = new DateProvider(),
145
199
  telemetry: TelemetryClient = getTelemetryClient(),
146
200
  ) {
147
201
  const metrics = new ValidatorMetrics(telemetry);
148
202
  const blockProposalValidator = new BlockProposalValidator(epochCache, {
149
203
  txsPermitted: !config.disableTransactions,
204
+ maxTxsPerBlock: config.validateMaxTxsPerBlock,
150
205
  });
151
206
  const blockProposalHandler = new BlockProposalHandler(
152
- blockBuilder,
207
+ checkpointsBuilder,
208
+ worldState,
153
209
  blockSource,
154
210
  l1ToL2MessageSource,
155
211
  txProvider,
156
212
  blockProposalValidator,
213
+ epochCache,
157
214
  config,
158
215
  metrics,
159
216
  dateProvider,
160
217
  telemetry,
161
218
  );
162
219
 
220
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
221
+ let slashingProtectionSigner: ValidatorHASigner;
222
+ if (config.haSigningEnabled) {
223
+ // Multi-node HA mode: use PostgreSQL-backed distributed locking.
224
+ // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
225
+ const haConfig = {
226
+ ...config,
227
+ maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000,
228
+ };
229
+ ({ signer: slashingProtectionSigner } = await createHASigner(haConfig, {
230
+ telemetryClient: telemetry,
231
+ dateProvider,
232
+ }));
233
+ } else {
234
+ // Single-node mode: use LMDB-backed local signing protection.
235
+ // This prevents double-signing if the node crashes and restarts mid-proposal.
236
+ ({ signer: slashingProtectionSigner } = await createLocalSignerWithProtection(config, {
237
+ telemetryClient: telemetry,
238
+ dateProvider,
239
+ }));
240
+ }
241
+ const validatorKeyStore: ExtendedValidatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, slashingProtectionSigner);
242
+
163
243
  const validator = new ValidatorClient(
164
- NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager),
244
+ validatorKeyStore,
165
245
  epochCache,
166
246
  p2pClient,
167
247
  blockProposalHandler,
248
+ blockSource,
249
+ checkpointsBuilder,
250
+ worldState,
251
+ l1ToL2MessageSource,
168
252
  config,
253
+ blobClient,
254
+ slashingProtectionSigner,
169
255
  dateProvider,
170
256
  telemetry,
171
257
  );
@@ -183,18 +269,8 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
183
269
  return this.blockProposalHandler;
184
270
  }
185
271
 
186
- // Proxy method for backwards compatibility with tests
187
- public reExecuteTransactions(
188
- proposal: BlockProposal,
189
- blockNumber: number,
190
- txs: any[],
191
- l1ToL2Messages: Fr[],
192
- ): Promise<any> {
193
- return this.blockProposalHandler.reexecuteTransactions(proposal, blockNumber, txs, l1ToL2Messages);
194
- }
195
-
196
- public signWithAddress(addr: EthAddress, msg: TypedDataDefinition) {
197
- return this.keyStore.signTypedDataWithAddress(addr, msg);
272
+ public signWithAddress(addr: EthAddress, msg: TypedDataDefinition, context: SigningContext) {
273
+ return this.keyStore.signTypedDataWithAddress(addr, msg, context);
198
274
  }
199
275
 
200
276
  public getCoinbaseForAttestor(attestor: EthAddress): EthAddress {
@@ -213,24 +289,27 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
213
289
  this.config = { ...this.config, ...config };
214
290
  }
215
291
 
292
+ public reloadKeystore(newManager: KeystoreManager): void {
293
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
294
+ this.keyStore = new HAKeyStore(newAdapter, this.slashingProtectionSigner);
295
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
296
+ }
297
+
216
298
  public async start() {
217
299
  if (this.epochCacheUpdateLoop.isRunning()) {
218
300
  this.log.warn(`Validator client already started`);
219
301
  return;
220
302
  }
221
303
 
304
+ await this.keyStore.start();
305
+
222
306
  await this.registerHandlers();
223
307
 
224
308
  const myAddresses = this.getValidatorAddresses();
225
309
  const inCommittee = await this.epochCache.filterInCommittee('now', myAddresses);
310
+ this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
226
311
  if (inCommittee.length > 0) {
227
- this.log.info(
228
- `Started validator with addresses in current validator committee: ${inCommittee
229
- .map(a => a.toString())
230
- .join(', ')}`,
231
- );
232
- } else {
233
- this.log.info(`Started validator with addresses: ${myAddresses.map(a => a.toString()).join(', ')}`);
312
+ this.log.info(`Addresses in current validator committee: ${inCommittee.map(a => a.toString()).join(', ')}`);
234
313
  }
235
314
  this.epochCacheUpdateLoop.start();
236
315
 
@@ -239,6 +318,7 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
239
318
 
240
319
  public async stop() {
241
320
  await this.epochCacheUpdateLoop.stop();
321
+ await this.keyStore.stop();
242
322
  }
243
323
 
244
324
  /** Register handlers on the p2p client */
@@ -247,9 +327,29 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
247
327
  this.hasRegisteredHandlers = true;
248
328
  this.log.debug(`Registering validator handlers for p2p client`);
249
329
 
250
- const handler = (block: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> =>
251
- this.attestToProposal(block, proposalSender);
252
- this.p2pClient.registerBlockProposalHandler(handler);
330
+ // Block proposal handler - validates but does NOT attest (validators only attest to checkpoints)
331
+ const blockHandler = (block: BlockProposal, proposalSender: PeerId): Promise<boolean> =>
332
+ this.validateBlockProposal(block, proposalSender);
333
+ this.p2pClient.registerBlockProposalHandler(blockHandler);
334
+
335
+ // Checkpoint proposal handler - validates and creates attestations
336
+ // The checkpoint is received as CheckpointProposalCore since the lastBlock is extracted
337
+ // and processed separately via the block handler above.
338
+ const checkpointHandler = (
339
+ checkpoint: CheckpointProposalCore,
340
+ proposalSender: PeerId,
341
+ ): Promise<CheckpointAttestation[] | undefined> => this.attestToCheckpointProposal(checkpoint, proposalSender);
342
+ this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
343
+
344
+ // Duplicate proposal handler - triggers slashing for equivocation
345
+ this.p2pClient.registerDuplicateProposalCallback((info: DuplicateProposalInfo) => {
346
+ this.handleDuplicateProposal(info);
347
+ });
348
+
349
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
350
+ this.p2pClient.registerDuplicateAttestationCallback((info: DuplicateAttestationInfo) => {
351
+ this.handleDuplicateAttestation(info);
352
+ });
253
353
 
254
354
  const myAddresses = this.getValidatorAddresses();
255
355
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
@@ -258,65 +358,86 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
258
358
  }
259
359
  }
260
360
 
261
- async attestToProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<BlockAttestation[] | undefined> {
262
- const slotNumber = proposal.slotNumber.toBigInt();
361
+ /**
362
+ * Validate a block proposal from a peer.
363
+ * Note: Validators do NOT attest to individual blocks - attestations are only for checkpoint proposals.
364
+ * @returns true if the proposal is valid, false otherwise
365
+ */
366
+ async validateBlockProposal(proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> {
367
+ const slotNumber = proposal.slotNumber;
368
+
369
+ // Note: During escape hatch, we still want to "validate" proposals for observability,
370
+ // but we intentionally reject them and disable slashing invalid block and attestation flow.
371
+ const escapeHatchOpen = await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber);
372
+
263
373
  const proposer = proposal.getSender();
264
374
 
265
375
  // Reject proposals with invalid signatures
266
376
  if (!proposer) {
267
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
268
- return undefined;
377
+ this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
378
+ return false;
269
379
  }
270
380
 
271
- // Check that I have any address in current committee before attesting
381
+ // Ignore proposals from ourselves (may happen in HA setups)
382
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
383
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
384
+ proposer: proposer.toString(),
385
+ slotNumber,
386
+ });
387
+ return false;
388
+ }
389
+
390
+ // Check if we're in the committee (for metrics purposes)
272
391
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
273
392
  const partOfCommittee = inCommittee.length > 0;
274
393
 
275
394
  const proposalInfo = { ...proposal.toBlockInfo(), proposer: proposer.toString() };
276
- this.log.info(`Received proposal for slot ${slotNumber}`, {
395
+ this.log.info(`Received block proposal for slot ${slotNumber}`, {
277
396
  ...proposalInfo,
278
397
  txHashes: proposal.txHashes.map(t => t.toString()),
398
+ fishermanMode: this.config.fishermanMode || false,
279
399
  });
280
400
 
281
- // Reexecute txs if we are part of the committee so we can attest, or if slashing is enabled so we can slash
282
- // invalid proposals even when not in the committee, or if we are configured to always reexecute for monitoring purposes.
283
- const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals } = this.config;
401
+ // Reexecute txs if we are part of the committee, or if slashing is enabled, or if we are configured to always reexecute.
402
+ // In fisherman mode, we always reexecute to validate proposals.
403
+ const { validatorReexecute, slashBroadcastedInvalidBlockPenalty, alwaysReexecuteBlockProposals, fishermanMode } =
404
+ this.config;
284
405
  const shouldReexecute =
406
+ fishermanMode ||
285
407
  (slashBroadcastedInvalidBlockPenalty > 0n && validatorReexecute) ||
286
408
  (partOfCommittee && validatorReexecute) ||
287
- alwaysReexecuteBlockProposals;
409
+ alwaysReexecuteBlockProposals ||
410
+ this.blobClient.canUpload();
288
411
 
289
412
  const validationResult = await this.blockProposalHandler.handleBlockProposal(
290
413
  proposal,
291
414
  proposalSender,
292
- !!shouldReexecute,
415
+ !!shouldReexecute && !escapeHatchOpen,
293
416
  );
294
417
 
295
418
  if (!validationResult.isValid) {
296
- this.log.warn(`Proposal validation failed: ${validationResult.reason}`, proposalInfo);
297
-
298
- // Only track attestation failure metrics if we're actually in the committee
299
- if (partOfCommittee) {
300
- const reason = validationResult.reason || 'unknown';
301
- // Classify failure reason: bad proposal vs node issue
302
- const badProposalReasons: BlockProposalValidationFailureReason[] = [
303
- 'invalid_proposal',
304
- 'state_mismatch',
305
- 'failed_txs',
306
- 'in_hash_mismatch',
307
- 'parent_block_wrong_slot',
308
- ];
309
-
310
- if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
311
- this.metrics.incFailedAttestationsBadProposal(1, reason);
312
- } else {
313
- // Node issues: parent_block_not_found, block_number_already_exists, txs_not_available, timeout, unknown_error
314
- this.metrics.incFailedAttestationsNodeIssue(1, reason);
315
- }
419
+ this.log.warn(`Block proposal validation failed: ${validationResult.reason}`, proposalInfo);
420
+
421
+ const reason = validationResult.reason || 'unknown';
422
+ // Classify failure reason: bad proposal vs node issue
423
+ const badProposalReasons: BlockProposalValidationFailureReason[] = [
424
+ 'invalid_proposal',
425
+ 'state_mismatch',
426
+ 'failed_txs',
427
+ 'in_hash_mismatch',
428
+ 'parent_block_wrong_slot',
429
+ ];
430
+
431
+ if (badProposalReasons.includes(reason as BlockProposalValidationFailureReason)) {
432
+ this.metrics.incFailedAttestationsBadProposal(1, reason, partOfCommittee);
433
+ } else {
434
+ // Node issues so we can't validate
435
+ this.metrics.incFailedAttestationsNodeIssue(1, reason, partOfCommittee);
316
436
  }
317
437
 
318
438
  // Slash invalid block proposals (can happen even when not in committee)
319
439
  if (
440
+ !escapeHatchOpen &&
320
441
  validationResult.reason &&
321
442
  SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(validationResult.reason) &&
322
443
  slashBroadcastedInvalidBlockPenalty > 0n
@@ -324,21 +445,383 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
324
445
  this.log.warn(`Slashing proposer for invalid block proposal`, proposalInfo);
325
446
  this.slashInvalidBlock(proposal);
326
447
  }
448
+ return false;
449
+ }
450
+
451
+ this.log.info(`Validated block proposal for slot ${slotNumber}`, {
452
+ ...proposalInfo,
453
+ inCommittee: partOfCommittee,
454
+ fishermanMode: this.config.fishermanMode || false,
455
+ escapeHatchOpen,
456
+ });
457
+
458
+ if (escapeHatchOpen) {
459
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
460
+ return false;
461
+ }
462
+
463
+ return true;
464
+ }
465
+
466
+ /**
467
+ * Validate and attest to a checkpoint proposal from a peer.
468
+ * The proposal is received as CheckpointProposalCore (without lastBlock) since
469
+ * the lastBlock is extracted and processed separately via the block handler.
470
+ * @returns Checkpoint attestations if valid, undefined otherwise
471
+ */
472
+ async attestToCheckpointProposal(
473
+ proposal: CheckpointProposalCore,
474
+ _proposalSender: PeerId,
475
+ ): Promise<CheckpointAttestation[] | undefined> {
476
+ const slotNumber = proposal.slotNumber;
477
+ const proposer = proposal.getSender();
478
+
479
+ // If escape hatch is open for this slot's epoch, do not attest.
480
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
481
+ this.log.warn(`Escape hatch open for slot ${slotNumber}, skipping checkpoint attestation handling`);
482
+ return undefined;
483
+ }
484
+
485
+ // Reject proposals with invalid signatures
486
+ if (!proposer) {
487
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
488
+ return undefined;
489
+ }
490
+
491
+ // Ignore proposals from ourselves (may happen in HA setups)
492
+ if (this.getValidatorAddresses().some(addr => addr.equals(proposer))) {
493
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
494
+ proposer: proposer.toString(),
495
+ slotNumber,
496
+ });
497
+ return undefined;
498
+ }
499
+
500
+ // Validate fee asset price modifier is within allowed range
501
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
502
+ this.log.warn(
503
+ `Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`,
504
+ );
327
505
  return undefined;
328
506
  }
329
507
 
330
508
  // Check that I have any address in current committee before attesting
331
- if (!partOfCommittee) {
509
+ const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
510
+ const partOfCommittee = inCommittee.length > 0;
511
+
512
+ const proposalInfo = {
513
+ slotNumber,
514
+ archive: proposal.archive.toString(),
515
+ proposer: proposer.toString(),
516
+ };
517
+ this.log.info(`Received checkpoint proposal for slot ${slotNumber}`, {
518
+ ...proposalInfo,
519
+ fishermanMode: this.config.fishermanMode || false,
520
+ });
521
+
522
+ // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
523
+ if (this.config.skipCheckpointProposalValidation) {
524
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
525
+ } else {
526
+ const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
527
+ if (!validationResult.isValid) {
528
+ this.log.warn(`Checkpoint proposal validation failed: ${validationResult.reason}`, proposalInfo);
529
+ return undefined;
530
+ }
531
+ }
532
+
533
+ // Upload blobs to filestore if we can (fire and forget)
534
+ if (this.blobClient.canUpload()) {
535
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
536
+ }
537
+
538
+ // Check that I have any address in current committee before attesting
539
+ // In fisherman mode, we still create attestations for validation even if not in committee
540
+ if (!partOfCommittee && !this.config.fishermanMode) {
332
541
  this.log.verbose(`No validator in the current committee, skipping attestation`, proposalInfo);
333
542
  return undefined;
334
543
  }
335
544
 
336
545
  // Provided all of the above checks pass, we can attest to the proposal
337
- this.log.info(`Attesting to proposal for slot ${slotNumber}`, proposalInfo);
546
+ this.log.info(`${partOfCommittee ? 'Attesting to' : 'Validated'} checkpoint proposal for slot ${slotNumber}`, {
547
+ ...proposalInfo,
548
+ inCommittee: partOfCommittee,
549
+ fishermanMode: this.config.fishermanMode || false,
550
+ });
551
+
338
552
  this.metrics.incSuccessfulAttestations(inCommittee.length);
339
553
 
340
- // If the above function does not throw an error, then we can attest to the proposal
341
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
554
+ // Track epoch participation per attester: count each (attester, epoch) pair at most once
555
+ const proposalEpoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
556
+ for (const attester of inCommittee) {
557
+ const key = attester.toString();
558
+ const lastEpoch = this.lastAttestedEpochByAttester.get(key);
559
+ if (lastEpoch === undefined || proposalEpoch > lastEpoch) {
560
+ this.lastAttestedEpochByAttester.set(key, proposalEpoch);
561
+ this.metrics.incAttestedEpochCount(attester);
562
+ }
563
+ }
564
+
565
+ // Determine which validators should attest
566
+ let attestors: EthAddress[];
567
+ if (partOfCommittee) {
568
+ attestors = inCommittee;
569
+ } else if (this.config.fishermanMode) {
570
+ // In fisherman mode, create attestations for validation purposes even if not in committee. These won't be broadcast.
571
+ attestors = this.getValidatorAddresses();
572
+ } else {
573
+ attestors = [];
574
+ }
575
+
576
+ // Only create attestations if we have attestors
577
+ if (attestors.length === 0) {
578
+ return undefined;
579
+ }
580
+
581
+ if (this.config.fishermanMode) {
582
+ // bail out early and don't save attestations to the pool in fisherman mode
583
+ this.log.info(`Creating checkpoint attestations for slot ${slotNumber}`, {
584
+ ...proposalInfo,
585
+ attestors: attestors.map(a => a.toString()),
586
+ });
587
+ return undefined;
588
+ }
589
+
590
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
591
+ }
592
+
593
+ /**
594
+ * Checks if we should attest to a slot based on equivocation prevention rules.
595
+ * @returns true if we should attest, false if we should skip
596
+ */
597
+ private shouldAttestToSlot(slotNumber: SlotNumber): boolean {
598
+ // If attestToEquivocatedProposals is true, always allow
599
+ if (this.config.attestToEquivocatedProposals) {
600
+ return true;
601
+ }
602
+
603
+ // Check if incoming slot is strictly greater than last attested
604
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
605
+ this.log.warn(
606
+ `Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`,
607
+ );
608
+ return false;
609
+ }
610
+
611
+ return true;
612
+ }
613
+
614
+ private async createCheckpointAttestationsFromProposal(
615
+ proposal: CheckpointProposalCore,
616
+ attestors: EthAddress[] = [],
617
+ ): Promise<CheckpointAttestation[] | undefined> {
618
+ // Equivocation check: must happen right before signing to minimize the race window
619
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
620
+ return undefined;
621
+ }
622
+
623
+ const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
624
+
625
+ // Track the proposal we attested to (to prevent equivocation)
626
+ this.lastAttestedProposal = proposal;
627
+
628
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
629
+ return attestations;
630
+ }
631
+
632
+ /**
633
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
634
+ * @returns Validation result with isValid flag and reason if invalid.
635
+ */
636
+ private async validateCheckpointProposal(
637
+ proposal: CheckpointProposalCore,
638
+ proposalInfo: LogData,
639
+ ): Promise<{ isValid: true } | { isValid: false; reason: string }> {
640
+ const slot = proposal.slotNumber;
641
+
642
+ // Timeout block syncing at the start of the next slot
643
+ const config = this.checkpointsBuilder.getConfig();
644
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
645
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
646
+
647
+ // Wait for last block to sync by archive
648
+ let lastBlockHeader: BlockHeader | undefined;
649
+ try {
650
+ lastBlockHeader = await retryUntil(
651
+ async () => {
652
+ await this.blockSource.syncImmediate();
653
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
654
+ },
655
+ `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
656
+ timeoutSeconds,
657
+ 0.5,
658
+ );
659
+ } catch (err) {
660
+ if (err instanceof TimeoutError) {
661
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
662
+ return { isValid: false, reason: 'last_block_not_found' };
663
+ }
664
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
665
+ return { isValid: false, reason: 'block_fetch_error' };
666
+ }
667
+
668
+ if (!lastBlockHeader) {
669
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
670
+ return { isValid: false, reason: 'last_block_not_found' };
671
+ }
672
+
673
+ // Get all full blocks for the slot and checkpoint
674
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
675
+ if (blocks.length === 0) {
676
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
677
+ return { isValid: false, reason: 'no_blocks_for_slot' };
678
+ }
679
+
680
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
681
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
682
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
683
+ return { isValid: false, reason: 'last_block_archive_mismatch' };
684
+ }
685
+
686
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
687
+ ...proposalInfo,
688
+ blockNumbers: blocks.map(b => b.number),
689
+ });
690
+
691
+ // Get checkpoint constants from first block
692
+ const firstBlock = blocks[0];
693
+ const constants = this.extractCheckpointConstants(firstBlock);
694
+ const checkpointNumber = firstBlock.checkpointNumber;
695
+
696
+ // Get L1-to-L2 messages for this checkpoint
697
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
698
+
699
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
700
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
701
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
702
+ .filter(c => c.checkpointNumber < checkpointNumber)
703
+ .map(c => c.checkpointOutHash);
704
+
705
+ // Fork world state at the block before the first block
706
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
707
+ const fork = await this.worldState.fork(parentBlockNumber);
708
+
709
+ try {
710
+ // Create checkpoint builder with all existing blocks
711
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
712
+ checkpointNumber,
713
+ constants,
714
+ proposal.feeAssetPriceModifier,
715
+ l1ToL2Messages,
716
+ previousCheckpointOutHashes,
717
+ fork,
718
+ blocks,
719
+ this.log.getBindings(),
720
+ );
721
+
722
+ // Complete the checkpoint to get computed values
723
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
724
+
725
+ // Compare checkpoint header with proposal
726
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
727
+ this.log.warn(`Checkpoint header mismatch`, {
728
+ ...proposalInfo,
729
+ computed: computedCheckpoint.header.toInspect(),
730
+ proposal: proposal.checkpointHeader.toInspect(),
731
+ });
732
+ return { isValid: false, reason: 'checkpoint_header_mismatch' };
733
+ }
734
+
735
+ // Compare archive root with proposal
736
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
737
+ this.log.warn(`Archive root mismatch`, {
738
+ ...proposalInfo,
739
+ computed: computedCheckpoint.archive.root.toString(),
740
+ proposal: proposal.archive.toString(),
741
+ });
742
+ return { isValid: false, reason: 'archive_mismatch' };
743
+ }
744
+
745
+ // Check that the accumulated epoch out hash matches the value in the proposal.
746
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
747
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
748
+ const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
749
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
750
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
751
+ this.log.warn(`Epoch out hash mismatch`, {
752
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
753
+ computedEpochOutHash: computedEpochOutHash.toString(),
754
+ checkpointOutHash: checkpointOutHash.toString(),
755
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
756
+ ...proposalInfo,
757
+ });
758
+ return { isValid: false, reason: 'out_hash_mismatch' };
759
+ }
760
+
761
+ // Final round of validations on the checkpoint, just in case.
762
+ try {
763
+ validateCheckpoint(computedCheckpoint, {
764
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
765
+ maxDABlockGas: this.config.validateMaxDABlockGas,
766
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
767
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
768
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint,
769
+ });
770
+ } catch (err) {
771
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
772
+ return { isValid: false, reason: 'checkpoint_validation_failed' };
773
+ }
774
+
775
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
776
+ return { isValid: true };
777
+ } finally {
778
+ await fork.close();
779
+ }
780
+ }
781
+
782
+ /**
783
+ * Extract checkpoint global variables from a block.
784
+ */
785
+ private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
786
+ const gv = block.header.globalVariables;
787
+ return {
788
+ chainId: gv.chainId,
789
+ version: gv.version,
790
+ slotNumber: gv.slotNumber,
791
+ timestamp: gv.timestamp,
792
+ coinbase: gv.coinbase,
793
+ feeRecipient: gv.feeRecipient,
794
+ gasFees: gv.gasFees,
795
+ };
796
+ }
797
+
798
+ /**
799
+ * Uploads blobs for a checkpoint to the filestore (fire and forget).
800
+ */
801
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
802
+ try {
803
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
804
+ if (!lastBlockHeader) {
805
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
806
+ return;
807
+ }
808
+
809
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
810
+ if (blocks.length === 0) {
811
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
812
+ return;
813
+ }
814
+
815
+ const blobFields = blocks.flatMap(b => b.toBlobFields());
816
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
817
+ await this.blobClient.sendBlobsToFilestore(blobs);
818
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
819
+ ...proposalInfo,
820
+ numBlobs: blobs.length,
821
+ });
822
+ } catch (err) {
823
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
824
+ }
342
825
  }
343
826
 
344
827
  private slashInvalidBlock(proposal: BlockProposal) {
@@ -363,34 +846,130 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
363
846
  validator: proposer,
364
847
  amount: this.config.slashBroadcastedInvalidBlockPenalty,
365
848
  offenseType: OffenseType.BROADCASTED_INVALID_BLOCK_PROPOSAL,
366
- epochOrSlot: proposal.slotNumber.toBigInt(),
849
+ epochOrSlot: BigInt(proposal.slotNumber),
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
+
861
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
862
+ proposer: proposer.toString(),
863
+ slot,
864
+ type,
865
+ });
866
+
867
+ // Emit slash event
868
+ this.emit(WANT_TO_SLASH_EVENT, [
869
+ {
870
+ validator: proposer,
871
+ amount: this.config.slashDuplicateProposalPenalty,
872
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
873
+ epochOrSlot: BigInt(slot),
874
+ },
875
+ ]);
876
+ }
877
+
878
+ /**
879
+ * Handle detection of a duplicate attestation (equivocation).
880
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
881
+ */
882
+ private handleDuplicateAttestation(info: DuplicateAttestationInfo): void {
883
+ const { slot, attester } = info;
884
+
885
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
886
+ attester: attester.toString(),
887
+ slot,
888
+ });
889
+
890
+ this.emit(WANT_TO_SLASH_EVENT, [
891
+ {
892
+ validator: attester,
893
+ amount: this.config.slashDuplicateAttestationPenalty,
894
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
895
+ epochOrSlot: BigInt(slot),
367
896
  },
368
897
  ]);
369
898
  }
370
899
 
371
900
  async createBlockProposal(
372
- blockNumber: number,
373
- header: CheckpointHeader,
901
+ blockHeader: BlockHeader,
902
+ indexWithinCheckpoint: IndexWithinCheckpoint,
903
+ inHash: Fr,
374
904
  archive: Fr,
375
- stateReference: StateReference,
376
905
  txs: Tx[],
377
906
  proposerAddress: EthAddress | undefined,
378
- options: BlockProposalOptions,
379
- ): Promise<BlockProposal | undefined> {
380
- if (this.previousProposal?.slotNumber.equals(header.slotNumber)) {
381
- this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
382
- return Promise.resolve(undefined);
907
+ options: BlockProposalOptions = {},
908
+ ): Promise<BlockProposal> {
909
+ // Validate that we're not creating a proposal for an older or equal position
910
+ if (this.lastProposedBlock) {
911
+ const lastSlot = this.lastProposedBlock.slotNumber;
912
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
913
+ const newSlot = blockHeader.globalVariables.slotNumber;
914
+
915
+ if (newSlot < lastSlot || (newSlot === lastSlot && indexWithinCheckpoint <= lastIndex)) {
916
+ throw new Error(
917
+ `Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` +
918
+ `already proposed block for slot ${lastSlot} index ${lastIndex}`,
919
+ );
920
+ }
383
921
  }
384
922
 
923
+ this.log.info(
924
+ `Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`,
925
+ );
385
926
  const newProposal = await this.validationService.createBlockProposal(
386
- header,
927
+ blockHeader,
928
+ indexWithinCheckpoint,
929
+ inHash,
387
930
  archive,
388
- stateReference,
389
931
  txs,
390
932
  proposerAddress,
391
- { ...options, broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal },
933
+ {
934
+ ...options,
935
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal,
936
+ },
937
+ );
938
+ this.lastProposedBlock = newProposal;
939
+ return newProposal;
940
+ }
941
+
942
+ async createCheckpointProposal(
943
+ checkpointHeader: CheckpointHeader,
944
+ archive: Fr,
945
+ feeAssetPriceModifier: bigint,
946
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
947
+ proposerAddress: EthAddress | undefined,
948
+ options: CheckpointProposalOptions = {},
949
+ ): Promise<CheckpointProposal> {
950
+ // Validate that we're not creating a proposal for an older or equal slot
951
+ if (this.lastProposedCheckpoint) {
952
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
953
+ const newSlot = checkpointHeader.slotNumber;
954
+
955
+ if (newSlot <= lastSlot) {
956
+ throw new Error(
957
+ `Cannot create checkpoint proposal for slot ${newSlot}: ` +
958
+ `already proposed checkpoint for slot ${lastSlot}`,
959
+ );
960
+ }
961
+ }
962
+
963
+ this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
964
+ const newProposal = await this.validationService.createCheckpointProposal(
965
+ checkpointHeader,
966
+ archive,
967
+ feeAssetPriceModifier,
968
+ lastBlockInfo,
969
+ proposerAddress,
970
+ options,
392
971
  );
393
- this.previousProposal = newProposal;
972
+ this.lastProposedCheckpoint = newProposal;
394
973
  return newProposal;
395
974
  }
396
975
 
@@ -401,20 +980,38 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
401
980
  async signAttestationsAndSigners(
402
981
  attestationsAndSigners: CommitteeAttestationsAndSigners,
403
982
  proposer: EthAddress,
983
+ slot: SlotNumber,
984
+ blockNumber: BlockNumber | CheckpointNumber,
404
985
  ): Promise<Signature> {
405
- return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer);
986
+ return await this.validationService.signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber);
406
987
  }
407
988
 
408
- async collectOwnAttestations(proposal: BlockProposal): Promise<BlockAttestation[]> {
409
- const slot = proposal.payload.header.slotNumber.toBigInt();
989
+ async collectOwnAttestations(proposal: CheckpointProposal): Promise<CheckpointAttestation[]> {
990
+ const slot = proposal.slotNumber;
410
991
  const inCommittee = await this.epochCache.filterInCommittee(slot, this.getValidatorAddresses());
411
992
  this.log.debug(`Collecting ${inCommittee.length} self-attestations for slot ${slot}`, { inCommittee });
412
- return this.createBlockAttestationsFromProposal(proposal, inCommittee);
993
+ const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
994
+
995
+ if (!attestations) {
996
+ return [];
997
+ }
998
+
999
+ // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
1000
+ // other nodes can see that our validators did attest to this block proposal, and do not slash us
1001
+ // due to inactivity for missed attestations.
1002
+ void this.p2pClient.broadcastCheckpointAttestations(attestations).catch(err => {
1003
+ this.log.error(`Failed to broadcast self-attestations for slot ${slot}`, err);
1004
+ });
1005
+ return attestations;
413
1006
  }
414
1007
 
415
- async collectAttestations(proposal: BlockProposal, required: number, deadline: Date): Promise<BlockAttestation[]> {
416
- // Wait and poll the p2pClient's attestation pool for this block until we have enough attestations
417
- const slot = proposal.payload.header.slotNumber.toBigInt();
1008
+ async collectAttestations(
1009
+ proposal: CheckpointProposal,
1010
+ required: number,
1011
+ deadline: Date,
1012
+ ): Promise<CheckpointAttestation[]> {
1013
+ // Wait and poll the p2pClient's attestation pool for this checkpoint until we have enough attestations
1014
+ const slot = proposal.slotNumber;
418
1015
  this.log.debug(`Collecting ${required} attestations for slot ${slot} with deadline ${deadline.toISOString()}`);
419
1016
 
420
1017
  if (+deadline < this.dateProvider.now()) {
@@ -429,16 +1026,16 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
429
1026
  const proposalId = proposal.archive.toString();
430
1027
  const myAddresses = this.getValidatorAddresses();
431
1028
 
432
- let attestations: BlockAttestation[] = [];
1029
+ let attestations: CheckpointAttestation[] = [];
433
1030
  while (true) {
434
- // Filter out attestations with a mismatching payload. This should NOT happen since we have verified
1031
+ // Filter out attestations with a mismatching archive. This should NOT happen since we have verified
435
1032
  // the proposer signature (ie our own) before accepting the attestation into the pool via the p2p client.
436
- const collectedAttestations = (await this.p2pClient.getAttestationsForSlot(slot, proposalId)).filter(
1033
+ const collectedAttestations = (await this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalId)).filter(
437
1034
  attestation => {
438
- if (!attestation.payload.equals(proposal.payload)) {
1035
+ if (!attestation.archive.equals(proposal.archive)) {
439
1036
  this.log.warn(
440
- `Received attestation for slot ${slot} with mismatched payload from ${attestation.getSender()?.toString()}`,
441
- { attestationPayload: attestation.payload, proposalPayload: proposal.payload },
1037
+ `Received attestation for slot ${slot} with mismatched archive from ${attestation.getSender()?.toString()}`,
1038
+ { attestationArchive: attestation.archive.toString(), proposalArchive: proposal.archive.toString() },
442
1039
  );
443
1040
  return false;
444
1041
  }
@@ -479,15 +1076,6 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
479
1076
  }
480
1077
  }
481
1078
 
482
- private async createBlockAttestationsFromProposal(
483
- proposal: BlockProposal,
484
- attestors: EthAddress[] = [],
485
- ): Promise<BlockAttestation[]> {
486
- const attestations = await this.validationService.attestToProposal(proposal, attestors);
487
- await this.p2pClient.addAttestations(attestations);
488
- return attestations;
489
- }
490
-
491
1079
  private async handleAuthRequest(peer: PeerId, msg: Buffer): Promise<Buffer> {
492
1080
  const authRequest = AuthRequest.fromBuffer(msg);
493
1081
  const statusMessage = await this.p2pClient.handleAuthRequestFromPeer(authRequest, peer).catch(_ => undefined);
@@ -506,7 +1094,9 @@ export class ValidatorClient extends (EventEmitter as new () => WatcherEmitter)
506
1094
  }
507
1095
 
508
1096
  const payloadToSign = authRequest.getPayloadToSign();
509
- const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign);
1097
+ // AUTH_REQUEST doesn't require HA protection - multiple signatures are safe
1098
+ const context: SigningContext = { dutyType: DutyType.AUTH_REQUEST };
1099
+ const signature = await this.keyStore.signMessageWithAddress(addressToUse, payloadToSign, context);
510
1100
  const authResponse = new AuthResponse(statusMessage, signature);
511
1101
  return authResponse.toBuffer();
512
1102
  }