@lodestar/beacon-node 2.1.0-dev.7438ca57ce → 2.1.0-dev.76e8ca15f1

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 (197) 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/beacon/pool/index.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/pool/index.js +8 -0
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/index.d.ts.map +1 -1
  8. package/lib/api/impl/beacon/state/index.js +3 -2
  9. package/lib/api/impl/beacon/state/index.js.map +1 -1
  10. package/lib/api/impl/beacon/state/utils.js +1 -1
  11. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  12. package/lib/api/impl/errors.d.ts +7 -0
  13. package/lib/api/impl/errors.d.ts.map +1 -1
  14. package/lib/api/impl/errors.js +9 -0
  15. package/lib/api/impl/errors.js.map +1 -1
  16. package/lib/api/impl/validator/index.js +1 -1
  17. package/lib/api/impl/validator/index.js.map +1 -1
  18. package/lib/api/rest/base.d.ts.map +1 -1
  19. package/lib/api/rest/base.js +6 -3
  20. package/lib/api/rest/base.js.map +1 -1
  21. package/lib/chain/ColumnReconstructionTracker.d.ts +3 -0
  22. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  23. package/lib/chain/ColumnReconstructionTracker.js +3 -1
  24. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  25. package/lib/chain/GetBlobsTracker.d.ts +3 -0
  26. package/lib/chain/GetBlobsTracker.d.ts.map +1 -1
  27. package/lib/chain/GetBlobsTracker.js +3 -1
  28. package/lib/chain/GetBlobsTracker.js.map +1 -1
  29. package/lib/chain/blocks/importBlock.d.ts.map +1 -1
  30. package/lib/chain/blocks/importBlock.js +14 -5
  31. package/lib/chain/blocks/importBlock.js.map +1 -1
  32. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  33. package/lib/chain/blocks/importExecutionPayload.js +4 -2
  34. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  35. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts +2 -1
  36. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts.map +1 -1
  37. package/lib/chain/chain.d.ts +2 -1
  38. package/lib/chain/chain.d.ts.map +1 -1
  39. package/lib/chain/chain.js +29 -6
  40. package/lib/chain/chain.js.map +1 -1
  41. package/lib/chain/errors/dataColumnSidecarError.d.ts +7 -0
  42. package/lib/chain/errors/dataColumnSidecarError.d.ts.map +1 -1
  43. package/lib/chain/errors/dataColumnSidecarError.js +1 -0
  44. package/lib/chain/errors/dataColumnSidecarError.js.map +1 -1
  45. package/lib/chain/forkChoice/index.d.ts +11 -2
  46. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  47. package/lib/chain/forkChoice/index.js +180 -13
  48. package/lib/chain/forkChoice/index.js.map +1 -1
  49. package/lib/chain/interface.d.ts +2 -1
  50. package/lib/chain/interface.d.ts.map +1 -1
  51. package/lib/chain/interface.js.map +1 -1
  52. package/lib/chain/opPools/opPool.d.ts +9 -3
  53. package/lib/chain/opPools/opPool.d.ts.map +1 -1
  54. package/lib/chain/opPools/opPool.js +22 -16
  55. package/lib/chain/opPools/opPool.js.map +1 -1
  56. package/lib/chain/options.d.ts.map +1 -1
  57. package/lib/chain/options.js +1 -2
  58. package/lib/chain/options.js.map +1 -1
  59. package/lib/chain/seenCache/index.d.ts +1 -0
  60. package/lib/chain/seenCache/index.d.ts.map +1 -1
  61. package/lib/chain/seenCache/index.js +1 -0
  62. package/lib/chain/seenCache/index.js.map +1 -1
  63. package/lib/chain/seenCache/seenBlockProposers.d.ts +3 -0
  64. package/lib/chain/seenCache/seenBlockProposers.d.ts.map +1 -1
  65. package/lib/chain/seenCache/seenBlockProposers.js +6 -2
  66. package/lib/chain/seenCache/seenBlockProposers.js.map +1 -1
  67. package/lib/chain/seenCache/seenDataColumnSidecars.d.ts +17 -0
  68. package/lib/chain/seenCache/seenDataColumnSidecars.d.ts.map +1 -0
  69. package/lib/chain/seenCache/seenDataColumnSidecars.js +61 -0
  70. package/lib/chain/seenCache/seenDataColumnSidecars.js.map +1 -0
  71. package/lib/chain/seenCache/seenGossipBlockInput.js +1 -1
  72. package/lib/chain/seenCache/seenGossipBlockInput.js.map +1 -1
  73. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts +11 -2
  74. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts.map +1 -1
  75. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js +28 -2
  76. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js.map +1 -1
  77. package/lib/chain/validation/attestation.d.ts.map +1 -1
  78. package/lib/chain/validation/attestation.js +4 -2
  79. package/lib/chain/validation/attestation.js.map +1 -1
  80. package/lib/chain/validation/block.d.ts.map +1 -1
  81. package/lib/chain/validation/block.js +20 -7
  82. package/lib/chain/validation/block.js.map +1 -1
  83. package/lib/chain/validation/dataColumnSidecar.js +1 -1
  84. package/lib/chain/validation/dataColumnSidecar.js.map +1 -1
  85. package/lib/chain/validation/proposerSlashing.js +5 -1
  86. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  87. package/lib/chain/validation/voluntaryExit.js +2 -2
  88. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  89. package/lib/index.d.ts +1 -0
  90. package/lib/index.d.ts.map +1 -1
  91. package/lib/index.js +1 -0
  92. package/lib/index.js.map +1 -1
  93. package/lib/network/core/networkCore.d.ts +1 -3
  94. package/lib/network/core/networkCore.d.ts.map +1 -1
  95. package/lib/network/core/networkCore.js +1 -3
  96. package/lib/network/core/networkCore.js.map +1 -1
  97. package/lib/network/forks.d.ts +2 -2
  98. package/lib/network/forks.d.ts.map +1 -1
  99. package/lib/network/forks.js +3 -3
  100. package/lib/network/forks.js.map +1 -1
  101. package/lib/network/gossip/scoringParameters.js +19 -14
  102. package/lib/network/gossip/scoringParameters.js.map +1 -1
  103. package/lib/network/network.d.ts +1 -6
  104. package/lib/network/network.d.ts.map +1 -1
  105. package/lib/network/network.js +16 -40
  106. package/lib/network/network.js.map +1 -1
  107. package/lib/network/options.d.ts +0 -1
  108. package/lib/network/options.d.ts.map +1 -1
  109. package/lib/network/options.js +0 -1
  110. package/lib/network/options.js.map +1 -1
  111. package/lib/network/peers/discover.d.ts +1 -0
  112. package/lib/network/peers/discover.d.ts.map +1 -1
  113. package/lib/network/peers/discover.js +44 -48
  114. package/lib/network/peers/discover.js.map +1 -1
  115. package/lib/network/peers/score/store.d.ts.map +1 -1
  116. package/lib/network/peers/score/store.js +1 -2
  117. package/lib/network/peers/score/store.js.map +1 -1
  118. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  119. package/lib/network/processor/gossipHandlers.js +85 -17
  120. package/lib/network/processor/gossipHandlers.js.map +1 -1
  121. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.d.ts.map +1 -1
  122. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +3 -1
  123. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  124. package/lib/sync/range/chain.d.ts.map +1 -1
  125. package/lib/sync/range/chain.js +1 -0
  126. package/lib/sync/range/chain.js.map +1 -1
  127. package/lib/sync/range/range.d.ts.map +1 -1
  128. package/lib/sync/range/range.js +5 -1
  129. package/lib/sync/range/range.js.map +1 -1
  130. package/lib/sync/unknownBlock.d.ts.map +1 -1
  131. package/lib/sync/unknownBlock.js +14 -1
  132. package/lib/sync/unknownBlock.js.map +1 -1
  133. package/lib/sync/utils/downloadByRange.d.ts +6 -0
  134. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  135. package/lib/sync/utils/downloadByRange.js +17 -8
  136. package/lib/sync/utils/downloadByRange.js.map +1 -1
  137. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  138. package/lib/sync/utils/downloadByRoot.js +1 -1
  139. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  140. package/lib/sync/utils/pendingBlocksTree.d.ts.map +1 -1
  141. package/lib/sync/utils/pendingBlocksTree.js +6 -1
  142. package/lib/sync/utils/pendingBlocksTree.js.map +1 -1
  143. package/lib/util/dataColumns.d.ts +2 -1
  144. package/lib/util/dataColumns.d.ts.map +1 -1
  145. package/lib/util/dataColumns.js +7 -2
  146. package/lib/util/dataColumns.js.map +1 -1
  147. package/lib/util/execution.d.ts +2 -1
  148. package/lib/util/execution.d.ts.map +1 -1
  149. package/lib/util/execution.js +7 -2
  150. package/lib/util/execution.js.map +1 -1
  151. package/package.json +18 -21
  152. package/src/api/impl/beacon/blocks/index.ts +1 -5
  153. package/src/api/impl/beacon/pool/index.ts +11 -0
  154. package/src/api/impl/beacon/state/index.ts +3 -7
  155. package/src/api/impl/beacon/state/utils.ts +1 -1
  156. package/src/api/impl/errors.ts +10 -0
  157. package/src/api/impl/validator/index.ts +1 -1
  158. package/src/api/rest/base.ts +9 -3
  159. package/src/chain/ColumnReconstructionTracker.ts +5 -1
  160. package/src/chain/GetBlobsTracker.ts +5 -0
  161. package/src/chain/blocks/importBlock.ts +14 -7
  162. package/src/chain/blocks/importExecutionPayload.ts +4 -2
  163. package/src/chain/blocks/payloadEnvelopeInput/types.ts +8 -1
  164. package/src/chain/chain.ts +34 -5
  165. package/src/chain/errors/dataColumnSidecarError.ts +8 -0
  166. package/src/chain/forkChoice/index.ts +233 -13
  167. package/src/chain/interface.ts +2 -0
  168. package/src/chain/opPools/opPool.ts +27 -16
  169. package/src/chain/options.ts +1 -2
  170. package/src/chain/seenCache/index.ts +1 -0
  171. package/src/chain/seenCache/seenBlockProposers.ts +12 -2
  172. package/src/chain/seenCache/seenDataColumnSidecars.ts +69 -0
  173. package/src/chain/seenCache/seenGossipBlockInput.ts +1 -1
  174. package/src/chain/seenCache/seenPayloadEnvelopeInput.ts +28 -2
  175. package/src/chain/validation/attestation.ts +4 -2
  176. package/src/chain/validation/block.ts +19 -7
  177. package/src/chain/validation/dataColumnSidecar.ts +1 -1
  178. package/src/chain/validation/proposerSlashing.ts +5 -1
  179. package/src/chain/validation/voluntaryExit.ts +2 -2
  180. package/src/index.ts +1 -0
  181. package/src/network/core/networkCore.ts +1 -3
  182. package/src/network/forks.ts +7 -3
  183. package/src/network/gossip/scoringParameters.ts +23 -14
  184. package/src/network/network.ts +20 -44
  185. package/src/network/options.ts +0 -2
  186. package/src/network/peers/discover.ts +42 -52
  187. package/src/network/peers/score/store.ts +1 -2
  188. package/src/network/processor/gossipHandlers.ts +147 -25
  189. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +4 -1
  190. package/src/sync/range/chain.ts +1 -0
  191. package/src/sync/range/range.ts +7 -1
  192. package/src/sync/unknownBlock.ts +20 -1
  193. package/src/sync/utils/downloadByRange.ts +30 -7
  194. package/src/sync/utils/downloadByRoot.ts +12 -9
  195. package/src/sync/utils/pendingBlocksTree.ts +6 -1
  196. package/src/util/dataColumns.ts +13 -1
  197. package/src/util/execution.ts +16 -1
@@ -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
  }
@@ -98,13 +107,16 @@ export async function validateGossipBlock(
98
107
  // If fork choice does *not* consider the parent to be a descendant of the finalized block,
99
108
  // then there are two more cases:
100
109
  //
101
- // 1. We have the parent stored in our database. Because fork-choice has confirmed the
102
- // parent is *not* in our post-finalization DAG, all other blocks must be either
103
- // pre-finalization or conflicting with finalization.
110
+ // 1. Fork choice still holds the parent. Because it is *not* in our post-finalization DAG,
111
+ // the parent is either pre-finalization or conflicting with finalization, so the
112
+ // finalized checkpoint is not an ancestor of the block: REJECT.
104
113
  // 2. The parent is unknown to us, we probably want to download it since it might actually
105
114
  // descend from the finalized root.
106
- // (Non-Lighthouse): Since we prune all blocks non-descendant from finalized checking the `db.block` database won't be useful to guard
107
- // against known bad fork blocks, so we throw PARENT_BLOCK_UNKNOWN for cases (1) and (2)
115
+ // Blocks that fork choice has already pruned fall into case (2), as the `db.block` database
116
+ // does not keep non-descendants of the finalized block either.
117
+ if (chain.forkChoice.hasBlockHexUnsafe(parentRoot)) {
118
+ throw new BlockGossipError(GossipAction.REJECT, {code: BlockErrorCode.NOT_FINALIZED_DESCENDANT, parentRoot});
119
+ }
108
120
  throw new BlockGossipError(GossipAction.IGNORE, {code: BlockErrorCode.PARENT_BLOCK_UNKNOWN, parentRoot});
109
121
  }
110
122
 
@@ -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
@@ -36,7 +36,11 @@ async function validateProposerSlashing(
36
36
 
37
37
  // [REJECT] All of the conditions within process_proposer_slashing pass validation.
38
38
  try {
39
- const proposer = state.getValidator(proposerSlashing.signedHeader1.message.proposerIndex);
39
+ const {proposerIndex} = proposerSlashing.signedHeader1.message;
40
+ if (proposerIndex >= state.validatorCount) {
41
+ throw Error(`Unknown proposer index ${proposerIndex}`);
42
+ }
43
+ const proposer = state.getValidator(proposerIndex);
40
44
  // verifySignature = false, verified in batch below
41
45
  assertValidProposerSlashing(chain.config, state.slot, proposerSlashing, proposer, false);
42
46
  } catch (e) {
@@ -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
 
@@ -85,8 +85,7 @@ export class PeerRpcScoreStore implements IPeerRpcScoreStore {
85
85
  for (const [peerIdStr, peerScore] of this.scores) {
86
86
  const newScore = peerScore.update();
87
87
 
88
- // Prune scores below threshold
89
- if (Math.abs(newScore) < SCORE_THRESHOLD) {
88
+ if (Math.abs(newScore) < SCORE_THRESHOLD && !peerScore.isCoolingDown()) {
90
89
  this.scores.delete(peerIdStr);
91
90
  }
92
91
  }