@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.001888fc

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