@lodestar/beacon-node 1.52.0-dev.dad8e3af98 → 1.52.0-dev.deb8a48a68

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 (142) hide show
  1. package/lib/api/impl/validator/index.d.ts.map +1 -1
  2. package/lib/api/impl/validator/index.js +2 -4
  3. package/lib/api/impl/validator/index.js.map +1 -1
  4. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  5. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  6. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  7. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  8. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  9. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  10. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  11. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  12. package/lib/chain/errors/executionPayloadBid.js +1 -0
  13. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  14. package/lib/chain/errors/executionPayloadEnvelope.d.ts +7 -0
  15. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  16. package/lib/chain/errors/executionPayloadEnvelope.js +1 -0
  17. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  18. package/lib/chain/lightClient/index.d.ts +13 -6
  19. package/lib/chain/lightClient/index.d.ts.map +1 -1
  20. package/lib/chain/lightClient/index.js +95 -115
  21. package/lib/chain/lightClient/index.js.map +1 -1
  22. package/lib/chain/prepareNextSlot.d.ts +45 -0
  23. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  24. package/lib/chain/prepareNextSlot.js +265 -69
  25. package/lib/chain/prepareNextSlot.js.map +1 -1
  26. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  27. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  28. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  29. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  30. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  31. package/lib/chain/validation/executionPayloadBid.js +17 -2
  32. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  33. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  34. package/lib/chain/validation/executionPayloadEnvelope.js +21 -5
  35. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  36. package/lib/execution/engine/blockHash.d.ts +12 -0
  37. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  38. package/lib/execution/engine/blockHash.js +17 -0
  39. package/lib/execution/engine/blockHash.js.map +1 -0
  40. package/lib/execution/engine/http.d.ts +2 -2
  41. package/lib/execution/engine/http.d.ts.map +1 -1
  42. package/lib/execution/engine/http.js +13 -7
  43. package/lib/execution/engine/http.js.map +1 -1
  44. package/lib/execution/engine/interface.d.ts +16 -3
  45. package/lib/execution/engine/interface.d.ts.map +1 -1
  46. package/lib/execution/engine/interface.js +11 -0
  47. package/lib/execution/engine/interface.js.map +1 -1
  48. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  49. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  50. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  51. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  52. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  53. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  54. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  55. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  56. package/lib/execution/engine/mock.d.ts.map +1 -1
  57. package/lib/execution/engine/mock.js +6 -6
  58. package/lib/execution/engine/mock.js.map +1 -1
  59. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  60. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  61. package/lib/execution/engine/payloadIdCache.js +7 -2
  62. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  63. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  64. package/lib/execution/engine/restHttpClient.js +9 -5
  65. package/lib/execution/engine/restHttpClient.js.map +1 -1
  66. package/lib/execution/engine/restTransport.d.ts +2 -2
  67. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  68. package/lib/execution/engine/restTransport.js +4 -4
  69. package/lib/execution/engine/restTransport.js.map +1 -1
  70. package/lib/execution/engine/signal.d.ts +6 -0
  71. package/lib/execution/engine/signal.d.ts.map +1 -0
  72. package/lib/execution/engine/signal.js +24 -0
  73. package/lib/execution/engine/signal.js.map +1 -0
  74. package/lib/execution/engine/transport.d.ts +2 -2
  75. package/lib/execution/engine/transport.d.ts.map +1 -1
  76. package/lib/index.d.ts +1 -1
  77. package/lib/index.d.ts.map +1 -1
  78. package/lib/index.js +1 -1
  79. package/lib/index.js.map +1 -1
  80. package/lib/metrics/metrics/beacon.d.ts +5 -0
  81. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  82. package/lib/metrics/metrics/beacon.js +5 -0
  83. package/lib/metrics/metrics/beacon.js.map +1 -1
  84. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  85. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  86. package/lib/metrics/metrics/lodestar.js +5 -0
  87. package/lib/metrics/metrics/lodestar.js.map +1 -1
  88. package/lib/network/gossip/gossipsub.d.ts +1 -0
  89. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  90. package/lib/network/gossip/gossipsub.js +3 -0
  91. package/lib/network/gossip/gossipsub.js.map +1 -1
  92. package/lib/network/network.d.ts.map +1 -1
  93. package/lib/network/network.js +6 -1
  94. package/lib/network/network.js.map +1 -1
  95. package/lib/network/peers/peerManager.d.ts.map +1 -1
  96. package/lib/network/peers/peerManager.js +22 -2
  97. package/lib/network/peers/peerManager.js.map +1 -1
  98. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  99. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  100. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  101. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  102. package/lib/sync/types.d.ts +2 -0
  103. package/lib/sync/types.d.ts.map +1 -1
  104. package/lib/sync/types.js.map +1 -1
  105. package/lib/sync/unknownBlock.d.ts.map +1 -1
  106. package/lib/sync/unknownBlock.js +123 -22
  107. package/lib/sync/unknownBlock.js.map +1 -1
  108. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  109. package/lib/sync/utils/downloadByRoot.js +5 -4
  110. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  111. package/package.json +26 -26
  112. package/src/api/impl/validator/index.ts +2 -4
  113. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  114. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  115. package/src/chain/errors/executionPayloadBid.ts +6 -0
  116. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  117. package/src/chain/lightClient/index.ts +108 -142
  118. package/src/chain/prepareNextSlot.ts +347 -89
  119. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  120. package/src/chain/validation/executionPayloadBid.ts +20 -2
  121. package/src/chain/validation/executionPayloadEnvelope.ts +28 -5
  122. package/src/execution/engine/blockHash.ts +27 -0
  123. package/src/execution/engine/http.ts +18 -10
  124. package/src/execution/engine/interface.ts +18 -3
  125. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  126. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  127. package/src/execution/engine/mock.ts +13 -8
  128. package/src/execution/engine/payloadIdCache.ts +12 -4
  129. package/src/execution/engine/restHttpClient.ts +17 -11
  130. package/src/execution/engine/restTransport.ts +5 -4
  131. package/src/execution/engine/signal.ts +28 -0
  132. package/src/execution/engine/transport.ts +3 -2
  133. package/src/index.ts +6 -1
  134. package/src/metrics/metrics/beacon.ts +9 -0
  135. package/src/metrics/metrics/lodestar.ts +5 -0
  136. package/src/network/gossip/gossipsub.ts +4 -0
  137. package/src/network/network.ts +6 -2
  138. package/src/network/peers/peerManager.ts +26 -2
  139. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  140. package/src/sync/types.ts +2 -0
  141. package/src/sync/unknownBlock.ts +133 -23
  142. package/src/sync/utils/downloadByRoot.ts +7 -5
@@ -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> {
@@ -449,7 +449,8 @@ export class PeerManager {
449
449
  .catch((e) => this.logger.verbose("cannot tag peer", {peerId: peer.toString()}, e as Error));
450
450
  peerData.relevantStatus = RelevantPeerStatus.relevant;
451
451
  }
452
- if (getConnection(this.libp2p, peer.toString())) {
452
+ // A peer rejected on connect is not tracked and may still send a status before its goodbye completes
453
+ if (peerData && getConnection(this.libp2p, peer.toString())) {
453
454
  const nodeId = peerData?.nodeId ?? computeNodeId(peer);
454
455
  // TODO(fulu): Are we sure we've run Metadata before this?
455
456
  const custodyGroupCount = peerData?.metadata?.custodyGroupCount ?? this.config.CUSTODY_REQUIREMENT;
@@ -554,6 +555,11 @@ export class PeerManager {
554
555
  // ban and disconnect peers with bad score, collect rest of healthy peers
555
556
  const connectedHealthyPeers: PeerId[] = [];
556
557
  for (const peer of connectedPeers) {
558
+ // Direct peers are trusted by the operator, a bad score never disconnects them
559
+ if (this.gossipsub.isDirectPeer(peer.toString())) {
560
+ connectedHealthyPeers.push(peer);
561
+ continue;
562
+ }
557
563
  switch (this.peerRpcScores.getScoreState(peer)) {
558
564
  case ScoreState.Banned:
559
565
  this.metrics?.peerManager.peersPruned.inc({reason: "banned"});
@@ -584,9 +590,11 @@ export class PeerManager {
584
590
  const prioritizeTimer = this.metrics?.peerManager.prioritizePeersDuration.startTimer();
585
591
  const {peersToDisconnect, peersToConnect, attnetQueries, syncnetQueries, custodyGroupQueries} = prioritizePeers(
586
592
  connectedHealthyPeers.map((peer) => {
587
- const peerData = this.connectedPeers.get(peer.toString());
593
+ const peerIdStr = peer.toString();
594
+ const peerData = this.connectedPeers.get(peerIdStr);
588
595
  return {
589
596
  id: peer,
597
+ direct: this.gossipsub.isDirectPeer(peerIdStr),
590
598
  direction: peerData?.direction ?? null,
591
599
  status: peerData?.status ?? null,
592
600
  attnets: peerData?.metadata?.attnets ?? null,
@@ -708,6 +716,10 @@ export class PeerManager {
708
716
  private updateGossipsubScores(): void {
709
717
  const gossipsubScores = new Map<string, number>();
710
718
  for (const peerIdStr of this.connectedPeers.keys()) {
719
+ // Direct peers are never disconnected, they must not take the negative score allowance of other peers
720
+ if (this.gossipsub.isDirectPeer(peerIdStr)) {
721
+ continue;
722
+ }
711
723
  gossipsubScores.set(peerIdStr, this.gossipsub.getScore(peerIdStr));
712
724
  }
713
725
 
@@ -786,6 +798,18 @@ export class PeerManager {
786
798
  return false;
787
799
  }
788
800
 
801
+ // The heartbeat only disconnects peers that are already connected, a peer with a bad score
802
+ // could otherwise reconnect right after and stay connected until the next heartbeat
803
+ const scoreState = this.peerRpcScores.getScoreState(remotePeer);
804
+ if (scoreState !== ScoreState.Healthy && !this.gossipsub.isDirectPeer(remotePeerStr)) {
805
+ this.logger.debug("Peer with bad score connected, disconnecting", {peer: remotePeerPrettyStr, scoreState});
806
+ void this.goodbyeAndDisconnect(
807
+ remotePeer,
808
+ scoreState === ScoreState.Banned ? GoodByeReasonCode.BANNED : GoodByeReasonCode.SCORE_TOO_LOW
809
+ );
810
+ return false;
811
+ }
812
+
789
813
  if (!opts.overwriteExisting && this.connectedPeers.has(remotePeerStr)) {
790
814
  return false;
791
815
  }
@@ -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) {
package/src/sync/types.ts CHANGED
@@ -172,6 +172,8 @@ export type PendingPayloadRootHex = {
172
172
  export type PendingPayloadEnvelope = {
173
173
  status: PendingPayloadInputStatus.waitingForBlock;
174
174
  envelope: SignedExecutionPayloadEnvelope;
175
+ /** Peer that served the envelope, undefined if it was already cached */
176
+ envelopePeerId?: string;
175
177
  timeAddedSec: number;
176
178
  peerIdStrings: Set<string>;
177
179
  };
@@ -13,6 +13,8 @@ import {PayloadEnvelopeInput, PayloadEnvelopeInputSource} from "../chain/blocks/
13
13
  import {
14
14
  BlockError,
15
15
  BlockErrorCode,
16
+ DataColumnSidecarErrorCode,
17
+ DataColumnSidecarValidationError,
16
18
  ExecutionPayloadEnvelopeError,
17
19
  ExecutionPayloadEnvelopeErrorCode,
18
20
  } from "../chain/errors/index.js";
@@ -1499,10 +1501,22 @@ export class BlockInputSync {
1499
1501
  return;
1500
1502
  }
1501
1503
  if (validationResult.err) {
1504
+ const err = validationResult.err;
1505
+ const {envelopePeerId} = pendingPayload;
1506
+ // Same penalties as for an envelope validated right after download in fetchPayloadInput
1507
+ if (
1508
+ envelopePeerId !== undefined &&
1509
+ err instanceof ExecutionPayloadEnvelopeError &&
1510
+ (pendingPayload.envelope.message.payload.slotNumber !== payloadInput.slot ||
1511
+ toRootHex(pendingPayload.envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1512
+ ) {
1513
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, err.type.code);
1514
+ }
1515
+
1502
1516
  this.logger.debug(
1503
1517
  "Pending payload envelope failed validation after block import, refetching by root",
1504
1518
  {slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex},
1505
- validationResult.err
1519
+ err
1506
1520
  );
1507
1521
 
1508
1522
  const pendingPayloadByRoot: PendingPayloadRootHex = {
@@ -1512,6 +1526,10 @@ export class BlockInputSync {
1512
1526
  timeAddedSec: pendingPayload.timeAddedSec,
1513
1527
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1514
1528
  };
1529
+ // Do not prefer the peer whose envelope just failed validation
1530
+ if (envelopePeerId !== undefined) {
1531
+ pendingPayloadByRoot.peerIdStrings.delete(envelopePeerId);
1532
+ }
1515
1533
  this.pendingPayloads.set(rootHex, pendingPayloadByRoot);
1516
1534
 
1517
1535
  if (this.network.getConnectedPeers().length > 0) {
@@ -1720,6 +1738,8 @@ export class BlockInputSync {
1720
1738
  ? cacheItem.payloadInput
1721
1739
  : await this.chain.seenPayloadEnvelopeInputCache.getOrReload(rootHex);
1722
1740
  let envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1741
+ // An envelope downloaded in an earlier attempt is validated with the peer of a later one
1742
+ let envelopePeerId: PeerIdStr | undefined;
1723
1743
 
1724
1744
  const fetchStartSec = Date.now() / 1000;
1725
1745
  if (typeof slot === "number") {
@@ -1767,6 +1787,7 @@ export class BlockInputSync {
1767
1787
  try {
1768
1788
  if (!envelope) {
1769
1789
  envelope = await this.fetchExecutionPayloadEnvelope(peerId, blockRoot, rootHex);
1790
+ envelopePeerId = peerId;
1770
1791
  cacheItem.peerIdStrings.add(peerId);
1771
1792
  const slotWasUnknown = typeof slot !== "number";
1772
1793
  slot = envelope.message.payload.slotNumber;
@@ -1790,6 +1811,7 @@ export class BlockInputSync {
1790
1811
  return {
1791
1812
  status: PendingPayloadInputStatus.waitingForBlock,
1792
1813
  envelope,
1814
+ envelopePeerId,
1793
1815
  timeAddedSec: cacheItem.timeAddedSec,
1794
1816
  peerIdStrings: cacheItem.peerIdStrings,
1795
1817
  };
@@ -1875,24 +1897,39 @@ export class BlockInputSync {
1875
1897
  excludedPeers.add(peerId);
1876
1898
  }
1877
1899
 
1900
+ // Honest peers serve the requested root and columns, and every path that stores payload columns verifies them
1901
+ if (e instanceof DownloadByRootError || e instanceof DataColumnSidecarValidationError) {
1902
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, e.type.code);
1903
+ }
1904
+
1878
1905
  if (e instanceof ExecutionPayloadEnvelopeError) {
1879
- switch (e.type.code) {
1880
- // Caused by local state, the downloaded envelope may still be valid
1881
- case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1882
- case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1883
- case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1884
- case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1885
- break;
1886
- // Every copy fails once the block is finalized, only a wrong slot makes the served copy invalid
1887
- case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1888
- if (envelope?.message.payload.slotNumber !== payloadInput?.slot) {
1906
+ // Range sync stores an envelope after checking only its root, slot and block hash, so an honest peer may
1907
+ // serve one that fails the other checks. Compared directly since validation stops at the first failure.
1908
+ if (
1909
+ envelope !== undefined &&
1910
+ payloadInput &&
1911
+ (envelope.message.payload.slotNumber !== payloadInput.slot ||
1912
+ toRootHex(envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1913
+ ) {
1914
+ if (envelopePeerId !== undefined) {
1915
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, e.type.code);
1916
+ }
1917
+ envelope = payloadInput.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1918
+ } else {
1919
+ switch (e.type.code) {
1920
+ // Caused by local state, the downloaded envelope may still be valid
1921
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1922
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1923
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1924
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1925
+ // Every copy fails once the block is finalized
1926
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1927
+ break;
1928
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1929
+ default:
1889
1930
  envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1890
- }
1891
- break;
1892
- // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1893
- default:
1894
- envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1895
- break;
1931
+ break;
1932
+ }
1896
1933
  }
1897
1934
  }
1898
1935
  } finally {
@@ -1929,7 +1966,12 @@ export class BlockInputSync {
1929
1966
 
1930
1967
  const receivedRootHex = toRootHex(envelope.message.beaconBlockRoot);
1931
1968
  if (receivedRootHex !== rootHex) {
1932
- throw new Error(`Execution payload envelope root mismatch requested=${rootHex} received=${receivedRootHex}`);
1969
+ throw new DownloadByRootError({
1970
+ code: DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT,
1971
+ peer: prettyPrintPeerIdStr(peerIdStr),
1972
+ requestedBlockRoot: rootHex,
1973
+ receivedBlockRoot: receivedRootHex,
1974
+ });
1933
1975
  }
1934
1976
 
1935
1977
  return envelope;
@@ -1958,9 +2000,13 @@ export class BlockInputSync {
1958
2000
  const requestedColumnsSet = new Set(requestedColumns);
1959
2001
  const extraColumns = columnSidecars.filter((columnSidecar) => !requestedColumnsSet.has(columnSidecar.index));
1960
2002
  if (extraColumns.length > 0) {
1961
- throw new Error(
1962
- `Received unexpected payload data columns indices=${prettyPrintIndices(extraColumns.map((column) => column.index))}`
1963
- );
2003
+ throw new DownloadByRootError({
2004
+ code: DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED,
2005
+ peer: prettyPrintPeerIdStr(peerIdStr),
2006
+ slot: payloadInput.slot,
2007
+ blockRoot: payloadInput.blockRootHex,
2008
+ invalidIndices: prettyPrintIndices(extraColumns.map((column) => column.index)),
2009
+ });
1964
2010
  }
1965
2011
 
1966
2012
  // PayloadEnvelopeInput already carries the block slot, root, and commitments, so reuse the
@@ -1997,7 +2043,20 @@ export class BlockInputSync {
1997
2043
 
1998
2044
  let i = 0;
1999
2045
  let deferredByRateLimit = false;
2046
+ let requestedWhenReconstructable = false;
2000
2047
  while (i++ < this.getMaxDownloadAttempts()) {
2048
+ const reconstructable =
2049
+ isPendingBlockInput(cacheItem) &&
2050
+ isBlockInputColumns(cacheItem.blockInput) &&
2051
+ cacheItem.blockInput.hasBlockAndAllData();
2052
+ // Reconstruction recovers whole rows however many columns are missing, so only one more request is worth it,
2053
+ // further peers could each hold the import until their response times out
2054
+ if (reconstructable) {
2055
+ if (requestedWhenReconstructable) {
2056
+ break;
2057
+ }
2058
+ requestedWhenReconstructable = true;
2059
+ }
2001
2060
  const pendingColumns =
2002
2061
  isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
2003
2062
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
@@ -2012,6 +2071,10 @@ export class BlockInputSync {
2012
2071
  now
2013
2072
  );
2014
2073
  if (peerMeta === null) {
2074
+ if (reconstructable) {
2075
+ break;
2076
+ }
2077
+
2015
2078
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
2016
2079
  if (retryAt !== null) {
2017
2080
  throw new UnknownBlockRateLimitedError(
@@ -2056,8 +2119,16 @@ export class BlockInputSync {
2056
2119
  for (const warning of warnings) {
2057
2120
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
2058
2121
  this.metrics?.blockInputSync.downloadByRoot.warn.inc({code: warning.type.code, client: peerClient});
2122
+ // A partial response is legal, columns that were not requested are not
2123
+ if (warning.type.code === DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED) {
2124
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, warning.type.code);
2125
+ excludedPeers.add(peerId);
2126
+ }
2127
+ // Not picked again for this block, it would be preferred as a previous source of it
2128
+ if (warning.type.code === DownloadByRootErrorCode.NOT_ENOUGH_SIDECARS_RECEIVED) {
2129
+ excludedPeers.add(peerId);
2130
+ }
2059
2131
  }
2060
- // TODO: penalize peer?
2061
2132
  }
2062
2133
  } catch (e) {
2063
2134
  this.logger.debug(
@@ -2066,7 +2137,6 @@ export class BlockInputSync {
2066
2137
  e as Error
2067
2138
  );
2068
2139
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
2069
- // TODO: penalize peer?
2070
2140
  if (e instanceof DownloadByRootError) {
2071
2141
  const errorCode = e.type.code;
2072
2142
  downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
@@ -2082,6 +2152,22 @@ export class BlockInputSync {
2082
2152
  this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2083
2153
  }
2084
2154
  excludedPeers.add(peerId);
2155
+ } else if (e instanceof DataColumnSidecarValidationError) {
2156
+ const errorCode = e.type.code;
2157
+ downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2158
+ // Not PROPOSAL_SIGNATURE_INVALID or INCORRECT_HEADER_ROOT, which compares signatures too: the spec does not
2159
+ // require verifying the header signature of req/resp columns, so honest peers may serve a bad one
2160
+ switch (errorCode) {
2161
+ case DataColumnSidecarErrorCode.INCORRECT_BLOCK:
2162
+ case DataColumnSidecarErrorCode.INVALID_INDEX:
2163
+ case DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT:
2164
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
2165
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
2166
+ case DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID:
2167
+ case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
2168
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2169
+ }
2170
+ excludedPeers.add(peerId);
2085
2171
  } else if (e instanceof RequestError) {
2086
2172
  // should look into req_resp metrics in this case
2087
2173
  downloadByRootMetrics?.error.inc({code: "req_resp", client: peerClient});
@@ -2133,6 +2219,30 @@ export class BlockInputSync {
2133
2219
 
2134
2220
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
2135
2221
 
2222
+ if (
2223
+ isPendingBlockInput(cacheItem) &&
2224
+ isBlockInputColumns(cacheItem.blockInput) &&
2225
+ cacheItem.blockInput.hasBlockAndAllData()
2226
+ ) {
2227
+ // Peers cannot serve the remaining columns now, half of them is enough to reconstruct the rest
2228
+ this.logger.verbose("BlockInputSync.fetchBlockInput: reconstructing columns peers could not serve", {
2229
+ slot,
2230
+ rootHex,
2231
+ missing: cacheItem.blockInput.getMissingSampledColumnMeta().missing.length,
2232
+ });
2233
+ this.chain.columnReconstructionTracker.triggerColumnReconstruction(cacheItem.blockInput);
2234
+ cacheItem = {...cacheItem, status: PendingBlockInputStatus.downloaded, timeSyncedSec: Date.now() / 1000};
2235
+ if (this.pendingBlocks.has(rootHex)) {
2236
+ this.pendingBlocks.set(rootHex, cacheItem);
2237
+ }
2238
+ const result = this.chain.forkChoice.hasBlockHex(cacheItem.blockInput.parentRootHex)
2239
+ ? FetchResult.SuccessResolved
2240
+ : FetchResult.SuccessMissingParent;
2241
+ this.metrics?.blockInputSync.fetchTime.observe({result}, Date.now() / 1000 - fetchStartSec);
2242
+ this.metrics?.blockInputSync.fetchPeers.set({result}, i - 1);
2243
+ return cacheItem;
2244
+ }
2245
+
2136
2246
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
2137
2247
  if (retryAt !== null) {
2138
2248
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -115,9 +115,8 @@ export async function downloadByRoot({
115
115
  });
116
116
  }
117
117
 
118
- const hasAllDataPreDownload = blockInput.hasBlockAndAllData();
119
-
120
- if (isBlockInputColumns(blockInput) && !hasAllDataPreDownload) {
118
+ // Like range sync, download every sampled column, half of them only counts as available for reconstruction
119
+ if (isBlockInputColumns(blockInput) && !blockInput.hasComputedAllData()) {
121
120
  // columnSidecars could be undefined if gossip resulted in full block+columns so we don't download any
122
121
  if (!columnSidecars) {
123
122
  throw new DownloadByRootError({
@@ -154,7 +153,10 @@ export async function downloadByRoot({
154
153
 
155
154
  let status: PendingBlockInputStatus;
156
155
  let timeSyncedSec: number | undefined;
157
- if (blockInput.hasBlockAndAllData()) {
156
+ if (
157
+ blockInput.hasBlock() &&
158
+ (isBlockInputColumns(blockInput) ? blockInput.hasComputedAllData() : blockInput.hasAllData())
159
+ ) {
158
160
  status = PendingBlockInputStatus.downloaded;
159
161
  timeSyncedSec = Date.now() / 1000;
160
162
  } else {
@@ -201,7 +203,7 @@ export async function fetchByRoot({
201
203
  }
202
204
 
203
205
  const forkName = config.getForkName(block.message.slot);
204
- if (!cacheItem.blockInput.hasAllData() && isBlockInputColumns(cacheItem.blockInput)) {
206
+ if (isBlockInputColumns(cacheItem.blockInput) && !cacheItem.blockInput.hasComputedAllData()) {
205
207
  columnSidecarResult = await fetchAndValidateColumns({
206
208
  config,
207
209
  chain,