@aztec/validator-client 0.0.1-commit.bf2612ae → 0.0.1-commit.c0b82b2

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 (46) hide show
  1. package/README.md +21 -18
  2. package/dest/block_proposal_handler.d.ts +2 -2
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +20 -34
  5. package/dest/checkpoint_builder.d.ts +13 -11
  6. package/dest/checkpoint_builder.d.ts.map +1 -1
  7. package/dest/checkpoint_builder.js +50 -30
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +7 -4
  11. package/dest/duties/validation_service.d.ts +2 -2
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +3 -3
  14. package/dest/index.d.ts +1 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +0 -1
  17. package/dest/key_store/ha_key_store.d.ts +1 -1
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -1
  19. package/dest/key_store/ha_key_store.js +2 -2
  20. package/dest/metrics.d.ts +4 -3
  21. package/dest/metrics.d.ts.map +1 -1
  22. package/dest/metrics.js +34 -5
  23. package/dest/validator.d.ts +33 -9
  24. package/dest/validator.d.ts.map +1 -1
  25. package/dest/validator.js +167 -44
  26. package/package.json +19 -19
  27. package/src/block_proposal_handler.ts +29 -48
  28. package/src/checkpoint_builder.ts +73 -29
  29. package/src/config.ts +7 -4
  30. package/src/duties/validation_service.ts +9 -2
  31. package/src/index.ts +0 -1
  32. package/src/key_store/ha_key_store.ts +2 -2
  33. package/src/metrics.ts +45 -6
  34. package/src/validator.ts +221 -53
  35. package/dest/tx_validator/index.d.ts +0 -3
  36. package/dest/tx_validator/index.d.ts.map +0 -1
  37. package/dest/tx_validator/index.js +0 -2
  38. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  39. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  40. package/dest/tx_validator/nullifier_cache.js +0 -24
  41. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  42. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  43. package/dest/tx_validator/tx_validator_factory.js +0 -54
  44. package/src/tx_validator/index.ts +0 -2
  45. package/src/tx_validator/nullifier_cache.ts +0 -30
  46. package/src/tx_validator/tx_validator_factory.ts +0 -135
package/dest/validator.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getBlobsPerL1Block } from '@aztec/blob-lib';
2
- import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
3
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
3
4
  import { TimeoutError } from '@aztec/foundation/error';
4
5
  import { createLogger } from '@aztec/foundation/log';
5
6
  import { retryUntil } from '@aztec/foundation/retry';
@@ -8,7 +9,7 @@ import { sleep } from '@aztec/foundation/sleep';
8
9
  import { DateProvider } from '@aztec/foundation/timer';
9
10
  import { AuthRequest, AuthResponse, BlockProposalValidator, ReqRespSubProtocol } from '@aztec/p2p';
10
11
  import { OffenseType, WANT_TO_SLASH_EVENT } from '@aztec/slasher';
11
- import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
12
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
12
13
  import { accumulateCheckpointOutHashes } from '@aztec/stdlib/messaging';
13
14
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
14
15
  import { getTelemetryClient } from '@aztec/telemetry-client';
@@ -41,6 +42,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
41
42
  l1ToL2MessageSource;
42
43
  config;
43
44
  blobClient;
45
+ haSigner;
44
46
  dateProvider;
45
47
  tracer;
46
48
  validationService;
@@ -48,17 +50,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
48
50
  log;
49
51
  // Whether it has already registered handlers on the p2p client
50
52
  hasRegisteredHandlers;
51
- // Used to check if we are sending the same proposal twice
52
- previousProposal;
53
+ /** Tracks the last block proposal we created, to detect duplicate proposal attempts. */ lastProposedBlock;
54
+ /** Tracks the last checkpoint proposal we created. */ lastProposedCheckpoint;
53
55
  lastEpochForCommitteeUpdateLoop;
54
56
  epochCacheUpdateLoop;
55
57
  proposersOfInvalidBlocks;
56
- // TODO(palla/mbps): Remove this once checkpoint validation is stable and we can validate all blocks properly.
57
- // Tracks slots for which we have successfully validated a block proposal, so we can attest to checkpoint proposals for those slots.
58
- // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
59
- validatedBlockSlots;
60
- constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
61
- 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.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set(), this.validatedBlockSlots = new Set();
58
+ /** Tracks the last checkpoint proposal we attested to, to prevent equivocation. */ lastAttestedProposal;
59
+ constructor(keyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, haSigner, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator')){
60
+ 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.haSigner = haSigner, this.dateProvider = dateProvider, this.hasRegisteredHandlers = false, this.proposersOfInvalidBlocks = new Set();
62
61
  // Create child logger with fisherman prefix if in fisherman mode
63
62
  this.log = config.fishermanMode ? log.createChild('[FISHERMAN]') : log;
64
63
  this.tracer = telemetry.getTracer('Validator');
@@ -118,17 +117,23 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
118
117
  txsPermitted: !config.disableTransactions
119
118
  });
120
119
  const blockProposalHandler = new BlockProposalHandler(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider, telemetry);
121
- let validatorKeyStore = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
120
+ const nodeKeystoreAdapter = NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager);
121
+ let validatorKeyStore = nodeKeystoreAdapter;
122
+ let haSigner;
122
123
  if (config.haSigningEnabled) {
123
124
  // If maxStuckDutiesAgeMs is not explicitly set, compute it from Aztec slot duration
124
125
  const haConfig = {
125
126
  ...config,
126
127
  maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs ?? epochCache.getL1Constants().slotDuration * 2 * 1000
127
128
  };
128
- const { signer } = await createHASigner(haConfig);
129
- validatorKeyStore = new HAKeyStore(validatorKeyStore, signer);
129
+ const { signer } = await createHASigner(haConfig, {
130
+ telemetryClient: telemetry,
131
+ dateProvider
132
+ });
133
+ haSigner = signer;
134
+ validatorKeyStore = new HAKeyStore(nodeKeystoreAdapter, signer);
130
135
  }
131
- const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, dateProvider, telemetry);
136
+ const validator = new ValidatorClient(validatorKeyStore, epochCache, p2pClient, blockProposalHandler, blockSource, checkpointsBuilder, worldState, l1ToL2MessageSource, config, blobClient, haSigner, dateProvider, telemetry);
132
137
  return validator;
133
138
  }
134
139
  getValidatorAddresses() {
@@ -155,6 +160,20 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
155
160
  ...config
156
161
  };
157
162
  }
163
+ reloadKeystore(newManager) {
164
+ if (this.config.haSigningEnabled && !this.haSigner) {
165
+ this.log.warn('HA signing is enabled in config but was not initialized at startup. ' + 'Restart the node to enable HA signing.');
166
+ } else if (!this.config.haSigningEnabled && this.haSigner) {
167
+ this.log.warn('HA signing was disabled via config update but the HA signer is still active. ' + 'Restart the node to fully disable HA signing.');
168
+ }
169
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
170
+ if (this.haSigner) {
171
+ this.keyStore = new HAKeyStore(newAdapter, this.haSigner);
172
+ } else {
173
+ this.keyStore = newAdapter;
174
+ }
175
+ this.validationService = new ValidationService(this.keyStore, this.log.createChild('validation-service'));
176
+ }
158
177
  async start() {
159
178
  if (this.epochCacheUpdateLoop.isRunning()) {
160
179
  this.log.warn(`Validator client already started`);
@@ -187,6 +206,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
187
206
  // and processed separately via the block handler above.
188
207
  const checkpointHandler = (checkpoint, proposalSender)=>this.attestToCheckpointProposal(checkpoint, proposalSender);
189
208
  this.p2pClient.registerCheckpointProposalHandler(checkpointHandler);
209
+ // Duplicate proposal handler - triggers slashing for equivocation
210
+ this.p2pClient.registerDuplicateProposalCallback((info)=>{
211
+ this.handleDuplicateProposal(info);
212
+ });
213
+ // Duplicate attestation handler - triggers slashing for attestation equivocation
214
+ this.p2pClient.registerDuplicateAttestationCallback((info)=>{
215
+ this.handleDuplicateAttestation(info);
216
+ });
190
217
  const myAddresses = this.getValidatorAddresses();
191
218
  this.p2pClient.registerThisValidatorAddresses(myAddresses);
192
219
  await this.p2pClient.addReqRespSubProtocol(ReqRespSubProtocol.AUTH, this.handleAuthRequest.bind(this));
@@ -207,6 +234,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
207
234
  this.log.warn(`Received block proposal with invalid signature for slot ${slotNumber}`);
208
235
  return false;
209
236
  }
237
+ // Ignore proposals from ourselves (may happen in HA setups)
238
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
239
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
240
+ proposer: proposer.toString(),
241
+ slotNumber
242
+ });
243
+ return false;
244
+ }
210
245
  // Check if we're in the committee (for metrics purposes)
211
246
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
212
247
  const partOfCommittee = inCommittee.length > 0;
@@ -258,9 +293,6 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
258
293
  this.log.warn(`Escape hatch open for slot ${slotNumber}, rejecting block proposal`, proposalInfo);
259
294
  return false;
260
295
  }
261
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
262
- // Track that we successfully validated a block for this slot, so we can attest to checkpoint proposals for it.
263
- this.validatedBlockSlots.add(slotNumber);
264
296
  return true;
265
297
  }
266
298
  /**
@@ -281,6 +313,19 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
281
313
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${slotNumber}`);
282
314
  return undefined;
283
315
  }
316
+ // Ignore proposals from ourselves (may happen in HA setups)
317
+ if (this.getValidatorAddresses().some((addr)=>addr.equals(proposer))) {
318
+ this.log.warn(`Ignoring block proposal from self for slot ${slotNumber}`, {
319
+ proposer: proposer.toString(),
320
+ slotNumber
321
+ });
322
+ return undefined;
323
+ }
324
+ // Validate fee asset price modifier is within allowed range
325
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
326
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${slotNumber}`);
327
+ return undefined;
328
+ }
284
329
  // Check that I have any address in current committee before attesting
285
330
  const inCommittee = await this.epochCache.filterInCommittee(slotNumber, this.getValidatorAddresses());
286
331
  const partOfCommittee = inCommittee.length > 0;
@@ -295,16 +340,9 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
295
340
  txHashes: proposal.txHashes.map((t)=>t.toString()),
296
341
  fishermanMode: this.config.fishermanMode || false
297
342
  });
298
- // TODO(palla/mbps): Remove this once checkpoint validation is stable.
299
- // Check that we have successfully validated a block for this slot before attesting to the checkpoint.
300
- if (!this.validatedBlockSlots.has(slotNumber)) {
301
- this.log.warn(`No validated block found for slot ${slotNumber}, refusing to attest to checkpoint`, proposalInfo);
302
- return undefined;
303
- }
304
343
  // Validate the checkpoint proposal before attesting (unless skipCheckpointProposalValidation is set)
305
- // TODO(palla/mbps): Change default to false once checkpoint validation is stable.
306
- if (this.config.skipCheckpointProposalValidation !== false) {
307
- this.log.verbose(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
344
+ if (this.config.skipCheckpointProposalValidation) {
345
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${slotNumber}`, proposalInfo);
308
346
  } else {
309
347
  const validationResult = await this.validateCheckpointProposal(proposal, proposalInfo);
310
348
  if (!validationResult.isValid) {
@@ -351,11 +389,32 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
351
389
  });
352
390
  return undefined;
353
391
  }
354
- return this.createCheckpointAttestationsFromProposal(proposal, attestors);
392
+ return await this.createCheckpointAttestationsFromProposal(proposal, attestors);
393
+ }
394
+ /**
395
+ * Checks if we should attest to a slot based on equivocation prevention rules.
396
+ * @returns true if we should attest, false if we should skip
397
+ */ shouldAttestToSlot(slotNumber) {
398
+ // If attestToEquivocatedProposals is true, always allow
399
+ if (this.config.attestToEquivocatedProposals) {
400
+ return true;
401
+ }
402
+ // Check if incoming slot is strictly greater than last attested
403
+ if (this.lastAttestedProposal && slotNumber <= this.lastAttestedProposal.slotNumber) {
404
+ this.log.warn(`Refusing to process a proposal for slot ${slotNumber} given we already attested to a proposal for slot ${this.lastAttestedProposal.slotNumber}`);
405
+ return false;
406
+ }
407
+ return true;
355
408
  }
356
409
  async createCheckpointAttestationsFromProposal(proposal, attestors = []) {
410
+ // Equivocation check: must happen right before signing to minimize the race window
411
+ if (!this.shouldAttestToSlot(proposal.slotNumber)) {
412
+ return undefined;
413
+ }
357
414
  const attestations = await this.validationService.attestToCheckpointProposal(proposal, attestors);
358
- await this.p2pClient.addCheckpointAttestations(attestations);
415
+ // Track the proposal we attested to (to prevent equivocation)
416
+ this.lastAttestedProposal = proposal;
417
+ await this.p2pClient.addOwnCheckpointAttestations(attestations);
359
418
  return attestations;
360
419
  }
361
420
  /**
@@ -363,7 +422,10 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
363
422
  * @returns Validation result with isValid flag and reason if invalid.
364
423
  */ async validateCheckpointProposal(proposal, proposalInfo) {
365
424
  const slot = proposal.slotNumber;
366
- const timeoutSeconds = 10;
425
+ // Timeout block syncing at the start of the next slot
426
+ const config = this.checkpointsBuilder.getConfig();
427
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
428
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
367
429
  // Wait for last block to sync by archive
368
430
  let lastBlockHeader;
369
431
  try {
@@ -401,6 +463,14 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
401
463
  reason: 'no_blocks_for_slot'
402
464
  };
403
465
  }
466
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
467
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
468
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
469
+ return {
470
+ isValid: false,
471
+ reason: 'last_block_archive_mismatch'
472
+ };
473
+ }
404
474
  this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
405
475
  ...proposalInfo,
406
476
  blockNumbers: blocks.map((b)=>b.number)
@@ -411,18 +481,15 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
411
481
  const checkpointNumber = firstBlock.checkpointNumber;
412
482
  // Get L1-to-L2 messages for this checkpoint
413
483
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
414
- // Compute the previous checkpoint out hashes for the epoch.
415
- // TODO: There can be a more efficient way to get the previous checkpoint out hashes without having to fetch the
416
- // actual checkpoints and the blocks/txs in them.
484
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
417
485
  const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
418
- const previousCheckpoints = (await this.blockSource.getCheckpointsForEpoch(epoch)).filter((b)=>b.number < checkpointNumber).sort((a, b)=>a.number - b.number);
419
- const previousCheckpointOutHashes = previousCheckpoints.map((c)=>c.getCheckpointOutHash());
486
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
420
487
  // Fork world state at the block before the first block
421
488
  const parentBlockNumber = BlockNumber(firstBlock.number - 1);
422
489
  const fork = await this.worldState.fork(parentBlockNumber);
423
490
  try {
424
491
  // Create checkpoint builder with all existing blocks
425
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks);
492
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
426
493
  // Complete the checkpoint to get computed values
427
494
  const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
428
495
  // Compare checkpoint header with proposal
@@ -486,6 +553,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
486
553
  chainId: gv.chainId,
487
554
  version: gv.version,
488
555
  slotNumber: gv.slotNumber,
556
+ timestamp: gv.timestamp,
489
557
  coinbase: gv.coinbase,
490
558
  feeRecipient: gv.feeRecipient,
491
559
  gasFees: gv.gasFees
@@ -506,7 +574,7 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
506
574
  return;
507
575
  }
508
576
  const blobFields = blocks.flatMap((b)=>b.toBlobFields());
509
- const blobs = getBlobsPerL1Block(blobFields);
577
+ const blobs = await getBlobsPerL1Block(blobFields);
510
578
  await this.blobClient.sendBlobsToFilestore(blobs);
511
579
  this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
512
580
  ...proposalInfo,
@@ -538,23 +606,75 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
538
606
  }
539
607
  ]);
540
608
  }
609
+ /**
610
+ * Handle detection of a duplicate proposal (equivocation).
611
+ * Emits a slash event when a proposer sends multiple proposals for the same position.
612
+ */ handleDuplicateProposal(info) {
613
+ const { slot, proposer, type } = info;
614
+ this.log.warn(`Triggering slash event for duplicate ${type} proposal from ${proposer.toString()} at slot ${slot}`, {
615
+ proposer: proposer.toString(),
616
+ slot,
617
+ type
618
+ });
619
+ // Emit slash event
620
+ this.emit(WANT_TO_SLASH_EVENT, [
621
+ {
622
+ validator: proposer,
623
+ amount: this.config.slashDuplicateProposalPenalty,
624
+ offenseType: OffenseType.DUPLICATE_PROPOSAL,
625
+ epochOrSlot: BigInt(slot)
626
+ }
627
+ ]);
628
+ }
629
+ /**
630
+ * Handle detection of a duplicate attestation (equivocation).
631
+ * Emits a slash event when an attester signs attestations for different proposals at the same slot.
632
+ */ handleDuplicateAttestation(info) {
633
+ const { slot, attester } = info;
634
+ this.log.warn(`Triggering slash event for duplicate attestation from ${attester.toString()} at slot ${slot}`, {
635
+ attester: attester.toString(),
636
+ slot
637
+ });
638
+ this.emit(WANT_TO_SLASH_EVENT, [
639
+ {
640
+ validator: attester,
641
+ amount: this.config.slashDuplicateAttestationPenalty,
642
+ offenseType: OffenseType.DUPLICATE_ATTESTATION,
643
+ epochOrSlot: BigInt(slot)
644
+ }
645
+ ]);
646
+ }
541
647
  async createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, options = {}) {
542
- // TODO(palla/mbps): Prevent double proposals properly
543
- // if (this.previousProposal?.slotNumber === blockHeader.globalVariables.slotNumber) {
544
- // this.log.verbose(`Already made a proposal for the same slot, skipping proposal`);
545
- // return Promise.resolve(undefined);
546
- // }
648
+ // Validate that we're not creating a proposal for an older or equal position
649
+ if (this.lastProposedBlock) {
650
+ const lastSlot = this.lastProposedBlock.slotNumber;
651
+ const lastIndex = this.lastProposedBlock.indexWithinCheckpoint;
652
+ const newSlot = blockHeader.globalVariables.slotNumber;
653
+ if (newSlot < lastSlot || newSlot === lastSlot && indexWithinCheckpoint <= lastIndex) {
654
+ throw new Error(`Cannot create block proposal for slot ${newSlot} index ${indexWithinCheckpoint}: ` + `already proposed block for slot ${lastSlot} index ${lastIndex}`);
655
+ }
656
+ }
547
657
  this.log.info(`Assembling block proposal for block ${blockHeader.globalVariables.blockNumber} slot ${blockHeader.globalVariables.slotNumber}`);
548
658
  const newProposal = await this.validationService.createBlockProposal(blockHeader, indexWithinCheckpoint, inHash, archive, txs, proposerAddress, {
549
659
  ...options,
550
660
  broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
551
661
  });
552
- this.previousProposal = newProposal;
662
+ this.lastProposedBlock = newProposal;
553
663
  return newProposal;
554
664
  }
555
- async createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options = {}) {
665
+ async createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options = {}) {
666
+ // Validate that we're not creating a proposal for an older or equal slot
667
+ if (this.lastProposedCheckpoint) {
668
+ const lastSlot = this.lastProposedCheckpoint.slotNumber;
669
+ const newSlot = checkpointHeader.slotNumber;
670
+ if (newSlot <= lastSlot) {
671
+ throw new Error(`Cannot create checkpoint proposal for slot ${newSlot}: ` + `already proposed checkpoint for slot ${lastSlot}`);
672
+ }
673
+ }
556
674
  this.log.info(`Assembling checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
557
- return await this.validationService.createCheckpointProposal(checkpointHeader, archive, lastBlockInfo, proposerAddress, options);
675
+ const newProposal = await this.validationService.createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAddress, options);
676
+ this.lastProposedCheckpoint = newProposal;
677
+ return newProposal;
558
678
  }
559
679
  async broadcastBlockProposal(proposal) {
560
680
  await this.p2pClient.broadcastProposal(proposal);
@@ -569,6 +689,9 @@ const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
569
689
  inCommittee
570
690
  });
571
691
  const attestations = await this.createCheckpointAttestationsFromProposal(proposal, inCommittee);
692
+ if (!attestations) {
693
+ return [];
694
+ }
572
695
  // We broadcast our own attestations to our peers so, in case our block does not get mined on L1,
573
696
  // other nodes can see that our validators did attest to this block proposal, and do not slash us
574
697
  // due to inactivity for missed attestations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/validator-client",
3
- "version": "0.0.1-commit.bf2612ae",
3
+ "version": "0.0.1-commit.c0b82b2",
4
4
  "main": "dest/index.js",
5
5
  "type": "module",
6
6
  "exports": {
@@ -64,30 +64,30 @@
64
64
  ]
65
65
  },
66
66
  "dependencies": {
67
- "@aztec/blob-client": "0.0.1-commit.bf2612ae",
68
- "@aztec/blob-lib": "0.0.1-commit.bf2612ae",
69
- "@aztec/constants": "0.0.1-commit.bf2612ae",
70
- "@aztec/epoch-cache": "0.0.1-commit.bf2612ae",
71
- "@aztec/ethereum": "0.0.1-commit.bf2612ae",
72
- "@aztec/foundation": "0.0.1-commit.bf2612ae",
73
- "@aztec/node-keystore": "0.0.1-commit.bf2612ae",
74
- "@aztec/noir-protocol-circuits-types": "0.0.1-commit.bf2612ae",
75
- "@aztec/p2p": "0.0.1-commit.bf2612ae",
76
- "@aztec/protocol-contracts": "0.0.1-commit.bf2612ae",
77
- "@aztec/prover-client": "0.0.1-commit.bf2612ae",
78
- "@aztec/simulator": "0.0.1-commit.bf2612ae",
79
- "@aztec/slasher": "0.0.1-commit.bf2612ae",
80
- "@aztec/stdlib": "0.0.1-commit.bf2612ae",
81
- "@aztec/telemetry-client": "0.0.1-commit.bf2612ae",
82
- "@aztec/validator-ha-signer": "0.0.1-commit.bf2612ae",
67
+ "@aztec/blob-client": "0.0.1-commit.c0b82b2",
68
+ "@aztec/blob-lib": "0.0.1-commit.c0b82b2",
69
+ "@aztec/constants": "0.0.1-commit.c0b82b2",
70
+ "@aztec/epoch-cache": "0.0.1-commit.c0b82b2",
71
+ "@aztec/ethereum": "0.0.1-commit.c0b82b2",
72
+ "@aztec/foundation": "0.0.1-commit.c0b82b2",
73
+ "@aztec/node-keystore": "0.0.1-commit.c0b82b2",
74
+ "@aztec/noir-protocol-circuits-types": "0.0.1-commit.c0b82b2",
75
+ "@aztec/p2p": "0.0.1-commit.c0b82b2",
76
+ "@aztec/protocol-contracts": "0.0.1-commit.c0b82b2",
77
+ "@aztec/prover-client": "0.0.1-commit.c0b82b2",
78
+ "@aztec/simulator": "0.0.1-commit.c0b82b2",
79
+ "@aztec/slasher": "0.0.1-commit.c0b82b2",
80
+ "@aztec/stdlib": "0.0.1-commit.c0b82b2",
81
+ "@aztec/telemetry-client": "0.0.1-commit.c0b82b2",
82
+ "@aztec/validator-ha-signer": "0.0.1-commit.c0b82b2",
83
83
  "koa": "^2.16.1",
84
84
  "koa-router": "^13.1.1",
85
85
  "tslib": "^2.4.0",
86
86
  "viem": "npm:@aztec/viem@2.38.2"
87
87
  },
88
88
  "devDependencies": {
89
- "@aztec/archiver": "0.0.1-commit.bf2612ae",
90
- "@aztec/world-state": "0.0.1-commit.bf2612ae",
89
+ "@aztec/archiver": "0.0.1-commit.c0b82b2",
90
+ "@aztec/world-state": "0.0.1-commit.c0b82b2",
91
91
  "@electric-sql/pglite": "^0.3.14",
92
92
  "@jest/globals": "^30.0.0",
93
93
  "@types/jest": "^30.0.0",
@@ -1,7 +1,6 @@
1
1
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
2
2
  import type { EpochCache } from '@aztec/epoch-cache';
3
3
  import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
- import { chunkBy } from '@aztec/foundation/collection';
5
4
  import { Fr } from '@aztec/foundation/curves/bn254';
6
5
  import { TimeoutError } from '@aztec/foundation/error';
7
6
  import { createLogger } from '@aztec/foundation/log';
@@ -9,16 +8,12 @@ import { retryUntil } from '@aztec/foundation/retry';
9
8
  import { DateProvider, Timer } from '@aztec/foundation/timer';
10
9
  import type { P2P, PeerId } from '@aztec/p2p';
11
10
  import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
12
- import type { L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
11
+ import type { BlockData, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
13
12
  import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
14
13
  import type { ITxProvider, ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
15
- import {
16
- type L1ToL2MessageSource,
17
- computeCheckpointOutHash,
18
- computeInHashFromL1ToL2Messages,
19
- } from '@aztec/stdlib/messaging';
14
+ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
20
15
  import type { BlockProposal } from '@aztec/stdlib/p2p';
21
- import { BlockHeader, type CheckpointGlobalVariables, type FailedTx, type Tx } from '@aztec/stdlib/tx';
16
+ import type { CheckpointGlobalVariables, FailedTx, Tx } from '@aztec/stdlib/tx';
22
17
  import {
23
18
  ReExFailedTxsError,
24
19
  ReExStateMismatchError,
@@ -153,16 +148,16 @@ export class BlockProposalHandler {
153
148
  }
154
149
 
155
150
  // Check that the parent proposal is a block we know, otherwise reexecution would fail
156
- const parentBlockHeader = await this.getParentBlock(proposal);
157
- if (parentBlockHeader === undefined) {
151
+ const parentBlock = await this.getParentBlock(proposal);
152
+ if (parentBlock === undefined) {
158
153
  this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
159
154
  return { isValid: false, reason: 'parent_block_not_found' };
160
155
  }
161
156
 
162
157
  // Check that the parent block's slot is not greater than the proposal's slot.
163
- if (parentBlockHeader !== 'genesis' && parentBlockHeader.getSlot() > slotNumber) {
158
+ if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
164
159
  this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
165
- parentBlockSlot: parentBlockHeader.getSlot().toString(),
160
+ parentBlockSlot: parentBlock.header.getSlot().toString(),
166
161
  proposalSlot: slotNumber.toString(),
167
162
  ...proposalInfo,
168
163
  });
@@ -171,9 +166,9 @@ export class BlockProposalHandler {
171
166
 
172
167
  // Compute the block number based on the parent block
173
168
  const blockNumber =
174
- parentBlockHeader === 'genesis'
169
+ parentBlock === 'genesis'
175
170
  ? BlockNumber(INITIAL_L2_BLOCK_NUM)
176
- : BlockNumber(parentBlockHeader.getBlockNumber() + 1);
171
+ : BlockNumber(parentBlock.header.getBlockNumber() + 1);
177
172
 
178
173
  // Check that this block number does not exist already
179
174
  const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
@@ -190,7 +185,7 @@ export class BlockProposalHandler {
190
185
  });
191
186
 
192
187
  // Compute the checkpoint number for this block and validate checkpoint consistency
193
- const checkpointResult = await this.computeCheckpointNumber(proposal, parentBlockHeader, proposalInfo);
188
+ const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
194
189
  if (checkpointResult.reason) {
195
190
  return { isValid: false, blockNumber, reason: checkpointResult.reason };
196
191
  }
@@ -218,17 +213,11 @@ export class BlockProposalHandler {
218
213
  // Try re-executing the transactions in the proposal if needed
219
214
  let reexecutionResult;
220
215
  if (shouldReexecute) {
221
- // Compute the previous checkpoint out hashes for the epoch.
222
- // TODO(leila/mbps): There can be a more efficient way to get the previous checkpoint out
223
- // hashes without having to fetch all the blocks.
216
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
224
217
  const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
225
- const checkpointedBlocks = (await this.blockSource.getCheckpointedBlocksForEpoch(epoch))
226
- .filter(b => b.block.number < blockNumber)
227
- .sort((a, b) => a.block.number - b.block.number);
228
- const blocksByCheckpoint = chunkBy(checkpointedBlocks, b => b.checkpointNumber);
229
- const previousCheckpointOutHashes = blocksByCheckpoint.map(checkpointBlocks =>
230
- computeCheckpointOutHash(checkpointBlocks.map(b => b.block.body.txEffects.map(tx => tx.l2ToL1Msgs))),
231
- );
218
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
219
+ .filter(c => c.checkpointNumber < checkpointNumber)
220
+ .map(c => c.checkpointOutHash);
232
221
 
233
222
  try {
234
223
  this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
@@ -260,7 +249,7 @@ export class BlockProposalHandler {
260
249
  return { isValid: true, blockNumber, reexecutionResult };
261
250
  }
262
251
 
263
- private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockHeader | undefined> {
252
+ private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockData | undefined> {
264
253
  const parentArchive = proposal.blockHeader.lastArchive.root;
265
254
  const slot = proposal.slotNumber;
266
255
  const config = this.checkpointsBuilder.getConfig();
@@ -276,12 +265,11 @@ export class BlockProposalHandler {
276
265
 
277
266
  try {
278
267
  return (
279
- (await this.blockSource.getBlockHeaderByArchive(parentArchive)) ??
268
+ (await this.blockSource.getBlockDataByArchive(parentArchive)) ??
280
269
  (timeoutDurationMs <= 0
281
270
  ? undefined
282
271
  : await retryUntil(
283
- () =>
284
- this.blockSource.syncImmediate().then(() => this.blockSource.getBlockHeaderByArchive(parentArchive)),
272
+ () => this.blockSource.syncImmediate().then(() => this.blockSource.getBlockDataByArchive(parentArchive)),
285
273
  'force archiver sync',
286
274
  timeoutDurationMs / 1000,
287
275
  0.5,
@@ -297,12 +285,12 @@ export class BlockProposalHandler {
297
285
  }
298
286
  }
299
287
 
300
- private async computeCheckpointNumber(
288
+ private computeCheckpointNumber(
301
289
  proposal: BlockProposal,
302
- parentBlockHeader: 'genesis' | BlockHeader,
290
+ parentBlock: 'genesis' | BlockData,
303
291
  proposalInfo: object,
304
- ): Promise<CheckpointComputationResult> {
305
- if (parentBlockHeader === 'genesis') {
292
+ ): CheckpointComputationResult {
293
+ if (parentBlock === 'genesis') {
306
294
  // First block is in checkpoint 1
307
295
  if (proposal.indexWithinCheckpoint !== 0) {
308
296
  this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
@@ -311,19 +299,9 @@ export class BlockProposalHandler {
311
299
  return { checkpointNumber: CheckpointNumber.INITIAL };
312
300
  }
313
301
 
314
- // Get the parent block to find its checkpoint number
315
- // TODO(palla/mbps): The block header should include the checkpoint number to avoid this lookup,
316
- // or at least the L2BlockSource should return a different struct that includes it.
317
- const parentBlockNumber = parentBlockHeader.getBlockNumber();
318
- const parentBlock = await this.blockSource.getL2Block(parentBlockNumber);
319
- if (!parentBlock) {
320
- this.log.warn(`Parent block ${parentBlockNumber} not found in archiver`, proposalInfo);
321
- return { reason: 'invalid_proposal' };
322
- }
323
-
324
302
  if (proposal.indexWithinCheckpoint === 0) {
325
303
  // If this is the first block in a new checkpoint, increment the checkpoint number
326
- if (!(proposal.blockHeader.getSlot() > parentBlockHeader.getSlot())) {
304
+ if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
327
305
  this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
328
306
  return { reason: 'invalid_proposal' };
329
307
  }
@@ -335,7 +313,7 @@ export class BlockProposalHandler {
335
313
  this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
336
314
  return { reason: 'invalid_proposal' };
337
315
  }
338
- if (proposal.blockHeader.getSlot() !== parentBlockHeader.getSlot()) {
316
+ if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
339
317
  this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
340
318
  return { reason: 'invalid_proposal' };
341
319
  }
@@ -356,7 +334,7 @@ export class BlockProposalHandler {
356
334
  */
357
335
  private validateNonFirstBlockInCheckpoint(
358
336
  proposal: BlockProposal,
359
- parentBlock: L2Block,
337
+ parentBlock: BlockData,
360
338
  proposalInfo: object,
361
339
  ): CheckpointComputationResult | undefined {
362
340
  const proposalGlobals = proposal.blockHeader.globalVariables;
@@ -475,13 +453,14 @@ export class BlockProposalHandler {
475
453
  // Fork before the block to be built
476
454
  const parentBlockNumber = BlockNumber(blockNumber - 1);
477
455
  await this.worldState.syncImmediate(parentBlockNumber);
478
- using fork = await this.worldState.fork(parentBlockNumber);
456
+ await using fork = await this.worldState.fork(parentBlockNumber);
479
457
 
480
- // Build checkpoint constants from proposal (excludes blockNumber and timestamp which are per-block)
458
+ // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
481
459
  const constants: CheckpointGlobalVariables = {
482
460
  chainId: new Fr(config.l1ChainId),
483
461
  version: new Fr(config.rollupVersion),
484
462
  slotNumber: slot,
463
+ timestamp: blockHeader.globalVariables.timestamp,
485
464
  coinbase: blockHeader.globalVariables.coinbase,
486
465
  feeRecipient: blockHeader.globalVariables.feeRecipient,
487
466
  gasFees: blockHeader.globalVariables.gasFees,
@@ -491,10 +470,12 @@ export class BlockProposalHandler {
491
470
  const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
492
471
  checkpointNumber,
493
472
  constants,
473
+ 0n, // only takes effect in the following checkpoint.
494
474
  l1ToL2Messages,
495
475
  previousCheckpointOutHashes,
496
476
  fork,
497
477
  priorBlocks,
478
+ this.log.getBindings(),
498
479
  );
499
480
 
500
481
  // Build the new block