@lodestar/beacon-node 2.1.0-dev.a207065589 → 2.1.0-dev.a2ac365b3e

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 (126) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +1 -3
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/errors.d.ts +7 -0
  5. package/lib/api/impl/errors.d.ts.map +1 -1
  6. package/lib/api/impl/errors.js +9 -0
  7. package/lib/api/impl/errors.js.map +1 -1
  8. package/lib/api/rest/base.d.ts.map +1 -1
  9. package/lib/api/rest/base.js +5 -2
  10. package/lib/api/rest/base.js.map +1 -1
  11. package/lib/chain/ColumnReconstructionTracker.d.ts +3 -0
  12. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  13. package/lib/chain/ColumnReconstructionTracker.js +3 -1
  14. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  15. package/lib/chain/GetBlobsTracker.d.ts +3 -0
  16. package/lib/chain/GetBlobsTracker.d.ts.map +1 -1
  17. package/lib/chain/GetBlobsTracker.js +3 -1
  18. package/lib/chain/GetBlobsTracker.js.map +1 -1
  19. package/lib/chain/chain.d.ts +2 -1
  20. package/lib/chain/chain.d.ts.map +1 -1
  21. package/lib/chain/chain.js +5 -1
  22. package/lib/chain/chain.js.map +1 -1
  23. package/lib/chain/errors/dataColumnSidecarError.d.ts +7 -0
  24. package/lib/chain/errors/dataColumnSidecarError.d.ts.map +1 -1
  25. package/lib/chain/errors/dataColumnSidecarError.js +1 -0
  26. package/lib/chain/errors/dataColumnSidecarError.js.map +1 -1
  27. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  28. package/lib/chain/forkChoice/index.js +1 -2
  29. package/lib/chain/forkChoice/index.js.map +1 -1
  30. package/lib/chain/interface.d.ts +2 -1
  31. package/lib/chain/interface.d.ts.map +1 -1
  32. package/lib/chain/interface.js.map +1 -1
  33. package/lib/chain/options.d.ts.map +1 -1
  34. package/lib/chain/options.js +0 -2
  35. package/lib/chain/options.js.map +1 -1
  36. package/lib/chain/seenCache/index.d.ts +1 -0
  37. package/lib/chain/seenCache/index.d.ts.map +1 -1
  38. package/lib/chain/seenCache/index.js +1 -0
  39. package/lib/chain/seenCache/index.js.map +1 -1
  40. package/lib/chain/seenCache/seenBlockProposers.d.ts +3 -0
  41. package/lib/chain/seenCache/seenBlockProposers.d.ts.map +1 -1
  42. package/lib/chain/seenCache/seenBlockProposers.js +6 -2
  43. package/lib/chain/seenCache/seenBlockProposers.js.map +1 -1
  44. package/lib/chain/seenCache/seenDataColumnSidecars.d.ts +17 -0
  45. package/lib/chain/seenCache/seenDataColumnSidecars.d.ts.map +1 -0
  46. package/lib/chain/seenCache/seenDataColumnSidecars.js +61 -0
  47. package/lib/chain/seenCache/seenDataColumnSidecars.js.map +1 -0
  48. package/lib/chain/validation/block.d.ts.map +1 -1
  49. package/lib/chain/validation/block.js +12 -2
  50. package/lib/chain/validation/block.js.map +1 -1
  51. package/lib/chain/validation/dataColumnSidecar.js +1 -1
  52. package/lib/chain/validation/dataColumnSidecar.js.map +1 -1
  53. package/lib/chain/validation/voluntaryExit.js +2 -2
  54. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  55. package/lib/index.d.ts +1 -0
  56. package/lib/index.d.ts.map +1 -1
  57. package/lib/index.js +1 -0
  58. package/lib/index.js.map +1 -1
  59. package/lib/network/core/networkCore.d.ts +1 -3
  60. package/lib/network/core/networkCore.d.ts.map +1 -1
  61. package/lib/network/core/networkCore.js +1 -3
  62. package/lib/network/core/networkCore.js.map +1 -1
  63. package/lib/network/forks.d.ts +2 -2
  64. package/lib/network/forks.d.ts.map +1 -1
  65. package/lib/network/forks.js +3 -3
  66. package/lib/network/forks.js.map +1 -1
  67. package/lib/network/gossip/scoringParameters.js +19 -14
  68. package/lib/network/gossip/scoringParameters.js.map +1 -1
  69. package/lib/network/network.d.ts +1 -6
  70. package/lib/network/network.d.ts.map +1 -1
  71. package/lib/network/network.js +16 -40
  72. package/lib/network/network.js.map +1 -1
  73. package/lib/network/options.d.ts +0 -1
  74. package/lib/network/options.d.ts.map +1 -1
  75. package/lib/network/options.js +0 -1
  76. package/lib/network/options.js.map +1 -1
  77. package/lib/network/peers/discover.d.ts +1 -0
  78. package/lib/network/peers/discover.d.ts.map +1 -1
  79. package/lib/network/peers/discover.js +44 -48
  80. package/lib/network/peers/discover.js.map +1 -1
  81. package/lib/network/peers/score/store.d.ts.map +1 -1
  82. package/lib/network/peers/score/store.js +1 -2
  83. package/lib/network/peers/score/store.js.map +1 -1
  84. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  85. package/lib/network/processor/gossipHandlers.js +61 -3
  86. package/lib/network/processor/gossipHandlers.js.map +1 -1
  87. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  88. package/lib/sync/utils/downloadByRange.js +4 -0
  89. package/lib/sync/utils/downloadByRange.js.map +1 -1
  90. package/lib/util/dataColumns.d.ts +2 -1
  91. package/lib/util/dataColumns.d.ts.map +1 -1
  92. package/lib/util/dataColumns.js +7 -2
  93. package/lib/util/dataColumns.js.map +1 -1
  94. package/lib/util/execution.d.ts +2 -1
  95. package/lib/util/execution.d.ts.map +1 -1
  96. package/lib/util/execution.js +7 -2
  97. package/lib/util/execution.js.map +1 -1
  98. package/package.json +18 -18
  99. package/src/api/impl/beacon/blocks/index.ts +1 -5
  100. package/src/api/impl/errors.ts +10 -0
  101. package/src/api/rest/base.ts +4 -2
  102. package/src/chain/ColumnReconstructionTracker.ts +5 -1
  103. package/src/chain/GetBlobsTracker.ts +5 -0
  104. package/src/chain/chain.ts +5 -0
  105. package/src/chain/errors/dataColumnSidecarError.ts +8 -0
  106. package/src/chain/forkChoice/index.ts +1 -3
  107. package/src/chain/interface.ts +2 -0
  108. package/src/chain/options.ts +0 -2
  109. package/src/chain/seenCache/index.ts +1 -0
  110. package/src/chain/seenCache/seenBlockProposers.ts +12 -2
  111. package/src/chain/seenCache/seenDataColumnSidecars.ts +69 -0
  112. package/src/chain/validation/block.ts +11 -2
  113. package/src/chain/validation/dataColumnSidecar.ts +1 -1
  114. package/src/chain/validation/voluntaryExit.ts +2 -2
  115. package/src/index.ts +1 -0
  116. package/src/network/core/networkCore.ts +1 -3
  117. package/src/network/forks.ts +7 -3
  118. package/src/network/gossip/scoringParameters.ts +23 -14
  119. package/src/network/network.ts +20 -44
  120. package/src/network/options.ts +0 -2
  121. package/src/network/peers/discover.ts +42 -52
  122. package/src/network/peers/score/store.ts +1 -2
  123. package/src/network/processor/gossipHandlers.ts +107 -3
  124. package/src/sync/utils/downloadByRange.ts +3 -0
  125. package/src/util/dataColumns.ts +13 -1
  126. package/src/util/execution.ts +16 -1
@@ -127,6 +127,7 @@ import {
127
127
  SeenAttesters,
128
128
  SeenBlockProposers,
129
129
  SeenContributionAndProof,
130
+ SeenDataColumnSidecars,
130
131
  SeenExecutionPayloadBids,
131
132
  SeenPayloadAttesters,
132
133
  SeenPayloadEnvelopeInput,
@@ -224,6 +225,7 @@ export class BeaconChain implements IBeaconChain {
224
225
  readonly seenAggregatedAttestations: SeenAggregatedAttestations;
225
226
  readonly seenExecutionPayloadBids = new SeenExecutionPayloadBids();
226
227
  readonly seenBlockProposers = new SeenBlockProposers();
228
+ readonly seenDataColumnSidecars = new SeenDataColumnSidecars();
227
229
  /** Proposer indexes with an in-flight proposer slashing production */
228
230
  private readonly producingProposerSlashing = new Set<ValidatorIndex>();
229
231
  readonly seenSyncCommitteeMessages = new SeenSyncCommitteeMessages();
@@ -527,12 +529,14 @@ export class BeaconChain implements IBeaconChain {
527
529
  logger,
528
530
  executionEngine: this.executionEngine,
529
531
  emitter,
532
+ seenDataColumnSidecars: this.seenDataColumnSidecars,
530
533
  metrics,
531
534
  config,
532
535
  });
533
536
  this.columnReconstructionTracker = new ColumnReconstructionTracker({
534
537
  logger,
535
538
  emitter,
539
+ seenDataColumnSidecars: this.seenDataColumnSidecars,
536
540
  metrics,
537
541
  config,
538
542
  signal,
@@ -2039,6 +2043,7 @@ export class BeaconChain implements IBeaconChain {
2039
2043
 
2040
2044
  const finalizedSlot = computeStartSlotAtEpoch(cp.epoch);
2041
2045
  this.seenBlockProposers.prune(finalizedSlot);
2046
+ this.seenDataColumnSidecars.prune(finalizedSlot);
2042
2047
 
2043
2048
  // Update validator custody to account for effective balance changes
2044
2049
  try {
@@ -35,6 +35,7 @@ export enum DataColumnSidecarErrorCode {
35
35
 
36
36
  // following errors are adapted from the block errors
37
37
  ALREADY_KNOWN = "DATA_COLUMN_SIDECAR_ERROR_ALREADY_KNOWN",
38
+ REPEAT_PROPOSAL = "DATA_COLUMN_SIDECAR_ERROR_REPEAT_PROPOSAL",
38
39
  FUTURE_SLOT = "DATA_COLUMN_SIDECAR_ERROR_FUTURE_SLOT",
39
40
  WOULD_REVERT_FINALIZED_SLOT = "DATA_COLUMN_SIDECAR_ERROR_WOULD_REVERT_FINALIZED_SLOT",
40
41
  PARENT_UNKNOWN = "DATA_COLUMN_SIDECAR_ERROR_PARENT_UNKNOWN",
@@ -79,6 +80,13 @@ export type DataColumnSidecarErrorType =
79
80
  limit: number;
80
81
  }
81
82
  | {code: DataColumnSidecarErrorCode.ALREADY_KNOWN; columnIndex: number; slot: Slot}
83
+ | {
84
+ code: DataColumnSidecarErrorCode.REPEAT_PROPOSAL;
85
+ slot: Slot;
86
+ proposerIndex: number;
87
+ columnIndex: number;
88
+ root: RootHex;
89
+ }
82
90
  | {code: DataColumnSidecarErrorCode.FUTURE_SLOT; blockSlot: Slot; currentSlot: Slot}
83
91
  | {code: DataColumnSidecarErrorCode.WOULD_REVERT_FINALIZED_SLOT; blockSlot: Slot; finalizedSlot: Slot}
84
92
  | {
@@ -318,9 +318,7 @@ export function initializeNativeForkChoice(
318
318
  : isPostGloas
319
319
  ? Number(state.latestExecutionPayloadBid.gasLimit)
320
320
  : state.latestExecutionPayloadHeader.gasLimit,
321
- // A Gloas payload is judged when its envelope arrives, the genesis one included
322
- executionStatus:
323
- blockHeader.slot === GENESIS_SLOT && !isPostGloasAnchor ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
321
+ executionStatus: blockHeader.slot === GENESIS_SLOT ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
324
322
  }
325
323
  : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
326
324
 
@@ -68,6 +68,7 @@ import {
68
68
  SeenAttesters,
69
69
  SeenBlockProposers,
70
70
  SeenContributionAndProof,
71
+ SeenDataColumnSidecars,
71
72
  SeenExecutionPayloadBids,
72
73
  SeenPayloadAttesters,
73
74
  SeenSyncCommitteeMessages,
@@ -147,6 +148,7 @@ export interface IBeaconChain {
147
148
  readonly seenAggregatedAttestations: SeenAggregatedAttestations;
148
149
  readonly seenExecutionPayloadBids: SeenExecutionPayloadBids;
149
150
  readonly seenBlockProposers: SeenBlockProposers;
151
+ readonly seenDataColumnSidecars: SeenDataColumnSidecars;
150
152
  readonly seenSyncCommitteeMessages: SeenSyncCommitteeMessages;
151
153
  readonly seenContributionAndProof: SeenContributionAndProof;
152
154
  readonly seenAttestationDatas: SeenAttestationDatas;
@@ -123,8 +123,6 @@ export const defaultChainOptions: IChainOptions = {
123
123
  maxSkipSlots: 32,
124
124
  disableProposerSlashings: false,
125
125
  // should be less than or equal to MIN_SIGNATURE_SETS_TO_BATCH_VERIFY
126
- // batching too much may block the I/O thread so if useWorker=false, suggest this value to be 32
127
- // since this batch attestation work is designed to work with useWorker=true, make this the lowest value
128
126
  minSameMessageSignatureSetsToBatch: 2,
129
127
  // as of Feb 2025, this option turned out to be very useful:
130
128
  // - it allows to share a persisted checkpoint state to other nodes
@@ -2,6 +2,7 @@ export {SeenAggregators, SeenAttesters, SeenPayloadAttesters} from "./seenAttest
2
2
  export {SeenBlockProposers} from "./seenBlockProposers.js";
3
3
  export {SeenSyncCommitteeMessages} from "./seenCommittee.js";
4
4
  export {SeenContributionAndProof} from "./seenCommitteeContribution.js";
5
+ export {SeenDataColumnSidecars} from "./seenDataColumnSidecars.js";
5
6
  export {SeenExecutionPayloadBids} from "./seenExecutionPayloadBids.js";
6
7
  export {SeenBlockInput} from "./seenGossipBlockInput.js";
7
8
  export {PayloadEnvelopeInput, SeenPayloadEnvelopeInput} from "./seenPayloadEnvelopeInput.js";
@@ -1,9 +1,9 @@
1
1
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
2
2
  import {Epoch, RootHex, Slot, ValidatorIndex, phase0} from "@lodestar/types";
3
- import {MapDef} from "@lodestar/utils";
3
+ import {MapDef, byteArrayEquals} from "@lodestar/utils";
4
4
 
5
5
  /** Two distinct block roots signed by the same proposer for the same slot are sufficient to establish an equivocation */
6
- const MIN_EQUIVOCATION_BLOCK_ROOTS_PER_PROPOSAL = 2;
6
+ export const MIN_EQUIVOCATION_BLOCK_ROOTS_PER_PROPOSAL = 2;
7
7
 
8
8
  /**
9
9
  * Keeps a cache to filter block proposals from the same validator in the same slot.
@@ -44,6 +44,16 @@ export class SeenBlockProposers {
44
44
  return this.signedBlockHeadersBySlot.get(blockSlot)?.get(proposerIndex)?.has(blockRoot) === true;
45
45
  }
46
46
 
47
+ hasBlockSignature(
48
+ blockSlot: Slot,
49
+ proposerIndex: ValidatorIndex,
50
+ blockRoot: RootHex,
51
+ signature: Uint8Array
52
+ ): boolean {
53
+ const signedBlockHeader = this.signedBlockHeadersBySlot.get(blockSlot)?.get(proposerIndex)?.get(blockRoot);
54
+ return signedBlockHeader !== undefined && byteArrayEquals(signedBlockHeader.signature, signature);
55
+ }
56
+
47
57
  isEquivocating(blockSlot: Slot, proposerIndex: ValidatorIndex): boolean {
48
58
  return (
49
59
  (this.signedBlockHeadersBySlot.get(blockSlot)?.get(proposerIndex)?.size ?? 0) >=
@@ -0,0 +1,69 @@
1
+ import {ColumnIndex, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
2
+ import {MapDef} from "@lodestar/utils";
3
+ import {MIN_EQUIVOCATION_BLOCK_ROOTS_PER_PROPOSAL} from "./seenBlockProposers.js";
4
+
5
+ /**
6
+ * Tracks the column indices of valid gossip data column sidecars per slot, proposer and block root,
7
+ * to ignore sidecars of a repeated proposal. Sidecars are accepted for at most two block roots per slot and
8
+ * proposer, same as blocks. Pruned on finalization.
9
+ */
10
+ export class SeenDataColumnSidecars {
11
+ private readonly columnIndicesBySlot = new MapDef<Slot, MapDef<ValidatorIndex, MapDef<RootHex, Set<ColumnIndex>>>>(
12
+ () => new MapDef(() => new MapDef(() => new Set()))
13
+ );
14
+ private readonly evidenceChecksBySlot = new MapDef<Slot, Set<ValidatorIndex>>(() => new Set());
15
+ private finalizedSlot: Slot = 0;
16
+
17
+ isRepeatProposal(slot: Slot, proposerIndex: ValidatorIndex, columnIndex: ColumnIndex, blockRoot: RootHex): boolean {
18
+ const columnIndicesByRoot = this.columnIndicesBySlot.get(slot)?.get(proposerIndex);
19
+ if (columnIndicesByRoot === undefined) {
20
+ return false;
21
+ }
22
+ if (!columnIndicesByRoot.has(blockRoot) && columnIndicesByRoot.size >= MIN_EQUIVOCATION_BLOCK_ROOTS_PER_PROPOSAL) {
23
+ return true;
24
+ }
25
+ for (const [root, columnIndices] of columnIndicesByRoot) {
26
+ if (root !== blockRoot && columnIndices.has(columnIndex)) {
27
+ return true;
28
+ }
29
+ }
30
+ return false;
31
+ }
32
+
33
+ isKnown(slot: Slot, proposerIndex: ValidatorIndex, columnIndex: ColumnIndex, blockRoot: RootHex): boolean {
34
+ return this.columnIndicesBySlot.get(slot)?.get(proposerIndex)?.get(blockRoot)?.has(columnIndex) === true;
35
+ }
36
+
37
+ add(slot: Slot, proposerIndex: ValidatorIndex, columnIndex: ColumnIndex, blockRoot: RootHex): void {
38
+ if (slot < this.finalizedSlot || this.isRepeatProposal(slot, proposerIndex, columnIndex, blockRoot)) {
39
+ return;
40
+ }
41
+ this.columnIndicesBySlot.getOrDefault(slot).getOrDefault(proposerIndex).getOrDefault(blockRoot).add(columnIndex);
42
+ }
43
+
44
+ markEvidenceCheck(slot: Slot, proposerIndex: ValidatorIndex): boolean {
45
+ if (slot < this.finalizedSlot) {
46
+ return false;
47
+ }
48
+ const proposers = this.evidenceChecksBySlot.getOrDefault(slot);
49
+ if (proposers.has(proposerIndex)) {
50
+ return false;
51
+ }
52
+ proposers.add(proposerIndex);
53
+ return true;
54
+ }
55
+
56
+ prune(finalizedSlot: Slot): void {
57
+ this.finalizedSlot = finalizedSlot;
58
+ for (const slot of this.columnIndicesBySlot.keys()) {
59
+ if (slot < finalizedSlot) {
60
+ this.columnIndicesBySlot.delete(slot);
61
+ }
62
+ }
63
+ for (const slot of this.evidenceChecksBySlot.keys()) {
64
+ if (slot < finalizedSlot) {
65
+ this.evidenceChecksBySlot.delete(slot);
66
+ }
67
+ }
68
+ }
69
+ }
@@ -76,8 +76,17 @@ export async function validateGossipBlock(
76
76
  const proposerIndex = block.proposerIndex;
77
77
  if (chain.seenBlockProposers.isKnown(blockSlot, proposerIndex)) {
78
78
  if (chain.seenBlockProposers.isRepeatProposal(blockSlot, proposerIndex, blockRoot)) {
79
- const hasBlockRoot = chain.seenBlockProposers.hasBlockRoot(blockSlot, proposerIndex, blockRoot);
80
- if (!hasBlockRoot && !chain.seenBlockProposers.isEquivocating(blockSlot, proposerIndex)) {
79
+ if (chain.seenBlockProposers.hasBlockRoot(blockSlot, proposerIndex, blockRoot)) {
80
+ // The root is known with a verified signature, e.g. from the header of a data column sidecar, and a valid
81
+ // BLS signature of the same message by the same proposer is unique
82
+ if (!chain.seenBlockProposers.hasBlockSignature(blockSlot, proposerIndex, blockRoot, signedBlock.signature)) {
83
+ throw new BlockGossipError(GossipAction.REJECT, {
84
+ code: BlockErrorCode.PROPOSAL_SIGNATURE_INVALID,
85
+ slot: blockSlot,
86
+ root: blockRoot,
87
+ });
88
+ }
89
+ } else if (!chain.seenBlockProposers.isEquivocating(blockSlot, proposerIndex)) {
81
90
  await verifyBlockProposerSignature(chain, signedBlock, blockRoot, {verifyOnMainThread: false});
82
91
  chain.seenBlockProposers.observeBlockRoot(blockSlot, proposerIndex, blockRoot, signedBlockHeader);
83
92
  }
@@ -225,7 +225,7 @@ export async function validateGossipFuluDataColumnSidecar(
225
225
 
226
226
  // 12) [IGNORE] The sidecar is the first sidecar for the tuple (block_header.slot, block_header.proposer_index,
227
227
  // sidecar.index) with valid header signature, sidecar inclusion proof, and kzg proof
228
- // -- Handled in seenGossipBlockInput
228
+ // -- Handled in gossip handler with seenDataColumnSidecars
229
229
  }
230
230
 
231
231
  // SPEC FUNCTION
@@ -60,7 +60,7 @@ export async function validateApiVoluntaryExit(
60
60
  });
61
61
  }
62
62
 
63
- const signatureSet = getVoluntaryExitSignatureSet(chain.config, state, voluntaryExit);
63
+ const signatureSet = getVoluntaryExitSignatureSet(chain.config, state.slot, voluntaryExit);
64
64
  if (!(await chain.bls.verifySignatureSets([signatureSet], {batchable: true, priority: prioritizeBls}))) {
65
65
  throw new VoluntaryExitError(GossipAction.REJECT, {
66
66
  code: VoluntaryExitErrorCode.INVALID_SIGNATURE,
@@ -150,7 +150,7 @@ async function validateVoluntaryExit(
150
150
  }
151
151
 
152
152
  // [REJECT] The signature is valid
153
- const signatureSet = getVoluntaryExitSignatureSet(chain.config, state, voluntaryExit);
153
+ const signatureSet = getVoluntaryExitSignatureSet(chain.config, state.slot, voluntaryExit);
154
154
  if (!(await chain.bls.verifySignatureSets([signatureSet], {batchable: true, priority: prioritizeBls}))) {
155
155
  throw new VoluntaryExitError(GossipAction.REJECT, {
156
156
  code: VoluntaryExitErrorCode.INVALID_SIGNATURE,
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Export generic RestApi server for CLI
2
2
 
3
+ export {ServiceNotReady} from "./api/impl/errors.js";
3
4
  export type {RestApiServerMetrics, RestApiServerModules, RestApiServerOpts} from "./api/rest/base.js";
4
5
  export {RestApiServer} from "./api/rest/base.js";
5
6
  export {persistAnchorState} from "./chain/index.js";
@@ -81,9 +81,7 @@ function formatActiveResources(): string {
81
81
  }
82
82
 
83
83
  /**
84
- * This class is meant to work both:
85
- * - In a libp2p worker
86
- * - In the main thread
84
+ * This class runs in the libp2p worker.
87
85
  *
88
86
  * libp2p holds the reference to the TCP transport socket. libp2p is in a worker, what components
89
87
  * must be in a worker too?
@@ -29,10 +29,14 @@ import {Epoch} from "@lodestar/types";
29
29
  export const FORK_EPOCH_LOOKAHEAD = 2;
30
30
 
31
31
  /**
32
- * Return the list of `ForkBoundary`s meant to be active at `epoch`
32
+ * Return the fork boundaries active at any epoch in the inclusive range.
33
33
  * @see FORK_EPOCH_LOOKAHEAD for details on when fork boundaries are considered 'active'
34
34
  */
35
- export function getActiveForkBoundaries(config: ChainForkConfig, epoch: Epoch): ForkBoundary[] {
35
+ export function getActiveForkBoundaries(
36
+ config: ChainForkConfig,
37
+ fromEpoch: Epoch,
38
+ toEpoch = fromEpoch
39
+ ): ForkBoundary[] {
36
40
  const activeBoundaries: ForkBoundary[] = [];
37
41
  const {forkBoundariesAscendingEpochOrder} = config;
38
42
 
@@ -48,7 +52,7 @@ export function getActiveForkBoundaries(config: ChainForkConfig, epoch: Epoch):
48
52
  continue;
49
53
  }
50
54
 
51
- if (epoch >= currentEpoch - FORK_EPOCH_LOOKAHEAD && epoch <= nextEpoch + FORK_EPOCH_LOOKAHEAD) {
55
+ if (toEpoch >= currentEpoch - FORK_EPOCH_LOOKAHEAD && fromEpoch <= nextEpoch + FORK_EPOCH_LOOKAHEAD) {
52
56
  activeBoundaries.push(currentForkBoundary);
53
57
  }
54
58
  }
@@ -6,8 +6,8 @@ import {
6
6
  } from "@libp2p/gossipsub/score";
7
7
  import {BeaconConfig} from "@lodestar/config";
8
8
  import {ATTESTATION_SUBNET_COUNT, PTC_SIZE, SLOTS_PER_EPOCH, TARGET_AGGREGATORS_PER_COMMITTEE} from "@lodestar/params";
9
- import {computeCommitteeCount} from "@lodestar/state-transition";
10
- import {getActiveForkBoundaries} from "../forks.js";
9
+ import {computeCommitteeCount, computeStartSlotAtEpoch} from "@lodestar/state-transition";
10
+ import {FORK_EPOCH_LOOKAHEAD, getActiveForkBoundaries} from "../forks.js";
11
11
  import {Eth2Context} from "./gossipsub.js";
12
12
  import {GossipType} from "./interface.js";
13
13
  import {stringifyGossipTopic} from "./topic.js";
@@ -132,11 +132,20 @@ function getAllTopicsScoreParams(
132
132
  precomputedParams: PreComputedParams
133
133
  ): Record<string, TopicScoreParams> {
134
134
  const {epochDurationMs, slotDurationMs} = precomputedParams;
135
- const epoch = eth2Context.currentEpoch;
136
135
  const topicsParams: Record<string, TopicScoreParams> = {};
137
- const boundaries = getActiveForkBoundaries(config, epoch);
136
+ // Gossipsub copies the score parameters at construction, including those for future subscriptions.
137
+ const boundaries = getActiveForkBoundaries(config, eth2Context.currentEpoch, Infinity);
138
138
  const beaconAttestationSubnetWeight = 1 / ATTESTATION_SUBNET_COUNT;
139
139
  for (const boundary of boundaries) {
140
+ const currentSlot = Math.max(
141
+ eth2Context.currentSlot,
142
+ computeStartSlotAtEpoch(boundary.epoch - FORK_EPOCH_LOOKAHEAD)
143
+ );
144
+ // The node subscribes to a boundary's topics FORK_EPOCH_LOOKAHEAD epochs early, but peers only publish on
145
+ // them from the boundary epoch. Hold back the mesh delivery penalty until then, otherwise every mesh peer
146
+ // is penalized for an empty topic.
147
+ const subscribeEpoch = Math.max(eth2Context.currentEpoch, boundary.epoch - FORK_EPOCH_LOOKAHEAD);
148
+ const activationDelayMs = Math.max(0, boundary.epoch - subscribeEpoch) * epochDurationMs;
140
149
  //first all fixed topics
141
150
  topicsParams[
142
151
  stringifyGossipTopic(config, {
@@ -225,8 +234,8 @@ function getAllTopicsScoreParams(
225
234
  meshMessageInfo: {
226
235
  decaySlots: SLOTS_PER_EPOCH * 5,
227
236
  capFactor: 3,
228
- activationWindow: epochDurationMs,
229
- currentSlot: eth2Context.currentSlot,
237
+ activationWindow: activationDelayMs + epochDurationMs,
238
+ currentSlot,
230
239
  },
231
240
  });
232
241
  topicsParams[
@@ -241,8 +250,8 @@ function getAllTopicsScoreParams(
241
250
  meshMessageInfo: {
242
251
  decaySlots: SLOTS_PER_EPOCH * 5,
243
252
  capFactor: 3,
244
- activationWindow: epochDurationMs,
245
- currentSlot: eth2Context.currentSlot,
253
+ activationWindow: activationDelayMs + epochDurationMs,
254
+ currentSlot,
246
255
  },
247
256
  });
248
257
 
@@ -268,8 +277,8 @@ function getAllTopicsScoreParams(
268
277
  meshMessageInfo: {
269
278
  decaySlots: SLOTS_PER_EPOCH * 2,
270
279
  capFactor: 4,
271
- activationWindow: epochDurationMs,
272
- currentSlot: eth2Context.currentSlot,
280
+ activationWindow: activationDelayMs + epochDurationMs,
281
+ currentSlot,
273
282
  },
274
283
  });
275
284
 
@@ -280,10 +289,10 @@ function getAllTopicsScoreParams(
280
289
  meshMessageInfo: {
281
290
  decaySlots: multipleBurstsPerSubnetPerEpoch ? SLOTS_PER_EPOCH * 4 : SLOTS_PER_EPOCH * 16,
282
291
  capFactor: 16,
283
- activationWindow: multipleBurstsPerSubnetPerEpoch
284
- ? slotDurationMs * (SLOTS_PER_EPOCH / 2 + 1)
285
- : epochDurationMs,
286
- currentSlot: eth2Context.currentSlot,
292
+ activationWindow:
293
+ activationDelayMs +
294
+ (multipleBurstsPerSubnetPerEpoch ? slotDurationMs * (SLOTS_PER_EPOCH / 2 + 1) : epochDurationMs),
295
+ currentSlot,
287
296
  },
288
297
  });
289
298
  for (let subnet = 0; subnet < ATTESTATION_SUBNET_COUNT; subnet++) {
@@ -36,7 +36,7 @@ import {ChainEvent, IBeaconChain} from "../chain/index.js";
36
36
  import {computeSubnetForDataColumnSidecar} from "../chain/validation/dataColumnSidecar.js";
37
37
  import {GoodByeReasonCode} from "../constants/index.js";
38
38
  import {IBeaconDb} from "../db/interface.js";
39
- import {Metrics, RegistryMetricCreator} from "../metrics/index.js";
39
+ import {Metrics} from "../metrics/index.js";
40
40
  import {IClock} from "../util/clock.js";
41
41
  import {CustodyConfig} from "../util/dataColumns.js";
42
42
  import {PeerIdStr, peerIdToString} from "../util/peerId.js";
@@ -46,7 +46,7 @@ import {
46
46
  DataColumnSidecarsByRootRequest,
47
47
  ExecutionPayloadEnvelopesByRootRequest,
48
48
  } from "../util/types.js";
49
- import {INetworkCore, NetworkCore, WorkerNetworkCore} from "./core/index.js";
49
+ import {INetworkCore, WorkerNetworkCore} from "./core/index.js";
50
50
  import {INetworkEventBus, NetworkEvent, NetworkEventBus, NetworkEventData} from "./events.js";
51
51
  import {getActiveForkBoundaries} from "./forks.js";
52
52
  import {GossipHandlers, GossipTopicMap, GossipType, GossipTypeMap} from "./gossip/index.js";
@@ -100,12 +100,7 @@ export type NetworkInitModules = {
100
100
  };
101
101
 
102
102
  /**
103
- * Must support running both on worker and on main thread.
104
- *
105
- * Exists a front class that's what consumers interact with.
106
- * This class will multiplex between:
107
- * - libp2p in worker
108
- * - libp2p in main thread
103
+ * Front class that consumers interact with. libp2p runs in a worker thread.
109
104
  */
110
105
  export class Network implements INetwork {
111
106
  readonly peerId: PeerId;
@@ -173,42 +168,23 @@ export class Network implements INetwork {
173
168
  const initialStatus = chain.getStatus();
174
169
  const initialCustodyGroupCount = chain.custodyConfig.targetCustodyGroupCount;
175
170
 
176
- if (opts.useWorker) {
177
- logger.info("running libp2p instance in worker thread");
178
- }
179
-
180
- const core = opts.useWorker
181
- ? await WorkerNetworkCore.init({
182
- opts: {
183
- ...opts,
184
- peerStoreDir,
185
- metricsEnabled: Boolean(metrics),
186
- activeValidatorCount,
187
- genesisTime: chain.genesisTime,
188
- initialStatus,
189
- initialCustodyGroupCount,
190
- },
191
- config,
192
- privateKey,
193
- logger,
194
- events,
195
- metrics,
196
- getReqRespHandler,
197
- })
198
- : await NetworkCore.init({
199
- opts,
200
- config,
201
- privateKey,
202
- peerStoreDir,
203
- logger,
204
- clock: chain.clock,
205
- events,
206
- getReqRespHandler,
207
- metricsRegistry: metrics ? new RegistryMetricCreator() : null,
208
- initialStatus,
209
- initialCustodyGroupCount,
210
- activeValidatorCount,
211
- });
171
+ const core = await WorkerNetworkCore.init({
172
+ opts: {
173
+ ...opts,
174
+ peerStoreDir,
175
+ metricsEnabled: Boolean(metrics),
176
+ activeValidatorCount,
177
+ genesisTime: chain.genesisTime,
178
+ initialStatus,
179
+ initialCustodyGroupCount,
180
+ },
181
+ config,
182
+ privateKey,
183
+ logger,
184
+ events,
185
+ metrics,
186
+ getReqRespHandler,
187
+ });
212
188
 
213
189
  const networkProcessor = new NetworkProcessor(
214
190
  {chain, db, config, logger, metrics, events, gossipHandlers, core, aggregatorTracker},
@@ -28,7 +28,6 @@ export interface NetworkOptions
28
28
  /** Include the version in libp2p Identify. Private mode takes precedence. */
29
29
  advertiseVersion?: boolean;
30
30
  private?: boolean;
31
- useWorker?: boolean;
32
31
  maxYoungGenerationSizeMb?: number;
33
32
  disableLightClientServer?: boolean;
34
33
  /**
@@ -67,7 +66,6 @@ export const defaultNetworkOptions: NetworkOptions = {
67
66
  /** disabled by default */
68
67
  discv5: null,
69
68
  rateLimitMultiplier: 1,
70
- useWorker: true,
71
69
  // set after testing before 1.19.0, see https://github.com/ChainSafe/lodestar/issues/6596
72
70
  disableFloodPublish: true,
73
71
  // default set via research in https://github.com/ChainSafe/lodestar/issues/2115
@@ -4,7 +4,7 @@ import {ENR} from "@chainsafe/enr";
4
4
  import {BeaconConfig} from "@lodestar/config";
5
5
  import {LoggerNode} from "@lodestar/logger/node";
6
6
  import {ATTESTATION_SUBNET_COUNT, ForkSeq, SYNC_COMMITTEE_SUBNET_COUNT} from "@lodestar/params";
7
- import {CustodyIndex, SubnetID} from "@lodestar/types";
7
+ import {SubnetID} from "@lodestar/types";
8
8
  import {bytesToInt, pruneSetToMax, sleep, toHex} from "@lodestar/utils";
9
9
  import {IClock} from "../../util/clock.js";
10
10
  import {getCustodyGroups} from "../../util/dataColumns.js";
@@ -252,32 +252,22 @@ export class PeerDiscovery {
252
252
  }
253
253
  cachedENRsReverse.reverse();
254
254
 
255
- this.peersToConnect += peersToConnect;
255
+ this.peersToConnect = peersToConnect;
256
256
 
257
257
  // starting from PeerDAS, we need to prioritize column subnet peers first in order to have stable subnet sampling
258
- const groupsToDiscover = new Set<CustodyIndex>();
259
- let groupPeersToDiscover = 0;
260
-
261
- const forkSeq = this.config.getForkSeq(this.clock.currentSlot);
262
- if (forkSeq >= ForkSeq.fulu) {
263
- group: for (const [group, maxPeersToConnect] of custodyGroupRequests) {
264
- let cachedENRsInGroup = 0;
265
- for (const cachedENR of cachedENRsReverse) {
266
- if (cachedENR.custodyGroups?.includes(group)) {
267
- cachedENRsToDial.set(cachedENR.peerId.toString(), cachedENR);
268
-
269
- if (++cachedENRsInGroup >= maxPeersToConnect) {
270
- continue group;
271
- }
272
- }
273
-
274
- const groupPeersToConnect = Math.max(maxPeersToConnect - cachedENRsInGroup, 0);
275
- this.custodyGroupQueries.set(group, groupPeersToConnect);
276
- groupsToDiscover.add(group);
277
- groupPeersToDiscover += groupPeersToConnect;
258
+ this.custodyGroupQueries.clear();
259
+ if (this.config.getForkSeq(this.clock.currentSlot) >= ForkSeq.fulu) {
260
+ for (const [group, count] of custodyGroupRequests) {
261
+ if (count > 0) this.custodyGroupQueries.set(group, count);
262
+ }
263
+ for (const cachedENR of cachedENRsReverse) {
264
+ if (this.custodyGroupQueries.size === 0) break;
265
+ if (this.consumeCustodyGroupRequests(cachedENR)) {
266
+ cachedENRsToDial.set(cachedENR.peerId.toString(), cachedENR);
278
267
  }
279
268
  }
280
269
  }
270
+ const groupPeersToDiscover = Array.from(this.custodyGroupQueries.values()).reduce((sum, count) => sum + count, 0);
281
271
 
282
272
  subnet: for (const subnetRequest of subnetRequests) {
283
273
  // Get cached ENRs from the discovery service that are in the requested `subnetId`, but not connected yet
@@ -312,7 +302,7 @@ export class PeerDiscovery {
312
302
  }
313
303
 
314
304
  // If subnetRequests won't connect enough peers for peersToConnect, add more
315
- if (cachedENRsToDial.size < peersToConnect) {
305
+ if (groupPeersToDiscover === 0 && cachedENRsToDial.size < peersToConnect) {
316
306
  for (const cachedENR of cachedENRsReverse) {
317
307
  cachedENRsToDial.set(cachedENR.peerId.toString(), cachedENR);
318
308
  if (cachedENRsToDial.size >= peersToConnect) {
@@ -330,7 +320,8 @@ export class PeerDiscovery {
330
320
  }
331
321
 
332
322
  // Run a discv5 subnet query to try to discover new peers
333
- const shouldRunFindRandomNodeQuery = subnetsToDiscoverPeers.length > 0 || cachedENRsToDial.size < peersToConnect;
323
+ const shouldRunFindRandomNodeQuery =
324
+ groupPeersToDiscover > 0 || subnetsToDiscoverPeers.length > 0 || cachedENRsToDial.size < peersToConnect;
334
325
  if (shouldRunFindRandomNodeQuery) {
335
326
  void this.runFindRandomNodeQuery();
336
327
  }
@@ -339,7 +330,7 @@ export class PeerDiscovery {
339
330
  peersToConnect,
340
331
  peersAvailableToDial: cachedENRsToDial.size,
341
332
  subnetsToDiscover: subnetsToDiscoverPeers.length,
342
- groupsToDiscover: Array.from(groupsToDiscover).join(","),
333
+ groupsToDiscover: Array.from(this.custodyGroupQueries.keys()).join(","),
343
334
  groupPeersToDiscover,
344
335
  shouldRunFindRandomNodeQuery,
345
336
  });
@@ -411,7 +402,14 @@ export class PeerDiscovery {
411
402
  if (this.randomNodeQuery.code === QueryStatusCode.Active) {
412
403
  this.randomNodeQuery.count++;
413
404
  }
414
- const peerId = enr.peerId;
405
+ let peerId: PeerId;
406
+ try {
407
+ peerId = enr.peerId;
408
+ } catch (e) {
409
+ this.logger.debug("Discovered ENR with invalid public key", {nodeId: enr.nodeId}, e as Error);
410
+ this.metrics?.discovery.discoveredStatus.inc({status: DiscoveredPeerStatus.error});
411
+ return;
412
+ }
415
413
  // At least one transport is known to be present, checked inside the worker
416
414
  const multiaddrTCP = enr.getLocationMultiaddr(ENRKey.tcp);
417
415
  const multiaddrQUIC = enr.getLocationMultiaddr(ENRKey.quic);
@@ -530,32 +528,24 @@ export class PeerDiscovery {
530
528
  }
531
529
  }
532
530
 
533
- private shouldDialPeer(peer: CachedENR): boolean {
534
- const forkSeq = this.config.getForkSeq(this.clock.currentSlot);
535
- if (forkSeq >= ForkSeq.fulu && peer.custodyGroups !== null) {
536
- // pre-fulu `this.custodyGroupQueries` is empty
537
- // starting from fulu, we need to make sure we have stable subnet sampling peers first
538
- // given SAMPLES_PER_SLOT = 8 and 100 peers, we have 800 custody columns from peers
539
- // with NUMBER_OF_CUSTODY_GROUPS = 128, we have 800 / 128 = 6.25 peers per column in average
540
- // it would not be hard to find TARGET_SUBNET_PEERS(6) peers per sampling columns columns and TARGET_GROUP_PEERS_PER_SUBNET(4) peers per non-sampling columns
541
- // after some first heartbeats, we should have no more column requested, then go with conditions of prior forks
542
- let hasMatchingGroup = false;
543
- let custodyGroupRequestCount = 0;
544
- for (const [group, peersToConnect] of this.custodyGroupQueries.entries()) {
545
- if (peersToConnect <= 0) {
546
- this.custodyGroupQueries.delete(group);
547
- } else if (peer.custodyGroups.includes(group)) {
548
- this.custodyGroupQueries.set(group, Math.max(0, peersToConnect - 1));
549
- hasMatchingGroup = true;
550
- custodyGroupRequestCount += peersToConnect;
551
- }
552
- }
531
+ private consumeCustodyGroupRequests(peer: CachedENR): boolean {
532
+ let matched = false;
533
+ for (const group of peer.custodyGroups ?? []) {
534
+ const remaining = this.custodyGroupQueries.get(group);
535
+ if (remaining === undefined) continue;
553
536
 
554
- // if subnet sampling peers are not stable and this peer is not in the requested columns, ignore it
555
- if (custodyGroupRequestCount > 0 && !hasMatchingGroup) {
556
- this.metrics?.discovery.notDialReason.inc({reason: NotDialReason.not_contain_requested_sampling_groups});
557
- return false;
558
- }
537
+ if (remaining === 1) this.custodyGroupQueries.delete(group);
538
+ else this.custodyGroupQueries.set(group, remaining - 1);
539
+ matched = true;
540
+ }
541
+ return matched;
542
+ }
543
+
544
+ private shouldDialPeer(peer: CachedENR): boolean {
545
+ const needsCustodyPeers = this.custodyGroupQueries.size > 0;
546
+ if (needsCustodyPeers && !this.consumeCustodyGroupRequests(peer)) {
547
+ this.metrics?.discovery.notDialReason.inc({reason: NotDialReason.not_contain_requested_sampling_groups});
548
+ return false;
559
549
  }
560
550
 
561
551
  // logics up to Deneb fork
@@ -580,7 +570,7 @@ export class PeerDiscovery {
580
570
  // ideally we may want to leave this cheap condition at the top of the function
581
571
  // however we want to also update peersToConnect in this.subnetRequests
582
572
  // the this.subnetRequests[type] gradually has 0 subnet so this function should be cheap enough
583
- if (this.peersToConnect > 0) {
573
+ if (needsCustodyPeers || this.peersToConnect > 0) {
584
574
  return true;
585
575
  }
586
576