@lodestar/beacon-node 1.52.0-dev.3d90162721 → 1.52.0-dev.4996a91d93

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 (140) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +46 -26
  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 +3 -1
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  8. package/lib/api/impl/beacon/state/utils.js +2 -1
  9. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  10. package/lib/api/impl/debug/index.d.ts.map +1 -1
  11. package/lib/api/impl/debug/index.js +6 -2
  12. package/lib/api/impl/debug/index.js.map +1 -1
  13. package/lib/api/impl/validator/index.d.ts.map +1 -1
  14. package/lib/api/impl/validator/index.js +1 -1
  15. package/lib/api/impl/validator/index.js.map +1 -1
  16. package/lib/chain/ColumnReconstructionTracker.d.ts +4 -0
  17. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  18. package/lib/chain/ColumnReconstructionTracker.js +4 -0
  19. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  20. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  21. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  22. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  23. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  24. package/lib/chain/blocks/index.d.ts.map +1 -1
  25. package/lib/chain/blocks/index.js +3 -17
  26. package/lib/chain/blocks/index.js.map +1 -1
  27. package/lib/chain/chain.d.ts +6 -5
  28. package/lib/chain/chain.d.ts.map +1 -1
  29. package/lib/chain/chain.js +62 -20
  30. package/lib/chain/chain.js.map +1 -1
  31. package/lib/chain/errors/executionPayloadBid.d.ts +3 -2
  32. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  33. package/lib/chain/errors/executionPayloadBid.js +1 -1
  34. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  35. package/lib/chain/interface.d.ts +1 -1
  36. package/lib/chain/interface.d.ts.map +1 -1
  37. package/lib/chain/opPools/opPool.js +6 -6
  38. package/lib/chain/opPools/opPool.js.map +1 -1
  39. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  40. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  41. package/lib/chain/seenCache/seenAttesters.js +1 -1
  42. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  43. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  44. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  45. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  46. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  47. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts +13 -4
  48. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts.map +1 -1
  49. package/lib/chain/seenCache/seenExecutionPayloadBids.js +13 -12
  50. package/lib/chain/seenCache/seenExecutionPayloadBids.js.map +1 -1
  51. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  52. package/lib/chain/validation/executionPayloadBid.js +30 -40
  53. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  54. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  55. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  56. package/lib/chain/validatorMonitor.js +43 -43
  57. package/lib/chain/validatorMonitor.js.map +1 -1
  58. package/lib/network/gossip/topic.d.ts +1 -7
  59. package/lib/network/gossip/topic.d.ts.map +1 -1
  60. package/lib/network/gossip/topic.js +0 -13
  61. package/lib/network/gossip/topic.js.map +1 -1
  62. package/lib/network/network.d.ts +1 -0
  63. package/lib/network/network.d.ts.map +1 -1
  64. package/lib/network/network.js +20 -11
  65. package/lib/network/network.js.map +1 -1
  66. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  67. package/lib/network/processor/gossipHandlers.js +17 -4
  68. package/lib/network/processor/gossipHandlers.js.map +1 -1
  69. package/lib/network/processor/gossipValidatorFn.d.ts.map +1 -1
  70. package/lib/network/processor/gossipValidatorFn.js +4 -1
  71. package/lib/network/processor/gossipValidatorFn.js.map +1 -1
  72. package/lib/network/processor/index.d.ts.map +1 -1
  73. package/lib/network/processor/index.js +4 -2
  74. package/lib/network/processor/index.js.map +1 -1
  75. package/lib/network/reqresp/utils/collect.d.ts +4 -4
  76. package/lib/network/reqresp/utils/collect.d.ts.map +1 -1
  77. package/lib/network/reqresp/utils/collect.js +9 -8
  78. package/lib/network/reqresp/utils/collect.js.map +1 -1
  79. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts +1 -1
  80. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts.map +1 -1
  81. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js +2 -2
  82. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js.map +1 -1
  83. package/lib/sync/range/batch.d.ts +6 -0
  84. package/lib/sync/range/batch.d.ts.map +1 -1
  85. package/lib/sync/range/batch.js +17 -0
  86. package/lib/sync/range/batch.js.map +1 -1
  87. package/lib/sync/range/chain.d.ts.map +1 -1
  88. package/lib/sync/range/chain.js +8 -1
  89. package/lib/sync/range/chain.js.map +1 -1
  90. package/lib/sync/range/range.d.ts.map +1 -1
  91. package/lib/sync/range/range.js +43 -3
  92. package/lib/sync/range/range.js.map +1 -1
  93. package/lib/sync/types.d.ts +12 -1
  94. package/lib/sync/types.d.ts.map +1 -1
  95. package/lib/sync/types.js +2 -0
  96. package/lib/sync/types.js.map +1 -1
  97. package/lib/sync/unknownBlock.d.ts +27 -1
  98. package/lib/sync/unknownBlock.d.ts.map +1 -1
  99. package/lib/sync/unknownBlock.js +217 -21
  100. package/lib/sync/unknownBlock.js.map +1 -1
  101. package/lib/sync/utils/downloadByRange.d.ts +14 -1
  102. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  103. package/lib/sync/utils/downloadByRange.js +12 -2
  104. package/lib/sync/utils/downloadByRange.js.map +1 -1
  105. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  106. package/lib/sync/utils/downloadByRoot.js +2 -0
  107. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  108. package/package.json +17 -17
  109. package/src/api/impl/beacon/blocks/index.ts +52 -28
  110. package/src/api/impl/beacon/pool/index.ts +9 -7
  111. package/src/api/impl/beacon/state/utils.ts +2 -1
  112. package/src/api/impl/debug/index.ts +6 -2
  113. package/src/api/impl/validator/index.ts +1 -2
  114. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  115. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  116. package/src/chain/blocks/index.ts +3 -31
  117. package/src/chain/chain.ts +95 -37
  118. package/src/chain/errors/executionPayloadBid.ts +3 -2
  119. package/src/chain/interface.ts +1 -1
  120. package/src/chain/opPools/opPool.ts +6 -6
  121. package/src/chain/seenCache/seenAttesters.ts +1 -1
  122. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  123. package/src/chain/seenCache/seenExecutionPayloadBids.ts +35 -15
  124. package/src/chain/validation/executionPayloadBid.ts +40 -42
  125. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  126. package/src/chain/validatorMonitor.ts +43 -43
  127. package/src/network/gossip/topic.ts +1 -14
  128. package/src/network/network.ts +33 -11
  129. package/src/network/processor/gossipHandlers.ts +23 -11
  130. package/src/network/processor/gossipValidatorFn.ts +4 -0
  131. package/src/network/processor/index.ts +7 -2
  132. package/src/network/reqresp/utils/collect.ts +16 -8
  133. package/src/network/reqresp/utils/collectSequentialBlocksInRange.ts +3 -2
  134. package/src/sync/range/batch.ts +20 -0
  135. package/src/sync/range/chain.ts +8 -0
  136. package/src/sync/range/range.ts +56 -3
  137. package/src/sync/types.ts +11 -0
  138. package/src/sync/unknownBlock.ts +250 -21
  139. package/src/sync/utils/downloadByRange.ts +29 -3
  140. package/src/sync/utils/downloadByRoot.ts +2 -0
@@ -7,7 +7,7 @@ import { isBlockInputColumns } from "../chain/blocks/blockInput/blockInput.js";
7
7
  import { BlockInputSource } from "../chain/blocks/blockInput/types.js";
8
8
  import { PayloadError, PayloadErrorCode } from "../chain/blocks/importExecutionPayload.js";
9
9
  import { PayloadEnvelopeInputSource } from "../chain/blocks/payloadEnvelopeInput/index.js";
10
- import { BlockError, BlockErrorCode } from "../chain/errors/index.js";
10
+ import { BlockError, BlockErrorCode, ExecutionPayloadEnvelopeError, ExecutionPayloadEnvelopeErrorCode, } from "../chain/errors/index.js";
11
11
  import { ChainEvent } from "../chain/index.js";
12
12
  import { validateGloasBlockDataColumnSidecars } from "../chain/validation/dataColumnSidecar.js";
13
13
  import { validateGossipExecutionPayloadEnvelope } from "../chain/validation/executionPayloadEnvelope.js";
@@ -25,6 +25,15 @@ import { getRateLimitedUntilMs } from "./utils/rateLimit.js";
25
25
  const MAX_ATTEMPTS_PER_BLOCK = 5;
26
26
  const MAX_KNOWN_BAD_BLOCKS = 500;
27
27
  const MAX_PENDING_BLOCKS = 100;
28
+ /**
29
+ * A failed download is retried after this delay, doubling per failure up to one slot.
30
+ */
31
+ const DOWNLOAD_RETRY_BASE_MS = 1_000;
32
+ /**
33
+ * Requests per peer per window, half the BeaconBlocksByRoot quota peers enforce, they disconnect a peer that exceeds it.
34
+ */
35
+ const MAX_REQUESTS_PER_PEER = 64;
36
+ const REQUESTS_PER_PEER_WINDOW_MS = 10_000;
28
37
  /**
29
38
  * A pending payload without slot can only stay at most 2 epochs.
30
39
  */
@@ -93,6 +102,8 @@ export class BlockInputSync {
93
102
  subscribedToNetworkEvents = false;
94
103
  peerBalancer;
95
104
  rateLimitBackoffTimeout;
105
+ downloadRetryTimeout;
106
+ downloadRetryAtMs;
96
107
  /**
97
108
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
98
109
  */
@@ -133,6 +144,7 @@ export class BlockInputSync {
133
144
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
134
145
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
135
146
  this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
147
+ this.chain.clock.on(ClockEvent.slot, this.pruneUnresolvedBlocks);
136
148
  // Seed the balancer with peers that connected before we subscribed
137
149
  for (const peerId of this.network.getConnectedPeers()) {
138
150
  try {
@@ -151,7 +163,9 @@ export class BlockInputSync {
151
163
  unsubscribeFromNetwork() {
152
164
  this.logger.verbose("BlockInputSync disabled.");
153
165
  this.clearRateLimitBackoffTimer();
166
+ this.clearDownloadRetryTimer();
154
167
  this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
168
+ this.chain.clock.off(ClockEvent.slot, this.pruneUnresolvedBlocks);
155
169
  this.payloadPollAbortController?.abort();
156
170
  this.payloadPollAbortController = undefined;
157
171
  this.deferredPayloadRoots.clear();
@@ -293,6 +307,9 @@ export class BlockInputSync {
293
307
  this.addByRootHex(missingDependency.rootHex, data.peer);
294
308
  }
295
309
  this.addByBlockInput(data.blockInput, data.peer);
310
+ if (data.source === BlockInputSource.gossip) {
311
+ this.limitRetainedBlocks(data.blockInput, data.peer);
312
+ }
296
313
  this.triggerUnknownBlockSearch();
297
314
  this.metrics?.blockInputSync.requests.inc({ type: PendingBlockType.UNKNOWN_PARENT });
298
315
  this.metrics?.blockInputSync.source.inc({ source: data.source });
@@ -319,7 +336,8 @@ export class BlockInputSync {
319
336
  // because the payload at the finalized block is not finalized
320
337
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
321
338
  const nowSec = Date.now() / 1000;
322
- const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * this.config.SLOT_DURATION_MS) / 1000;
339
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
340
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
323
341
  let belowFinalizedPayloads = 0;
324
342
  let agedOutPayloads = 0;
325
343
  let unresolvedSlotPayloads = 0;
@@ -414,13 +432,7 @@ export class BlockInputSync {
414
432
  if (peerIdStr && pendingBlock.peerIdStrings.size < MAX_PEERS_PER_ROOT) {
415
433
  pendingBlock.peerIdStrings.add(peerIdStr);
416
434
  }
417
- // TODO: check this prune methodology
418
- // Limit pending blocks to prevent DOS attacks that cause OOM
419
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
420
- if (prunedItemCount > 0) {
421
- this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
422
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
423
- }
435
+ this.prunePendingBlocks();
424
436
  return added;
425
437
  };
426
438
  addByBlockInput = (blockInput, peerIdStr) => {
@@ -451,14 +463,59 @@ export class BlockInputSync {
451
463
  if (peerIdStr && pendingBlock.peerIdStrings.size < MAX_PEERS_PER_ROOT) {
452
464
  pendingBlock.peerIdStrings.add(peerIdStr);
453
465
  }
454
- // TODO: check this prune methodology
455
- // Limit pending blocks to prevent DOS attacks that cause OOM
456
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
457
- if (prunedItemCount > 0) {
458
- this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
459
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
460
- }
466
+ this.prunePendingBlocks();
461
467
  };
468
+ /**
469
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
470
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
471
+ * A downloaded block is only checked against its root, so this only applies while blocks and the roots they wait on
472
+ * fill at most half the cap, otherwise they could pin it and evict every new root on insertion.
473
+ */
474
+ prunePendingBlocks() {
475
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
476
+ return;
477
+ }
478
+ const awaitedRoots = new Set();
479
+ for (const pendingBlock of this.pendingBlocks.values()) {
480
+ if (isPendingBlockInput(pendingBlock)) {
481
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
482
+ }
483
+ }
484
+ const isKept = (rootHex, pendingBlock) => isPendingBlockInput(pendingBlock) || awaitedRoots.has(rootHex);
485
+ let keptCount = 0;
486
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
487
+ if (isKept(rootHex, pendingBlock)) {
488
+ keptCount++;
489
+ }
490
+ }
491
+ let prunedItemCount = 0;
492
+ if (keptCount <= this.maxPendingBlocks / 2) {
493
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
494
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
495
+ break;
496
+ }
497
+ if (!isKept(rootHex, pendingBlock)) {
498
+ this.pendingBlocks.delete(rootHex);
499
+ prunedItemCount++;
500
+ }
501
+ }
502
+ }
503
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
504
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
505
+ break;
506
+ }
507
+ this.pendingBlocks.delete(rootHex);
508
+ prunedItemCount++;
509
+ // The block input cache is only trimmed on import, a block whose parent never resolves would stay there
510
+ if (isPendingBlockInput(pendingBlock) &&
511
+ pendingBlock.status !== PendingBlockInputStatus.processing &&
512
+ this.getMissingBlockDependency(pendingBlock.blockInput).kind === "parentBlock") {
513
+ this.chain.seenBlockInputCache.remove(rootHex);
514
+ }
515
+ }
516
+ this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
517
+ this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
518
+ }
462
519
  addByPayloadRootHex = (rootHex, peerIdStr, slot) => {
463
520
  if (this.knownBadBlocks.has(rootHex)) {
464
521
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -574,6 +631,72 @@ export class BlockInputSync {
574
631
  this.peerBalancer.onPeerDisconnected(peerId);
575
632
  this.scheduleRateLimitBackoffRetry();
576
633
  };
634
+ /**
635
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
636
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
637
+ */
638
+ limitRetainedBlocks(blockInput, peerIdStr) {
639
+ const pendingBlock = this.pendingBlocks.get(blockInput.blockRootHex);
640
+ if (pendingBlock === undefined || !isPendingBlockInput(pendingBlock) || pendingBlock.retainedBy !== undefined) {
641
+ return;
642
+ }
643
+ pendingBlock.retainedBy = peerIdStr;
644
+ pendingBlock.retainedBytes = this.config
645
+ .getForkTypes(blockInput.slot)
646
+ .SignedBeaconBlock.value_serializedSize(blockInput.getBlock());
647
+ const retainedBlocks = [];
648
+ let retainedBytes = 0;
649
+ for (const item of this.pendingBlocks.values()) {
650
+ if (isPendingBlockInput(item) && item.retainedBy === peerIdStr && this.isWaitingOnParent(item)) {
651
+ retainedBlocks.push(item);
652
+ retainedBytes += item.retainedBytes ?? 0;
653
+ }
654
+ }
655
+ // One block of the max gossip size fits, honest blocks are far smaller
656
+ for (const item of retainedBlocks) {
657
+ if (retainedBytes <= this.config.MAX_PAYLOAD_SIZE) {
658
+ break;
659
+ }
660
+ retainedBytes -= item.retainedBytes ?? 0;
661
+ this.removeUnresolvedBlock(item, DroppedItemReason.peerBudget);
662
+ }
663
+ }
664
+ /**
665
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
666
+ */
667
+ pruneUnresolvedBlocks = () => {
668
+ const nowSec = Date.now() / 1000;
669
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
670
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
671
+ for (const pendingBlock of this.pendingBlocks.values()) {
672
+ if (isPendingBlockInput(pendingBlock) &&
673
+ nowSec - pendingBlock.timeAddedSec > maxSecInCache &&
674
+ this.isWaitingOnParent(pendingBlock)) {
675
+ this.removeUnresolvedBlock(pendingBlock, DroppedItemReason.agedOut);
676
+ }
677
+ }
678
+ };
679
+ isWaitingOnParent(pendingBlock) {
680
+ if (pendingBlock.status === PendingBlockInputStatus.processing) {
681
+ return false;
682
+ }
683
+ const { kind } = this.getMissingBlockDependency(pendingBlock.blockInput);
684
+ return kind === "parentBlock" || kind === "parentPayload";
685
+ }
686
+ /**
687
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
688
+ */
689
+ removeUnresolvedBlock(pendingBlock, reason) {
690
+ const rootHex = pendingBlock.blockInput.blockRootHex;
691
+ this.pendingBlocks.delete(rootHex);
692
+ this.chain.seenBlockInputCache.remove(rootHex);
693
+ this.metrics?.blockInputSync.removedBlocks.inc({ reason });
694
+ this.logger.debug("Removed unresolved BlockInputSync block", {
695
+ slot: pendingBlock.blockInput.slot,
696
+ root: rootHex,
697
+ reason,
698
+ });
699
+ }
577
700
  /**
578
701
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
579
702
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -692,8 +815,17 @@ export class BlockInputSync {
692
815
  this.logger.debug("No connected peers, skipping unknown block download.");
693
816
  }
694
817
  else {
818
+ // Blocks and roots a pending block waits on are downloaded first, any gossip message with an unknown root adds
819
+ // another root, and they all share the per-peer request budget
820
+ const awaitedRoots = new Set();
821
+ for (const pendingBlock of this.pendingBlocks.values()) {
822
+ if (isPendingBlockInput(pendingBlock)) {
823
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
824
+ }
825
+ }
826
+ const isAwaited = (block) => isPendingBlockInput(block) || awaitedRoots.has(block.rootHex);
695
827
  // Most of the time there is exactly 1 unknown block
696
- for (const block of unknowns) {
828
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
697
829
  this.downloadBlock(block).catch((e) => {
698
830
  this.logger.debug("Unexpected error - downloadBlock", { root: getBlockInputSyncCacheItemRootHex(block) }, e);
699
831
  });
@@ -763,6 +895,25 @@ export class BlockInputSync {
763
895
  this.rateLimitBackoffTimeout = undefined;
764
896
  }
765
897
  }
898
+ scheduleDownloadRetry(retryAtMs) {
899
+ if (this.downloadRetryAtMs !== undefined && this.downloadRetryAtMs <= retryAtMs) {
900
+ return;
901
+ }
902
+ this.clearDownloadRetryTimer();
903
+ this.downloadRetryAtMs = retryAtMs;
904
+ this.downloadRetryTimeout = setTimeout(() => {
905
+ this.downloadRetryTimeout = undefined;
906
+ this.downloadRetryAtMs = undefined;
907
+ this.triggerUnknownBlockSearch();
908
+ }, Math.max(0, retryAtMs - Date.now()));
909
+ }
910
+ clearDownloadRetryTimer() {
911
+ if (this.downloadRetryTimeout !== undefined) {
912
+ clearTimeout(this.downloadRetryTimeout);
913
+ this.downloadRetryTimeout = undefined;
914
+ }
915
+ this.downloadRetryAtMs = undefined;
916
+ }
766
917
  /**
767
918
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
768
919
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -877,6 +1028,10 @@ export class BlockInputSync {
877
1028
  if (block.status !== PendingBlockInputStatus.pending) {
878
1029
  return;
879
1030
  }
1031
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1032
+ this.scheduleDownloadRetry(block.retryAtMs);
1033
+ return;
1034
+ }
880
1035
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
881
1036
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
882
1037
  const logCtx = {
@@ -951,6 +1106,7 @@ export class BlockInputSync {
951
1106
  const pendingBlock = this.pendingBlocks.get(rootHex);
952
1107
  if (pendingBlock) {
953
1108
  pendingBlock.status = PendingBlockInputStatus.pending;
1109
+ pendingBlock.retryAtMs = res.err.retryAt;
954
1110
  }
955
1111
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
956
1112
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -963,8 +1119,17 @@ export class BlockInputSync {
963
1119
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
964
1120
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
965
1121
  const pendingBlock = this.pendingBlocks.get(rootHex);
966
- if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1122
+ // A partial download replaces the entry with a pending one that does not carry the failure count
1123
+ if (pendingBlock &&
1124
+ (pendingBlock.status === PendingBlockInputStatus.fetching ||
1125
+ pendingBlock.status === PendingBlockInputStatus.pending)) {
967
1126
  pendingBlock.status = PendingBlockInputStatus.pending;
1127
+ // Not retried on every search, any gossip message with an unknown root triggers one
1128
+ pendingBlock.failedDownloads = (block.failedDownloads ?? 0) + 1;
1129
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
1130
+ pendingBlock.retryAtMs =
1131
+ Date.now() + Math.min(DOWNLOAD_RETRY_BASE_MS * 2 ** (pendingBlock.failedDownloads - 1), slotDurationMs);
1132
+ this.scheduleDownloadRetry(pendingBlock.retryAtMs);
968
1133
  }
969
1134
  }
970
1135
  }
@@ -1127,7 +1292,7 @@ export class BlockInputSync {
1127
1292
  const pendingPayloadByRoot = {
1128
1293
  status: PendingPayloadInputStatus.pending,
1129
1294
  rootHex,
1130
- slot: pendingPayload.envelope.message.payload.slotNumber,
1295
+ slot: payloadInput.slot,
1131
1296
  timeAddedSec: pendingPayload.timeAddedSec,
1132
1297
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1133
1298
  };
@@ -1429,6 +1594,26 @@ export class BlockInputSync {
1429
1594
  else {
1430
1595
  excludedPeers.add(peerId);
1431
1596
  }
1597
+ if (e instanceof ExecutionPayloadEnvelopeError) {
1598
+ switch (e.type.code) {
1599
+ // Caused by local state, the downloaded envelope may still be valid
1600
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1601
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1602
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1603
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1604
+ break;
1605
+ // Every copy fails once the block is finalized, only a wrong slot makes the served copy invalid
1606
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1607
+ if (envelope?.message.payload.slotNumber !== payloadInput?.slot) {
1608
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1609
+ }
1610
+ break;
1611
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1612
+ default:
1613
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1614
+ break;
1615
+ }
1616
+ }
1432
1617
  }
1433
1618
  finally {
1434
1619
  this.peerBalancer.onRequestCompleted(peerId);
@@ -1727,10 +1912,12 @@ export class UnknownBlockPeerBalancer {
1727
1912
  peersMeta;
1728
1913
  activeRequests;
1729
1914
  rateLimitedUntilByPeer;
1915
+ requestTimesByPeer;
1730
1916
  constructor() {
1731
1917
  this.peersMeta = new Map();
1732
1918
  this.activeRequests = new Map();
1733
1919
  this.rateLimitedUntilByPeer = new Map();
1920
+ this.requestTimesByPeer = new Map();
1734
1921
  }
1735
1922
  /** Trigger on each peer re-status */
1736
1923
  onPeerConnected(peerId, syncMeta) {
@@ -1743,12 +1930,14 @@ export class UnknownBlockPeerBalancer {
1743
1930
  this.peersMeta.delete(peerId);
1744
1931
  this.activeRequests.delete(peerId);
1745
1932
  this.rateLimitedUntilByPeer.delete(peerId);
1933
+ this.requestTimesByPeer.delete(peerId);
1746
1934
  }
1747
1935
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
1748
1936
  clear() {
1749
1937
  this.peersMeta.clear();
1750
1938
  this.activeRequests.clear();
1751
1939
  this.rateLimitedUntilByPeer.clear();
1940
+ this.requestTimesByPeer.clear();
1752
1941
  }
1753
1942
  onRateLimited(peerId, rateLimitedUntilMs) {
1754
1943
  this.rateLimitedUntilByPeer.set(peerId, rateLimitedUntilMs);
@@ -1793,15 +1982,22 @@ export class UnknownBlockPeerBalancer {
1793
1982
  // 2nd key (tiebreak): prefer peers with least active req
1794
1983
  (peerId) => this.activeRequests.get(peerId) ?? 0);
1795
1984
  const bestPeerId = sortedEligiblePeers[0];
1796
- this.onRequest(bestPeerId);
1985
+ this.onRequest(bestPeerId, now);
1797
1986
  return this.peersMeta.get(bestPeerId) ?? null;
1798
1987
  }
1799
1988
  /**
1800
1989
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
1801
1990
  * make this public for testing
1802
1991
  */
1803
- onRequest(peerId) {
1992
+ onRequest(peerId, now = Date.now()) {
1804
1993
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
1994
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter((time) => now - time < REQUESTS_PER_PEER_WINDOW_MS);
1995
+ requestTimes.push(now);
1996
+ this.requestTimesByPeer.set(peerId, requestTimes);
1997
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
1998
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
1999
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2000
+ }
1805
2001
  }
1806
2002
  /**
1807
2003
  * Consumers should call this method when a request is completed for a peer.