@lodestar/beacon-node 1.52.0-dev.b1d1e990d9 → 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 (136) hide show
  1. package/lib/api/impl/validator/index.d.ts.map +1 -1
  2. package/lib/api/impl/validator/index.js +13 -5
  3. package/lib/api/impl/validator/index.js.map +1 -1
  4. package/lib/chain/ColumnReconstructionTracker.d.ts +4 -0
  5. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  6. package/lib/chain/ColumnReconstructionTracker.js +4 -0
  7. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  8. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  9. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  10. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  11. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  12. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  13. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  14. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  15. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  16. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  17. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  18. package/lib/chain/blocks/index.js +0 -1
  19. package/lib/chain/blocks/index.js.map +1 -1
  20. package/lib/chain/chain.d.ts +3 -2
  21. package/lib/chain/chain.d.ts.map +1 -1
  22. package/lib/chain/chain.js +21 -2
  23. package/lib/chain/chain.js.map +1 -1
  24. package/lib/chain/errors/attestationError.d.ts +15 -1
  25. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  26. package/lib/chain/errors/attestationError.js +8 -0
  27. package/lib/chain/errors/attestationError.js.map +1 -1
  28. package/lib/chain/errors/executionPayloadEnvelope.d.ts +48 -0
  29. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  30. package/lib/chain/errors/executionPayloadEnvelope.js +7 -0
  31. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  32. package/lib/chain/lightClient/index.d.ts +13 -6
  33. package/lib/chain/lightClient/index.d.ts.map +1 -1
  34. package/lib/chain/lightClient/index.js +95 -115
  35. package/lib/chain/lightClient/index.js.map +1 -1
  36. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  37. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  38. package/lib/chain/seenCache/seenAttesters.js +1 -1
  39. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  40. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  41. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  42. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  43. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  44. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  45. package/lib/chain/validation/aggregateAndProof.js +24 -7
  46. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  47. package/lib/chain/validation/attestation.d.ts.map +1 -1
  48. package/lib/chain/validation/attestation.js +32 -16
  49. package/lib/chain/validation/attestation.js.map +1 -1
  50. package/lib/chain/validation/block.d.ts.map +1 -1
  51. package/lib/chain/validation/block.js +9 -1
  52. package/lib/chain/validation/block.js.map +1 -1
  53. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  54. package/lib/chain/validation/executionPayloadEnvelope.js +79 -4
  55. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  56. package/lib/network/gossip/gossipsub.d.ts +1 -0
  57. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  58. package/lib/network/gossip/gossipsub.js +5 -2
  59. package/lib/network/gossip/gossipsub.js.map +1 -1
  60. package/lib/network/network.d.ts.map +1 -1
  61. package/lib/network/network.js +6 -1
  62. package/lib/network/network.js.map +1 -1
  63. package/lib/network/peers/peerManager.d.ts.map +1 -1
  64. package/lib/network/peers/peerManager.js +12 -1
  65. package/lib/network/peers/peerManager.js.map +1 -1
  66. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  67. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  68. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  69. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  70. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  71. package/lib/network/processor/gossipHandlers.js +15 -6
  72. package/lib/network/processor/gossipHandlers.js.map +1 -1
  73. package/lib/network/processor/index.d.ts.map +1 -1
  74. package/lib/network/processor/index.js +4 -2
  75. package/lib/network/processor/index.js.map +1 -1
  76. package/lib/sync/range/batch.d.ts +6 -0
  77. package/lib/sync/range/batch.d.ts.map +1 -1
  78. package/lib/sync/range/batch.js +17 -0
  79. package/lib/sync/range/batch.js.map +1 -1
  80. package/lib/sync/range/chain.d.ts.map +1 -1
  81. package/lib/sync/range/chain.js +8 -1
  82. package/lib/sync/range/chain.js.map +1 -1
  83. package/lib/sync/range/range.d.ts.map +1 -1
  84. package/lib/sync/range/range.js +43 -3
  85. package/lib/sync/range/range.js.map +1 -1
  86. package/lib/sync/types.d.ts +12 -1
  87. package/lib/sync/types.d.ts.map +1 -1
  88. package/lib/sync/types.js +2 -0
  89. package/lib/sync/types.js.map +1 -1
  90. package/lib/sync/unknownBlock.d.ts +28 -1
  91. package/lib/sync/unknownBlock.d.ts.map +1 -1
  92. package/lib/sync/unknownBlock.js +294 -23
  93. package/lib/sync/unknownBlock.js.map +1 -1
  94. package/lib/sync/utils/downloadByRange.d.ts +14 -1
  95. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  96. package/lib/sync/utils/downloadByRange.js +12 -2
  97. package/lib/sync/utils/downloadByRange.js.map +1 -1
  98. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  99. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  100. package/lib/sync/utils/downloadByRoot.js +48 -5
  101. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  102. package/lib/util/eventLoop.d.ts +3 -3
  103. package/lib/util/eventLoop.d.ts.map +1 -1
  104. package/lib/util/eventLoop.js +3 -3
  105. package/lib/util/eventLoop.js.map +1 -1
  106. package/package.json +26 -26
  107. package/src/api/impl/validator/index.ts +15 -6
  108. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  109. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  110. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  111. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  112. package/src/chain/blocks/index.ts +0 -1
  113. package/src/chain/chain.ts +26 -3
  114. package/src/chain/errors/attestationError.ts +11 -1
  115. package/src/chain/errors/executionPayloadEnvelope.ts +50 -0
  116. package/src/chain/lightClient/index.ts +108 -142
  117. package/src/chain/seenCache/seenAttesters.ts +1 -1
  118. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  119. package/src/chain/validation/aggregateAndProof.ts +24 -9
  120. package/src/chain/validation/attestation.ts +31 -20
  121. package/src/chain/validation/block.ts +9 -1
  122. package/src/chain/validation/executionPayloadEnvelope.ts +87 -3
  123. package/src/network/gossip/gossipsub.ts +6 -2
  124. package/src/network/network.ts +6 -2
  125. package/src/network/peers/peerManager.ts +12 -1
  126. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  127. package/src/network/processor/gossipHandlers.ts +15 -7
  128. package/src/network/processor/index.ts +7 -2
  129. package/src/sync/range/batch.ts +20 -0
  130. package/src/sync/range/chain.ts +8 -0
  131. package/src/sync/range/range.ts +56 -3
  132. package/src/sync/types.ts +11 -0
  133. package/src/sync/unknownBlock.ts +338 -23
  134. package/src/sync/utils/downloadByRange.ts +29 -3
  135. package/src/sync/utils/downloadByRoot.ts +75 -7
  136. package/src/util/eventLoop.ts +3 -3
@@ -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(
@@ -25,7 +25,7 @@ import {getSlotDurations} from "@lodestar/state-transition";
25
25
  import {SubnetID} from "@lodestar/types";
26
26
  import {Logger, Map2d, Map2dArr} from "@lodestar/utils";
27
27
  import {RegistryMetricCreator} from "../../metrics/index.js";
28
- import {callImmediate, callInNextEventLoop} from "../../util/eventLoop.js";
28
+ import {callAfterIO, callInNextEventLoop} from "../../util/eventLoop.js";
29
29
  import {NetworkEvent, NetworkEventBus, NetworkEventData} from "../events.js";
30
30
  import {Libp2p} from "../interface.js";
31
31
  import {NetworkConfig} from "../networkConfig.js";
@@ -433,7 +433,7 @@ export class Eth2Gossipsub {
433
433
  // See https://github.com/ChainSafe/lodestar/issues/5604
434
434
  // A block arrives once per slot and cannot cause that lag, so it skips the 1ms timer delay
435
435
  if (topic.type === GossipType.beacon_block) {
436
- callImmediate(emitPendingMessage);
436
+ callAfterIO(emitPendingMessage);
437
437
  } else {
438
438
  callInNextEventLoop(emitPendingMessage);
439
439
  }
@@ -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
 
@@ -98,6 +98,7 @@ function computeStatusScore(ours: Status, theirs: Status | null, opts: Prioritiz
98
98
 
99
99
  type PeerInfo = {
100
100
  id: PeerId;
101
+ direct: boolean;
101
102
  direction: MessageStreamDirection | null;
102
103
  statusScore: StatusScore;
103
104
  attnets: phase0.AttestationSubnets;
@@ -140,6 +141,7 @@ export enum ExcessPeerDisconnectReason {
140
141
  export function prioritizePeers(
141
142
  connectedPeersInfo: {
142
143
  id: PeerId;
144
+ direct?: boolean;
143
145
  direction: MessageStreamDirection | null;
144
146
  status: Status | null;
145
147
  attnets: phase0.AttestationSubnets | null;
@@ -169,6 +171,7 @@ export function prioritizePeers(
169
171
  const connectedPeers = connectedPeersInfo.map(
170
172
  (peer): PeerInfo => ({
171
173
  id: peer.id,
174
+ direct: peer.direct ?? false,
172
175
  direction: peer.direction,
173
176
  statusScore: computeStatusScore(opts.status, peer.status, opts),
174
177
  attnets: peer.attnets ?? attnetsZero,
@@ -365,6 +368,11 @@ function pruneExcessPeers(
365
368
  const peersEligibleForPruning = sortedPeers
366
369
  // Then, iterate from highest score to lowest doing a manual filter for duties and outbound ratio
367
370
  .filter((peer) => {
371
+ // Direct peers are pinned by the operator, they count towards all targets but are never pruned
372
+ if (peer.direct) {
373
+ return false;
374
+ }
375
+
368
376
  // Peers with duties are not eligible for pruning
369
377
  if ((dutiesByPeer.get(peer) ?? 0) > 0) {
370
378
  return false;
@@ -488,11 +496,12 @@ function pruneExcessPeers(
488
496
  // otherwise we'll not able to accept new peer connection to consider better peers
489
497
  // see https://github.com/ChainSafe/lodestar/issues/5198
490
498
  const remainingPeersToDisconnect: PeerId[] = [];
491
- for (const {id} of sortedPeers) {
499
+ for (const {id, direct} of sortedPeers) {
492
500
  if (peersToDisconnectCount >= peersToDisconnectTarget) {
493
501
  break;
494
502
  }
495
503
  if (
504
+ direct ||
496
505
  noLongLivedSubnetPeersToDisconnect.includes(id) ||
497
506
  badScorePeersToDisconnect.includes(id) ||
498
507
  tooGroupedPeersToDisconnect.includes(id)
@@ -568,6 +577,10 @@ function findPeerToRemove(
568
577
  const peersOnSubnet = sortBy(peersOnMostGroupedSubnet, (peer) => peer.attnetsTrueBitIndices.length);
569
578
  let removedPeer: PeerInfo | null = null;
570
579
  for (const candidatePeer of peersOnSubnet) {
580
+ if (candidatePeer.direct) {
581
+ continue;
582
+ }
583
+
571
584
  // new logic of lodestar
572
585
  const attnetIndices = candidatePeer.attnetsTrueBitIndices;
573
586
  if (attnetIndices.length > 0) {
@@ -89,7 +89,7 @@ import {validateGossipProposerPreferences} from "../../chain/validation/proposer
89
89
  import {OpSource} from "../../chain/validatorMonitor.js";
90
90
  import {Metrics} from "../../metrics/index.js";
91
91
  import {getBlobKzgCommitments, getDataColumnSidecarSlot} from "../../util/dataColumns.js";
92
- import {callImmediate, callInNextEventLoop} from "../../util/eventLoop.js";
92
+ import {callAfterIO, callInNextEventLoop} from "../../util/eventLoop.js";
93
93
  import {INetworkCore} from "../core/index.js";
94
94
  import {NetworkEventBus} from "../events.js";
95
95
  import {
@@ -269,6 +269,16 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
269
269
  // The block is retained for unknown parent sync without full validation. Authenticate it first, this
270
270
  // does not need the parent state
271
271
  const proposerIndex = signedBlock.message.proposerIndex;
272
+ // An active proposer missing from the cache comes from a branch that finalized validators this node never
273
+ // processed, range sync recovers that branch from peer status
274
+ if (proposerIndex >= chain.pubkeyCache.size) {
275
+ throw new BlockGossipError(GossipAction.REJECT, {
276
+ code: BlockErrorCode.UNKNOWN_PROPOSER,
277
+ slot,
278
+ root: blockRootHex,
279
+ proposerIndex,
280
+ });
281
+ }
272
282
  await verifyBlockProposerSignature(chain, signedBlock, blockRootHex);
273
283
  chain.seenBlockProposers.observeBlockRoot(
274
284
  slot,
@@ -676,7 +686,7 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
676
686
  try {
677
687
  const blockInput = await validateBeaconBlock(signedBlock, topic.boundary.fork, peerIdStr, seenTimestampSec);
678
688
  // Runs after the validation result is reported, except with `network.useWorker: false`
679
- callImmediate(() => {
689
+ callAfterIO(() => {
680
690
  try {
681
691
  chain.serializedCache.set(signedBlock, serializedData);
682
692
  handleValidBeaconBlock(blockInput, peerIdStr, seenTimestampSec);
@@ -1425,13 +1435,11 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
1425
1435
  try {
1426
1436
  metrics?.inclusionListsValid.inc({source: InclusionListSource.gossip});
1427
1437
  metrics?.inclusionListsValidSize.inc(totalBytes);
1428
- // A list received before its slot within clock disparity is timely, the spec delays it until the slot
1429
- // starts. Bounded on receipt time as validation checks the slot after queueing. Late lists are untimely
1438
+ // A list received before its slot is timely, the spec delays it until the slot starts. Only gossip
1439
+ // validation bounds how early a list can be. Late lists are still stored, marked untimely
1430
1440
  const secFromSlot = chain.clock.secFromSlot(slot, seenTimestampSec);
1431
1441
  metrics?.inclusionListArrivalTime.observe(secFromSlot);
1432
- const isTimely =
1433
- secFromSlot * 1000 >= -config.MAXIMUM_GOSSIP_CLOCK_DISPARITY &&
1434
- secFromSlot * 1000 < config.getInclusionListDueMs(config.getForkName(slot));
1442
+ const isTimely = secFromSlot * 1000 < config.getInclusionListDueMs(config.getForkName(slot));
1435
1443
 
1436
1444
  const insertOutcome = chain.inclusionListStore.process(signedInclusionList, committeeIndices, isTimely);
1437
1445
  metrics?.inclusionListStore.insertOutcome.inc({insertOutcome});
@@ -1,7 +1,7 @@
1
1
  import {TopicValidatorResult} from "@libp2p/gossipsub";
2
2
  import {routes} from "@lodestar/api";
3
3
  import {ForkSeq, NUMBER_OF_COLUMNS, isForkPostGloas} from "@lodestar/params";
4
- import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
4
+ import {computeEpochAtSlot, computeStartSlotAtEpoch} from "@lodestar/state-transition";
5
5
  import {RootHex, Slot, SlotRootHex} from "@lodestar/types";
6
6
  import {Logger, MapDef, mapValues, sleep} from "@lodestar/utils";
7
7
  import {BlockInputSource} from "../../chain/blocks/blockInput/types.js";
@@ -947,8 +947,13 @@ export class NetworkProcessor {
947
947
  this.bufferedRootsBySlot.delete(slot);
948
948
  }
949
949
 
950
+ // A slot's search budget lives as long as gossip accepts messages for it, a pruned budget would start over
951
+ const minSearchedSlot = Math.min(
952
+ clockSlot - DEFAULT_EARLIEST_PERMISSIBLE_SLOT_DISTANCE,
953
+ computeStartSlotAtEpoch(computeEpochAtSlot(clockSlot) - 1)
954
+ );
950
955
  for (const slot of this.searchedRootsBySlot.keys()) {
951
- if (slot <= minSlot) this.searchedRootsBySlot.delete(slot);
956
+ if (slot < minSearchedSlot) this.searchedRootsBySlot.delete(slot);
952
957
  }
953
958
 
954
959
  for (const [peer, slot] of this.fatalPeers) {
@@ -633,6 +633,26 @@ export class Batch {
633
633
  };
634
634
  }
635
635
 
636
+ /**
637
+ * Downloading -> AwaitingDownload
638
+ *
639
+ * The batch may hold an evicted invalid block, drop every downloaded block and request the whole batch again
640
+ */
641
+ downloadingInvalidBlock(peer: PeerIdStr): void {
642
+ if (this.state.status !== BatchStatus.Downloading) {
643
+ throw new BatchError(this.wrongStatusErrorType(BatchStatus.Downloading));
644
+ }
645
+
646
+ this.failedDownloadAttempts.push(peer);
647
+ if (this.failedDownloadAttempts.length > MAX_BATCH_DOWNLOAD_ATTEMPTS) {
648
+ throw new BatchError(this.errorType({code: BatchErrorCode.MAX_DOWNLOAD_ATTEMPTS}));
649
+ }
650
+
651
+ this.successfulDownloads.clear();
652
+ this.state = {status: BatchStatus.AwaitingDownload, blocks: [], payloadEnvelopes: null};
653
+ this.resetRequests();
654
+ }
655
+
636
656
  /**
637
657
  * Downloading -> AwaitingDownload (without counting as a failed attempt).
638
658
  * Used when the peer rate-limited us — the request was never actually served.
@@ -602,6 +602,14 @@ export class SyncChain {
602
602
  this.scheduleRateLimitBackoffRetry();
603
603
  batch.downloadingRateLimited();
604
604
  this.triggerBatchDownloader();
605
+ } else if (
606
+ res.err instanceof DownloadByRangeError &&
607
+ res.err.type.code === DownloadByRangeErrorCode.INVALID_CACHED_BLOCK
608
+ ) {
609
+ if (res.err.type.blockPeer !== undefined) {
610
+ this.reportPeer(res.err.type.blockPeer, PeerAction.LowToleranceError, res.err.message);
611
+ }
612
+ batch.downloadingInvalidBlock(res.err.type.blockPeer ?? peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
605
613
  } else {
606
614
  batch.downloadingError(peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
607
615
  }
@@ -3,13 +3,20 @@ import {StrictEventEmitter} from "strict-event-emitter-types";
3
3
  import {BeaconConfig} from "@lodestar/config";
4
4
  import {IBeaconStateViewGloas, computeStartSlotAtEpoch, isStatePostGloas} from "@lodestar/state-transition";
5
5
  import {Epoch, Status, fulu, ssz} from "@lodestar/types";
6
- import {Logger, byteArrayEquals, prettyPrintIndices, toRootHex} from "@lodestar/utils";
6
+ import {Logger, byteArrayEquals, prettyPrintIndices, toHex, toRootHex} from "@lodestar/utils";
7
7
  import {IBlockInput} from "../../chain/blocks/blockInput/types.js";
8
8
  import {PayloadError, PayloadErrorCode} from "../../chain/blocks/importExecutionPayload.js";
9
9
  import {AttestationImportOpt, ImportBlockOpts} from "../../chain/blocks/index.js";
10
10
  import {assertLinearChainSegment} from "../../chain/blocks/utils/chainSegment.js";
11
- import {BlockError} from "../../chain/errors/index.js";
11
+ import {
12
+ BlockError,
13
+ BlockErrorCode,
14
+ BlockGossipError,
15
+ DataColumnSidecarErrorCode,
16
+ DataColumnSidecarValidationError,
17
+ } from "../../chain/errors/index.js";
12
18
  import {IBeaconChain} from "../../chain/index.js";
19
+ import {verifyBlockProposerSignature} from "../../chain/validation/block.js";
13
20
  import {Metrics} from "../../metrics/index.js";
14
21
  import {INetwork} from "../../network/index.js";
15
22
  import {PeerIdStr} from "../../util/peerId.js";
@@ -291,7 +298,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
291
298
  ...requests,
292
299
  });
293
300
  const {responses, payloadEnvelopes: downloadedPayloadEnvelopes} = result;
294
- const {blocks, payloadEnvelopes} = cacheByRangeResponses({
301
+ const {blocks, payloadEnvelopes, signatureMismatch} = cacheByRangeResponses({
295
302
  cache: this.chain.seenBlockInputCache,
296
303
  seenPayloadEnvelopeInputCache: this.chain.seenPayloadEnvelopeInputCache,
297
304
  peerIdStr: peer.peerId,
@@ -304,6 +311,52 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
304
311
  seenTimestampSec: Date.now() / 1000,
305
312
  });
306
313
 
314
+ if (signatureMismatch !== null) {
315
+ const {blockInput, columnSidecar} = signatureMismatch;
316
+ const block = blockInput.getBlock();
317
+ let isValidBlockSignature: boolean | null = true;
318
+ try {
319
+ await verifyBlockProposerSignature(this.chain, block, blockInput.blockRootHex);
320
+ } catch (e) {
321
+ isValidBlockSignature =
322
+ e instanceof BlockGossipError && e.type.code === BlockErrorCode.PROPOSAL_SIGNATURE_INVALID ? false : null;
323
+ }
324
+
325
+ if (isValidBlockSignature) {
326
+ throw new DataColumnSidecarValidationError(
327
+ {
328
+ code: DataColumnSidecarErrorCode.INCORRECT_BLOCK,
329
+ slot: blockInput.slot,
330
+ columnIndex: columnSidecar.index,
331
+ expected: toHex(block.signature),
332
+ actual: toHex(columnSidecar.signedBlockHeader.signature),
333
+ },
334
+ "DataColumnSidecar header signature doesn't match block signature"
335
+ );
336
+ }
337
+
338
+ // Later downloads reuse a cached block, evict it and the other unverified blocks of a peer
339
+ // proven to serve invalid signatures
340
+ const blockPeer = isValidBlockSignature === false ? blockInput.getBlockSource().peerIdStr : undefined;
341
+ const cache = this.chain.seenBlockInputCache;
342
+ for (const b of blocks) {
343
+ const isSuspect = b === blockInput || (blockPeer !== undefined && b.getBlockSource().peerIdStr === blockPeer);
344
+ if (
345
+ isSuspect &&
346
+ cache.get(b.blockRootHex) === b &&
347
+ !cache.isVerifiedProposerSignature(b.slot, b.blockRootHex, b.getBlock().signature)
348
+ ) {
349
+ cache.remove(b.blockRootHex);
350
+ }
351
+ }
352
+ throw new DownloadByRangeError({
353
+ code: DownloadByRangeErrorCode.INVALID_CACHED_BLOCK,
354
+ slot: blockInput.slot,
355
+ blockRoot: blockInput.blockRootHex,
356
+ blockPeer,
357
+ });
358
+ }
359
+
307
360
  const segmentBlocks = blocks.filter((b) => b.hasBlock()).sort((a, b) => a.slot - b.slot);
308
361
  const envelopeSlots = payloadEnvelopes
309
362
  ? Array.from(payloadEnvelopes.entries())
package/src/sync/types.ts CHANGED
@@ -107,6 +107,8 @@ export enum DroppedItemReason {
107
107
  invalidSignature = "invalid_signature",
108
108
  /** an unexpected / unhandled error code led to removal */
109
109
  unknown = "unknown",
110
+ /** a block waiting on its parent was evicted because the peer that gossiped it exceeded its byte budget */
111
+ peerBudget = "peer_budget",
110
112
  }
111
113
 
112
114
  export enum PendingPayloadInputStatus {
@@ -123,6 +125,12 @@ export type PendingBlockInput = {
123
125
  timeAddedSec: number;
124
126
  timeSyncedSec?: number;
125
127
  peerIdStrings: Set<string>;
128
+ /** Peer that gossiped a block retained for unknown parent sync */
129
+ retainedBy?: string;
130
+ retainedBytes?: number;
131
+ failedDownloads?: number;
132
+ /** A failed download is not retried before this time */
133
+ retryAtMs?: number;
126
134
  };
127
135
 
128
136
  export type PendingRootHex = {
@@ -131,6 +139,9 @@ export type PendingRootHex = {
131
139
  timeAddedSec: number;
132
140
  timeSyncedSec?: number;
133
141
  peerIdStrings: Set<string>;
142
+ failedDownloads?: number;
143
+ /** A failed download is not retried before this time */
144
+ retryAtMs?: number;
134
145
  };
135
146
 
136
147
  export type BlockInputSyncCacheItem = PendingBlockInput | PendingRootHex;