@lodestar/beacon-node 1.52.0-dev.b17bb95924 → 1.52.0-dev.b59a889970

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 (49) hide show
  1. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  2. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  3. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  4. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  5. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  6. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  7. package/lib/chain/errors/executionPayloadEnvelope.d.ts +48 -0
  8. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  9. package/lib/chain/errors/executionPayloadEnvelope.js +7 -0
  10. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  11. package/lib/chain/lightClient/index.d.ts +13 -6
  12. package/lib/chain/lightClient/index.d.ts.map +1 -1
  13. package/lib/chain/lightClient/index.js +95 -115
  14. package/lib/chain/lightClient/index.js.map +1 -1
  15. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  16. package/lib/chain/validation/executionPayloadEnvelope.js +79 -4
  17. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  18. package/lib/network/gossip/gossipsub.d.ts +1 -0
  19. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  20. package/lib/network/gossip/gossipsub.js +3 -0
  21. package/lib/network/gossip/gossipsub.js.map +1 -1
  22. package/lib/network/network.d.ts.map +1 -1
  23. package/lib/network/network.js +6 -1
  24. package/lib/network/network.js.map +1 -1
  25. package/lib/network/peers/peerManager.d.ts.map +1 -1
  26. package/lib/network/peers/peerManager.js +12 -1
  27. package/lib/network/peers/peerManager.js.map +1 -1
  28. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  29. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  30. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  31. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  32. package/lib/sync/unknownBlock.d.ts.map +1 -1
  33. package/lib/sync/unknownBlock.js +63 -3
  34. package/lib/sync/unknownBlock.js.map +1 -1
  35. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  36. package/lib/sync/utils/downloadByRoot.js +5 -4
  37. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  38. package/package.json +25 -25
  39. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  40. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  41. package/src/chain/errors/executionPayloadEnvelope.ts +50 -0
  42. package/src/chain/lightClient/index.ts +108 -142
  43. package/src/chain/validation/executionPayloadEnvelope.ts +87 -3
  44. package/src/network/gossip/gossipsub.ts +4 -0
  45. package/src/network/network.ts +6 -2
  46. package/src/network/peers/peerManager.ts +12 -1
  47. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  48. package/src/sync/unknownBlock.ts +68 -2
  49. package/src/sync/utils/downloadByRoot.ts +7 -5
@@ -1,4 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
+ import {GENESIS_SLOT} from "@lodestar/params";
2
3
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
3
4
  import {Epoch, Slot} from "@lodestar/types";
4
5
  import {Logger, prettyPrintIndices} from "@lodestar/utils";
@@ -13,6 +14,9 @@ import {Metrics} from "../../../metrics/index.js";
13
14
  */
14
15
  export const MAX_PRUNE_BLOCK_SLOTS_PER_RUN = 4096;
15
16
 
17
+ // Genesis is kept so the block and state stay available via the API, e.g. for checkpoint providers
18
+ const FIRST_PRUNABLE_SLOT = GENESIS_SLOT + 1;
19
+
16
20
  export async function pruneHistory(
17
21
  config: ChainForkConfig,
18
22
  db: IBeaconDb,
@@ -30,11 +34,12 @@ export async function pruneHistory(
30
34
  // ensure that during (extremely lol) long periods of non-finality we don't delete unfinalized epoch data
31
35
  finalizedEpoch
32
36
  );
33
- const firstBlockSlot = (await db.blockArchive.firstKey()) ?? 0;
37
+ const [firstBlockSlot = FIRST_PRUNABLE_SLOT] = await db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, limit: 1});
34
38
  const blockCutoffSlot = Math.min(computeStartSlotAtEpoch(blockCutoffEpoch), firstBlockSlot + maxBlockSlots);
35
39
  // The latest archived state is the anchor on restart and can trail finalization by a few epochs
36
40
  const lastArchivedStateSlot = (await db.stateArchive.lastKey()) ?? 0;
37
41
  const stateCutoffSlot = Math.min(computeStartSlotAtEpoch(finalizedEpoch), lastArchivedStateSlot);
42
+ const stateStartSlot = Math.max(statePruneFromSlot, FIRST_PRUNABLE_SLOT);
38
43
 
39
44
  logger.debug("Preparing to prune history", {
40
45
  currentEpoch,
@@ -46,9 +51,9 @@ export async function pruneHistory(
46
51
 
47
52
  const step0 = metrics?.pruneHistory.fetchKeys.startTimer();
48
53
  const [blocks, envelopes, states] = await Promise.all([
49
- db.blockArchive.keys({gte: 0, lt: blockCutoffSlot}),
50
- db.executionPayloadEnvelopeArchive.keys({gte: 0, lt: blockCutoffSlot}),
51
- stateCutoffSlot > statePruneFromSlot ? db.stateArchive.keys({gte: statePruneFromSlot, lt: stateCutoffSlot}) : [],
54
+ db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
55
+ db.executionPayloadEnvelopeArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
56
+ stateCutoffSlot > stateStartSlot ? db.stateArchive.keys({gte: stateStartSlot, lt: stateCutoffSlot}) : [],
52
57
  ]);
53
58
  step0?.();
54
59
 
@@ -9,10 +9,17 @@ export enum ExecutionPayloadEnvelopeErrorCode {
9
9
  ENVELOPE_ALREADY_KNOWN = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_ALREADY_KNOWN",
10
10
  INVALID_BLOCK = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INVALID_BLOCK",
11
11
  SLOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_SLOT_MISMATCH",
12
+ PARENT_BEACON_BLOCK_ROOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PARENT_BEACON_BLOCK_ROOT_MISMATCH",
12
13
  BUILDER_INDEX_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_BUILDER_INDEX_MISMATCH",
14
+ PREV_RANDAO_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PREV_RANDAO_MISMATCH",
15
+ GAS_LIMIT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_GAS_LIMIT_MISMATCH",
13
16
  BLOCK_HASH_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_BLOCK_HASH_MISMATCH",
14
17
  EXECUTION_REQUESTS_ROOT_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_EXECUTION_REQUESTS_ROOT_MISMATCH",
15
18
  TOO_MANY_TRANSACTIONS = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_TOO_MANY_TRANSACTIONS",
19
+ PARENT_HASH_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PARENT_HASH_MISMATCH",
20
+ INCORRECT_TIMESTAMP = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INCORRECT_TIMESTAMP",
21
+ EMPTY_TRANSACTION = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_EMPTY_TRANSACTION",
22
+ WITHDRAWALS_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_WITHDRAWALS_MISMATCH",
16
23
  INVALID_SIGNATURE = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INVALID_SIGNATURE",
17
24
  PAYLOAD_ENVELOPE_INPUT_MISSING = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PAYLOAD_ENVELOPE_INPUT_MISSING",
18
25
  }
@@ -34,6 +41,13 @@ export type ExecutionPayloadEnvelopeErrorType =
34
41
  envelopeSlot: Slot;
35
42
  blockSlot: Slot;
36
43
  }
44
+ | {
45
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BEACON_BLOCK_ROOT_MISMATCH;
46
+ slot: Slot;
47
+ root: RootHex;
48
+ envelopeParentBeaconBlockRoot: RootHex;
49
+ blockParentRoot: RootHex;
50
+ }
37
51
  | {
38
52
  code: ExecutionPayloadEnvelopeErrorCode.BUILDER_INDEX_MISMATCH;
39
53
  slot: Slot;
@@ -41,6 +55,20 @@ export type ExecutionPayloadEnvelopeErrorType =
41
55
  envelopeBuilderIndex: BuilderIndex;
42
56
  bidBuilderIndex: BuilderIndex | null;
43
57
  }
58
+ | {
59
+ code: ExecutionPayloadEnvelopeErrorCode.PREV_RANDAO_MISMATCH;
60
+ slot: Slot;
61
+ root: RootHex;
62
+ envelopePrevRandao: RootHex;
63
+ bidPrevRandao: RootHex;
64
+ }
65
+ | {
66
+ code: ExecutionPayloadEnvelopeErrorCode.GAS_LIMIT_MISMATCH;
67
+ slot: Slot;
68
+ root: RootHex;
69
+ envelopeGasLimit: number;
70
+ bidGasLimit: bigint;
71
+ }
44
72
  | {
45
73
  code: ExecutionPayloadEnvelopeErrorCode.BLOCK_HASH_MISMATCH;
46
74
  slot: Slot;
@@ -62,6 +90,28 @@ export type ExecutionPayloadEnvelopeErrorType =
62
90
  transactionCount: number;
63
91
  maxTransactionCount: number;
64
92
  }
93
+ | {
94
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_HASH_MISMATCH;
95
+ slot: Slot;
96
+ root: RootHex;
97
+ envelopeParentHash: RootHex;
98
+ latestBlockHash: RootHex;
99
+ }
100
+ | {
101
+ code: ExecutionPayloadEnvelopeErrorCode.INCORRECT_TIMESTAMP;
102
+ slot: Slot;
103
+ root: RootHex;
104
+ envelopeTimestamp: number;
105
+ expectedTimestamp: number;
106
+ }
107
+ | {code: ExecutionPayloadEnvelopeErrorCode.EMPTY_TRANSACTION; slot: Slot; root: RootHex; transactionIndex: number}
108
+ | {
109
+ code: ExecutionPayloadEnvelopeErrorCode.WITHDRAWALS_MISMATCH;
110
+ slot: Slot;
111
+ root: RootHex;
112
+ envelopeWithdrawalsRoot: RootHex;
113
+ expectedWithdrawalsRoot: RootHex;
114
+ }
65
115
  | {code: ExecutionPayloadEnvelopeErrorCode.INVALID_SIGNATURE; slot: Slot; root: RootHex}
66
116
  | {code: ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING; blockRoot: RootHex};
67
117
 
@@ -8,6 +8,7 @@ import {
8
8
  ForkPostGloas,
9
9
  ForkPreGloas,
10
10
  ForkSeq,
11
+ GENESIS_EPOCH,
11
12
  MIN_SYNC_COMMITTEE_PARTICIPANTS,
12
13
  SLOTS_PER_EPOCH,
13
14
  SYNC_COMMITTEE_SIZE,
@@ -16,8 +17,6 @@ import {
16
17
  } from "@lodestar/params";
17
18
  import {
18
19
  type IBeaconStateViewAltair,
19
- computeStartSlotAtEpoch,
20
- computeSyncPeriodAtEpoch,
21
20
  computeSyncPeriodAtSlot,
22
21
  executionPayloadToPayloadHeader,
23
22
  } from "@lodestar/state-transition";
@@ -44,8 +43,7 @@ import {
44
43
  phase0,
45
44
  ssz,
46
45
  } from "@lodestar/types";
47
- import {Logger, MapDef, byteArrayEquals, pruneSetToMax, toRootHex} from "@lodestar/utils";
48
- import {ZERO_HASH} from "../../constants/index.js";
46
+ import {Logger, MapDef, pruneSetToMax, toRootHex} from "@lodestar/utils";
49
47
  import {IBeaconDb} from "../../db/index.js";
50
48
  import {NUM_WITNESS, NUM_WITNESS_ELECTRA} from "../../db/repositories/lightclientSyncCommitteeWitness.js";
51
49
  import {Metrics} from "../../metrics/index.js";
@@ -72,16 +70,9 @@ export type SyncAttestedData = {
72
70
  attestedHeader: LightClientHeader;
73
71
  /** Precomputed root to prevent re-hashing */
74
72
  blockRoot: Uint8Array;
75
- } & (
76
- | {
77
- isFinalized: true;
78
- finalityBranch: Uint8Array[];
79
- finalizedCheckpoint: phase0.Checkpoint;
80
- }
81
- | {
82
- isFinalized: false;
83
- }
84
- );
73
+ finalizedCheckpoint: phase0.Checkpoint;
74
+ finalityBranch: Uint8Array[];
75
+ };
85
76
 
86
77
  type LightClientServerModules = {
87
78
  config: ChainForkConfig;
@@ -435,33 +426,14 @@ export class LightClientServer {
435
426
  // Store header in case it is referenced latter by a future finalized checkpoint
436
427
  await this.db.checkpointHeader.put(blockRoot, header);
437
428
 
438
- // Store finalized checkpoint data
439
- const finalizedCheckpoint = postState.finalizedCheckpoint;
440
- const finalizedCheckpointPeriod = computeSyncPeriodAtEpoch(finalizedCheckpoint.epoch);
441
- const isFinalized =
442
- finalizedCheckpointPeriod === period &&
443
- // Consider the edge case of genesis: Genesis state's finalizedCheckpoint is zero'ed.
444
- // If finalizedCheckpoint is zeroed, consider not finalized (ignore) since there won't exist a
445
- // finalized header for that root
446
- finalizedCheckpoint.epoch !== 0 &&
447
- !byteArrayEquals(finalizedCheckpoint.root, ZERO_HASH);
448
-
449
- this.prevHeadData.set(
450
- blockRootHex,
451
- isFinalized
452
- ? {
453
- isFinalized: true,
454
- attestedHeader: header,
455
- blockRoot,
456
- finalityBranch: postState.getFinalizedRootProof(),
457
- finalizedCheckpoint,
458
- }
459
- : {
460
- isFinalized: false,
461
- attestedHeader: header,
462
- blockRoot,
463
- }
464
- );
429
+ // Store finalized checkpoint data. The finality branch only depends on the post state, so it is
430
+ // collected for every block; see `buildUpdate` for the cases in which it is served.
431
+ this.prevHeadData.set(blockRootHex, {
432
+ attestedHeader: header,
433
+ blockRoot,
434
+ finalizedCheckpoint: postState.finalizedCheckpoint,
435
+ finalityBranch: postState.getFinalizedRootProof(),
436
+ });
465
437
 
466
438
  pruneSetToMax(this.prevHeadData, MAX_PREV_HEAD_DATA);
467
439
  }
@@ -505,7 +477,7 @@ export class LightClientServer {
505
477
  return;
506
478
  }
507
479
 
508
- const {attestedHeader, isFinalized} = attestedData;
480
+ const {attestedHeader} = attestedData;
509
481
  const attestedPeriod = computeSyncPeriodAtSlot(attestedHeader.beacon.slot);
510
482
  if (syncPeriod !== attestedPeriod) {
511
483
  this.logger.debug("attested data period different than signature period", {syncPeriod, attestedPeriod});
@@ -555,41 +527,36 @@ export class LightClientServer {
555
527
  this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_head_update"});
556
528
  }
557
529
 
558
- if (isFinalized) {
559
- const finalizedCheckpointRoot = attestedData.finalizedCheckpoint.root;
560
- let finalizedHeader = await this.getFinalizedHeader(finalizedCheckpointRoot);
561
-
562
- if (
563
- finalizedHeader &&
564
- (!this.finalized ||
565
- finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
566
- syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
567
- ) {
568
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
569
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
570
- }
571
- this.finalized = {
572
- attestedHeader,
573
- finalizedHeader,
574
- syncAggregate,
575
- finalityBranch: attestedData.finalityBranch,
576
- signatureSlot,
577
- };
578
- this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
579
-
580
- if (!isStaleLightClientUpdate) {
581
- // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
582
- this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
583
- version: attestedFork,
584
- data: this.finalized,
585
- });
586
- }
530
+ const builtUpdate = await this.buildUpdate(attestedData, syncAggregate, signatureSlot);
531
+ if (
532
+ builtUpdate?.hasFinality &&
533
+ (!this.finalized ||
534
+ builtUpdate.update.finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
535
+ syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
536
+ ) {
537
+ this.finalized = {
538
+ attestedHeader,
539
+ finalizedHeader: builtUpdate.update.finalizedHeader,
540
+ syncAggregate,
541
+ finalityBranch: builtUpdate.update.finalityBranch,
542
+ signatureSlot,
543
+ };
544
+ this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
545
+
546
+ if (!isStaleLightClientUpdate) {
547
+ // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
548
+ this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
549
+ version: attestedFork,
550
+ data: this.finalized,
551
+ });
587
552
  }
588
553
  }
589
554
 
590
555
  // Check if this update is better, otherwise ignore
591
556
  try {
592
- await this.maybeStoreNewBestUpdate(syncPeriod, syncAggregate, signatureSlot, attestedData);
557
+ if (builtUpdate) {
558
+ await this.maybeStoreNewBestUpdate(syncPeriod, builtUpdate);
559
+ }
593
560
  } catch (e) {
594
561
  this.logger.error(
595
562
  "Error updating best LightClientUpdate",
@@ -605,36 +572,50 @@ export class LightClientServer {
605
572
  */
606
573
  private async maybeStoreNewBestUpdate(
607
574
  syncPeriod: SyncPeriod,
608
- syncAggregate: altair.SyncAggregate,
609
- signatureSlot: Slot,
610
- attestedData: SyncAttestedData
575
+ built: {update: LightClientUpdate; summary: LightClientUpdateSummary}
611
576
  ): Promise<void> {
612
577
  const prevBestUpdate = await this.db.bestLightClientUpdate.get(syncPeriod);
613
- const {attestedHeader} = attestedData;
578
+ if (prevBestUpdate && !isBetterUpdate(built.summary, toLightClientUpdateSummary(prevBestUpdate))) {
579
+ this.metrics?.lightclientServer.updateNotBetter.inc();
580
+ return;
581
+ }
614
582
 
615
- if (prevBestUpdate) {
616
- const prevBestUpdateSummary = toLightClientUpdateSummary(prevBestUpdate);
583
+ // attestedData and the block of syncAggregate may not be in same sync period
584
+ // should not use attested data slot as sync period
585
+ // see https://github.com/ChainSafe/lodestar/issues/3933
586
+ await this.db.bestLightClientUpdate.put(syncPeriod, built.update);
587
+ this.logger.debug("Stored new PartialLightClientUpdate", {
588
+ syncPeriod,
589
+ isFinalized: built.summary.isFinalityUpdate,
590
+ participation: sumBits(built.update.syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
591
+ });
617
592
 
618
- const nextBestUpdate: LightClientUpdateSummary = {
619
- activeParticipants: sumBits(syncAggregate.syncCommitteeBits),
620
- attestedHeaderSlot: attestedHeader.beacon.slot,
621
- signatureSlot,
622
- // The actual finalizedHeader is fetched below. To prevent a DB read we approximate the actual slot.
623
- // If update is not finalized finalizedHeaderSlot does not matter (see is_better_update), so setting
624
- // to zero to set it some number.
625
- finalizedHeaderSlot: attestedData.isFinalized
626
- ? computeStartSlotAtEpoch(attestedData.finalizedCheckpoint.epoch)
627
- : 0,
628
- // All updates include a valid `nextSyncCommitteeBranch`, see below code
629
- isSyncCommitteeUpdate: true,
630
- isFinalityUpdate: attestedData.isFinalized,
631
- };
593
+ // Count total persisted updates per type. DB metrics don't diff between each type.
594
+ // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
595
+ this.metrics?.lightclientServer.onSyncAggregate.inc({
596
+ event: built.summary.isFinalityUpdate ? "store_finalized_update" : "store_nonfinalized_update",
597
+ });
598
+ this.metrics?.lightclientServer.highestSlot.set(
599
+ {item: built.summary.isFinalityUpdate ? "best_finalized_update" : "best_nonfinalized_update"},
600
+ built.update.attestedHeader.beacon.slot
601
+ );
602
+ }
632
603
 
633
- if (!isBetterUpdate(nextBestUpdate, prevBestUpdateSummary)) {
634
- this.metrics?.lightclientServer.updateNotBetter.inc();
635
- return;
636
- }
637
- }
604
+ /**
605
+ * Build the update for `syncAggregate` attesting to `attestedData`.
606
+ *
607
+ * Finality is indicated whenever it can be proven, in one of three ways:
608
+ * - the finalized checkpoint is genesis: the branch is served, the header stays empty, since
609
+ * genesis cannot be proven by a header and the branch alone proves that `finalized_root` is zero
610
+ * - the finalized header is available locally: both the header and the branch are served
611
+ * - the finalized header is not available: neither is served, and `hasFinality` is false
612
+ */
613
+ private async buildUpdate(
614
+ attestedData: SyncAttestedData,
615
+ syncAggregate: altair.SyncAggregate,
616
+ signatureSlot: Slot
617
+ ): Promise<{update: LightClientUpdate; summary: LightClientUpdateSummary; hasFinality: boolean} | null> {
618
+ const {attestedHeader} = attestedData;
638
619
 
639
620
  const syncCommitteeWitness = await this.db.syncCommitteeWitness.get(attestedData.blockRoot);
640
621
  if (!syncCommitteeWitness) {
@@ -662,41 +643,34 @@ export class LightClientServer {
662
643
  throw Error("nextSyncCommittee not available");
663
644
  }
664
645
  const nextSyncCommitteeBranch = getNextSyncCommitteeBranch(syncCommitteeWitness);
665
- const finalizedHeaderAttested = attestedData.isFinalized
666
- ? await this.getFinalizedHeader(attestedData.finalizedCheckpoint.root)
667
- : null;
668
646
 
669
- let isFinalized: boolean, finalityBranch: Uint8Array[], finalizedHeader: LightClientHeader;
647
+ const zeroFinality = this.getZeroFinality(attestedFork, attestedHeader.beacon.slot);
648
+ const {finalizedCheckpoint} = attestedData;
649
+ let finalityBranch = zeroFinality.finalityBranch;
650
+ let finalizedHeader = zeroFinality.finalizedHeader;
651
+ let hasFinality = false;
670
652
 
671
- if (
672
- attestedData.isFinalized &&
673
- finalizedHeaderAttested &&
674
- computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) === syncPeriod
675
- ) {
676
- isFinalized = true;
653
+ if (finalizedCheckpoint.epoch === GENESIS_EPOCH) {
654
+ // Genesis cannot be proven by a header, the branch alone proves that finalized_root is zero
677
655
  finalityBranch = attestedData.finalityBranch;
678
- finalizedHeader = finalizedHeaderAttested;
679
- // Fork of LightClientUpdate is based off on attested header's fork
680
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
681
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
682
- }
656
+ hasFinality = true;
683
657
  } else {
684
- isFinalized = false;
685
- let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
- if (!zeroFinality) {
687
- const {finalityBranch, finalizedHeader} = this.config
688
- .getPostAltairForkTypes(attestedHeader.beacon.slot)
689
- .LightClientUpdate.defaultValue();
690
- zeroFinality = {finalityBranch, finalizedHeader};
691
- this.zeroFinalityByFork.set(attestedFork, zeroFinality);
658
+ const finalizedHeaderAttested = await this.getFinalizedHeader(finalizedCheckpoint.root);
659
+ // If the finalized block is not available locally, both stay empty
660
+ if (finalizedHeaderAttested) {
661
+ finalityBranch = attestedData.finalityBranch;
662
+ finalizedHeader = finalizedHeaderAttested;
663
+ hasFinality = true;
664
+ // Fork of LightClientUpdate is based off on attested header's fork
665
+ if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
666
+ finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
667
+ }
692
668
  }
693
- finalityBranch = zeroFinality.finalityBranch;
694
- finalizedHeader = zeroFinality.finalizedHeader;
695
669
  }
696
670
 
697
- const newUpdate = {
671
+ const update = {
698
672
  attestedHeader,
699
- nextSyncCommittee: nextSyncCommittee,
673
+ nextSyncCommittee,
700
674
  nextSyncCommitteeBranch,
701
675
  finalizedHeader,
702
676
  finalityBranch,
@@ -704,25 +678,17 @@ export class LightClientServer {
704
678
  signatureSlot,
705
679
  } as LightClientUpdate;
706
680
 
707
- // attestedData and the block of syncAggregate may not be in same sync period
708
- // should not use attested data slot as sync period
709
- // see https://github.com/ChainSafe/lodestar/issues/3933
710
- await this.db.bestLightClientUpdate.put(syncPeriod, newUpdate);
711
- this.logger.debug("Stored new PartialLightClientUpdate", {
712
- syncPeriod,
713
- isFinalized,
714
- participation: sumBits(syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
715
- });
681
+ return {update, summary: toLightClientUpdateSummary(update), hasFinality};
682
+ }
716
683
 
717
- // Count total persisted updates per type. DB metrics don't diff between each type.
718
- // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
719
- this.metrics?.lightclientServer.onSyncAggregate.inc({
720
- event: isFinalized ? "store_finalized_update" : "store_nonfinalized_update",
721
- });
722
- this.metrics?.lightclientServer.highestSlot.set(
723
- {item: isFinalized ? "best_finalized_update" : "best_nonfinalized_update"},
724
- newUpdate.attestedHeader.beacon.slot
725
- );
684
+ private getZeroFinality(attestedFork: ForkName, attestedSlot: Slot): LightClientZeroFinality {
685
+ let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
+ if (!zeroFinality) {
687
+ const zero = this.config.getPostAltairForkTypes(attestedSlot).LightClientUpdate.defaultValue();
688
+ zeroFinality = {finalityBranch: zero.finalityBranch, finalizedHeader: zero.finalizedHeader};
689
+ this.zeroFinalityByFork.set(attestedFork, zeroFinality);
690
+ }
691
+ return zeroFinality;
726
692
  }
727
693
 
728
694
  private async storeSyncCommittee(syncCommittee: altair.SyncCommittee, syncCommitteeRoot: Uint8Array): Promise<void> {
@@ -1,6 +1,7 @@
1
1
  import {PayloadStatus, ProtoBlock} from "@lodestar/fork-choice";
2
2
  import {
3
3
  computeStartSlotAtEpoch,
4
+ computeTimeAtSlot,
4
5
  getExecutionPayloadEnvelopeSignatureSet,
5
6
  isStatePostGloas,
6
7
  } from "@lodestar/state-transition";
@@ -129,6 +130,17 @@ async function validateExecutionPayloadEnvelope(
129
130
  });
130
131
  }
131
132
 
133
+ // [REJECT] `envelope.parent_beacon_block_root == block.parent_root`
134
+ if (toRootHex(envelope.parentBeaconBlockRoot) !== block.parentRoot) {
135
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
136
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_BEACON_BLOCK_ROOT_MISMATCH,
137
+ slot: payload.slotNumber,
138
+ root: blockRootHex,
139
+ envelopeParentBeaconBlockRoot: toRootHex(envelope.parentBeaconBlockRoot),
140
+ blockParentRoot: block.parentRoot,
141
+ });
142
+ }
143
+
132
144
  // [REJECT] `envelope.builder_index == bid.builder_index`
133
145
  if (envelope.builderIndex !== payloadInput.getBuilderIndex()) {
134
146
  throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
@@ -140,6 +152,30 @@ async function validateExecutionPayloadEnvelope(
140
152
  });
141
153
  }
142
154
 
155
+ const bid = payloadInput.getBid();
156
+
157
+ // [REJECT] `payload.prev_randao == bid.prev_randao`
158
+ if (!byteArrayEquals(payload.prevRandao, bid.prevRandao)) {
159
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
160
+ code: ExecutionPayloadEnvelopeErrorCode.PREV_RANDAO_MISMATCH,
161
+ slot: payload.slotNumber,
162
+ root: blockRootHex,
163
+ envelopePrevRandao: toRootHex(payload.prevRandao),
164
+ bidPrevRandao: toRootHex(bid.prevRandao),
165
+ });
166
+ }
167
+
168
+ // [REJECT] `payload.gas_limit == bid.gas_limit`
169
+ if (BigInt(payload.gasLimit) !== bid.gasLimit) {
170
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
171
+ code: ExecutionPayloadEnvelopeErrorCode.GAS_LIMIT_MISMATCH,
172
+ slot: payload.slotNumber,
173
+ root: blockRootHex,
174
+ envelopeGasLimit: payload.gasLimit,
175
+ bidGasLimit: bid.gasLimit,
176
+ });
177
+ }
178
+
143
179
  // [REJECT] `payload.block_hash == bid.block_hash`
144
180
  if (toRootHex(payload.blockHash) !== payloadInput.getBlockHashHex()) {
145
181
  throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
@@ -153,13 +189,13 @@ async function validateExecutionPayloadEnvelope(
153
189
 
154
190
  // [REJECT] `hash_tree_root(envelope.execution_requests) == bid.execution_requests_root`
155
191
  const requestsRoot = ssz.gloas.ExecutionRequests.hashTreeRoot(envelope.executionRequests);
156
- if (!byteArrayEquals(requestsRoot, payloadInput.getBid().executionRequestsRoot)) {
192
+ if (!byteArrayEquals(requestsRoot, bid.executionRequestsRoot)) {
157
193
  throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
158
194
  code: ExecutionPayloadEnvelopeErrorCode.EXECUTION_REQUESTS_ROOT_MISMATCH,
159
195
  slot: payload.slotNumber,
160
196
  root: blockRootHex,
161
197
  envelopeRequestsRoot: toRootHex(requestsRoot),
162
- bidRequestsRoot: toRootHex(payloadInput.getBid().executionRequestsRoot),
198
+ bidRequestsRoot: toRootHex(bid.executionRequestsRoot),
163
199
  });
164
200
  }
165
201
 
@@ -177,7 +213,7 @@ async function validateExecutionPayloadEnvelope(
177
213
  });
178
214
  }
179
215
 
180
- // Get the block state to verify the builder's signature.
216
+ // Get the block state to verify the payload against it and the builder's signature.
181
217
  const blockState = await chain.regen
182
218
  .getState(block.stateRoot, RegenCaller.validateGossipPayloadEnvelope)
183
219
  .catch(() => {
@@ -191,6 +227,54 @@ async function validateExecutionPayloadEnvelope(
191
227
  throw new Error(`Expected gloas+ state for execution payload envelope validation, got fork=${blockState.forkName}`);
192
228
  }
193
229
 
230
+ // [REJECT] `payload.parent_hash == state.latest_block_hash`
231
+ if (!byteArrayEquals(payload.parentHash, blockState.latestBlockHash)) {
232
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
233
+ code: ExecutionPayloadEnvelopeErrorCode.PARENT_HASH_MISMATCH,
234
+ slot: payload.slotNumber,
235
+ root: blockRootHex,
236
+ envelopeParentHash: toRootHex(payload.parentHash),
237
+ latestBlockHash: toRootHex(blockState.latestBlockHash),
238
+ });
239
+ }
240
+
241
+ // [REJECT] `payload.timestamp == compute_time_at_slot(state.genesis_time, block.slot)`
242
+ const expectedTimestamp = computeTimeAtSlot(chain.config, block.slot, blockState.genesisTime);
243
+ if (payload.timestamp !== expectedTimestamp) {
244
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
245
+ code: ExecutionPayloadEnvelopeErrorCode.INCORRECT_TIMESTAMP,
246
+ slot: payload.slotNumber,
247
+ root: blockRootHex,
248
+ envelopeTimestamp: payload.timestamp,
249
+ expectedTimestamp,
250
+ });
251
+ }
252
+
253
+ // [REJECT] The payload contains no empty transactions
254
+ for (let i = 0; i < payload.transactions.length; i++) {
255
+ if (payload.transactions.getSize(i) === 0) {
256
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
257
+ code: ExecutionPayloadEnvelopeErrorCode.EMPTY_TRANSACTION,
258
+ slot: payload.slotNumber,
259
+ root: blockRootHex,
260
+ transactionIndex: i,
261
+ });
262
+ }
263
+ }
264
+
265
+ // [REJECT] `hash_tree_root(payload.withdrawals) == hash_tree_root(state.payload_expected_withdrawals)`
266
+ const withdrawalsRoot = ssz.gloas.Withdrawals.hashTreeRoot(payload.withdrawals);
267
+ const expectedWithdrawalsRoot = ssz.gloas.Withdrawals.hashTreeRoot(blockState.payloadExpectedWithdrawals);
268
+ if (!byteArrayEquals(withdrawalsRoot, expectedWithdrawalsRoot)) {
269
+ throw new ExecutionPayloadEnvelopeError(GossipAction.REJECT, {
270
+ code: ExecutionPayloadEnvelopeErrorCode.WITHDRAWALS_MISMATCH,
271
+ slot: payload.slotNumber,
272
+ root: blockRootHex,
273
+ envelopeWithdrawalsRoot: toRootHex(withdrawalsRoot),
274
+ expectedWithdrawalsRoot: toRootHex(expectedWithdrawalsRoot),
275
+ });
276
+ }
277
+
194
278
  // [REJECT] `signed_execution_payload_envelope.signature` is valid as verified
195
279
  // by `verify_execution_payload_envelope_signature`.
196
280
  const signatureSet = getExecutionPayloadEnvelopeSignatureSet(
@@ -505,6 +505,10 @@ export class Eth2Gossipsub {
505
505
  getDirectPeers(): string[] {
506
506
  return Array.from(this.gossipsub.direct);
507
507
  }
508
+
509
+ isDirectPeer(peerIdStr: string): boolean {
510
+ return this.gossipsub.direct.has(peerIdStr);
511
+ }
508
512
  }
509
513
 
510
514
  /**
@@ -431,7 +431,7 @@ export class Network implements INetwork {
431
431
  }
432
432
 
433
433
  async publishBlsToExecutionChange(blsToExecutionChange: capella.SignedBLSToExecutionChange): Promise<number> {
434
- const publishChanges = [];
434
+ const publishChanges: Promise<number>[] = [];
435
435
  for (const boundary of getActiveForkBoundaries(this.config, this.clock.currentEpoch)) {
436
436
  const fork = ForkSeq[boundary.fork];
437
437
 
@@ -447,7 +447,11 @@ export class Network implements INetwork {
447
447
  if (publishChanges.length === 0) {
448
448
  throw Error("No capella+ fork active yet to publish blsToExecutionChange");
449
449
  }
450
- return Promise.any(publishChanges);
450
+ try {
451
+ return await Promise.any(publishChanges);
452
+ } finally {
453
+ await Promise.allSettled(publishChanges);
454
+ }
451
455
  }
452
456
 
453
457
  async publishProposerSlashing(proposerSlashing: phase0.ProposerSlashing): Promise<number> {
@@ -554,6 +554,11 @@ export class PeerManager {
554
554
  // ban and disconnect peers with bad score, collect rest of healthy peers
555
555
  const connectedHealthyPeers: PeerId[] = [];
556
556
  for (const peer of connectedPeers) {
557
+ // Direct peers are trusted by the operator, a bad score never disconnects them
558
+ if (this.gossipsub.isDirectPeer(peer.toString())) {
559
+ connectedHealthyPeers.push(peer);
560
+ continue;
561
+ }
557
562
  switch (this.peerRpcScores.getScoreState(peer)) {
558
563
  case ScoreState.Banned:
559
564
  this.metrics?.peerManager.peersPruned.inc({reason: "banned"});
@@ -584,9 +589,11 @@ export class PeerManager {
584
589
  const prioritizeTimer = this.metrics?.peerManager.prioritizePeersDuration.startTimer();
585
590
  const {peersToDisconnect, peersToConnect, attnetQueries, syncnetQueries, custodyGroupQueries} = prioritizePeers(
586
591
  connectedHealthyPeers.map((peer) => {
587
- const peerData = this.connectedPeers.get(peer.toString());
592
+ const peerIdStr = peer.toString();
593
+ const peerData = this.connectedPeers.get(peerIdStr);
588
594
  return {
589
595
  id: peer,
596
+ direct: this.gossipsub.isDirectPeer(peerIdStr),
590
597
  direction: peerData?.direction ?? null,
591
598
  status: peerData?.status ?? null,
592
599
  attnets: peerData?.metadata?.attnets ?? null,
@@ -708,6 +715,10 @@ export class PeerManager {
708
715
  private updateGossipsubScores(): void {
709
716
  const gossipsubScores = new Map<string, number>();
710
717
  for (const peerIdStr of this.connectedPeers.keys()) {
718
+ // Direct peers are never disconnected, they must not take the negative score allowance of other peers
719
+ if (this.gossipsub.isDirectPeer(peerIdStr)) {
720
+ continue;
721
+ }
711
722
  gossipsubScores.set(peerIdStr, this.gossipsub.getScore(peerIdStr));
712
723
  }
713
724