@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
@@ -10,7 +10,14 @@ import {isBlockInputColumns} from "../chain/blocks/blockInput/blockInput.js";
10
10
  import {BlockInputSource, IBlockInput} from "../chain/blocks/blockInput/types.js";
11
11
  import {PayloadError, PayloadErrorCode} from "../chain/blocks/importExecutionPayload.js";
12
12
  import {PayloadEnvelopeInput, PayloadEnvelopeInputSource} from "../chain/blocks/payloadEnvelopeInput/index.js";
13
- import {BlockError, BlockErrorCode} from "../chain/errors/index.js";
13
+ import {
14
+ BlockError,
15
+ BlockErrorCode,
16
+ DataColumnSidecarErrorCode,
17
+ DataColumnSidecarValidationError,
18
+ ExecutionPayloadEnvelopeError,
19
+ ExecutionPayloadEnvelopeErrorCode,
20
+ } from "../chain/errors/index.js";
14
21
  import {ChainEvent, ChainEventData, IBeaconChain} from "../chain/index.js";
15
22
  import {validateGloasBlockDataColumnSidecars} from "../chain/validation/dataColumnSidecar.js";
16
23
  import {validateGossipExecutionPayloadEnvelope} from "../chain/validation/executionPayloadEnvelope.js";
@@ -47,13 +54,22 @@ import {
47
54
  isPendingPayloadEnvelope,
48
55
  isPendingPayloadInput,
49
56
  } from "./types.js";
50
- import {DownloadByRootError, downloadByRoot} from "./utils/downloadByRoot.js";
57
+ import {DownloadByRootError, DownloadByRootErrorCode, downloadByRoot} from "./utils/downloadByRoot.js";
51
58
  import {getAllDescendantBlocks, getUnknownAndAncestorBlocks} from "./utils/pendingBlocksTree.js";
52
59
  import {getRateLimitedUntilMs} from "./utils/rateLimit.js";
53
60
 
54
61
  const MAX_ATTEMPTS_PER_BLOCK = 5;
55
62
  const MAX_KNOWN_BAD_BLOCKS = 500;
56
63
  const MAX_PENDING_BLOCKS = 100;
64
+ /**
65
+ * A failed download is retried after this delay, doubling per failure up to one slot.
66
+ */
67
+ const DOWNLOAD_RETRY_BASE_MS = 1_000;
68
+ /**
69
+ * Requests per peer per window, half the BeaconBlocksByRoot quota peers enforce, they disconnect a peer that exceeds it.
70
+ */
71
+ const MAX_REQUESTS_PER_PEER = 64;
72
+ const REQUESTS_PER_PEER_WINDOW_MS = 10_000;
57
73
  /**
58
74
  * A pending payload without slot can only stay at most 2 epochs.
59
75
  */
@@ -127,6 +143,8 @@ export class BlockInputSync {
127
143
  private subscribedToNetworkEvents = false;
128
144
  private peerBalancer: UnknownBlockPeerBalancer;
129
145
  private rateLimitBackoffTimeout: NodeJS.Timeout | undefined;
146
+ private downloadRetryTimeout: NodeJS.Timeout | undefined;
147
+ private downloadRetryAtMs: number | undefined;
130
148
  /**
131
149
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
132
150
  */
@@ -178,6 +196,7 @@ export class BlockInputSync {
178
196
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
179
197
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
180
198
  this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
199
+ this.chain.clock.on(ClockEvent.slot, this.pruneUnresolvedBlocks);
181
200
 
182
201
  // Seed the balancer with peers that connected before we subscribed
183
202
  for (const peerId of this.network.getConnectedPeers()) {
@@ -198,7 +217,9 @@ export class BlockInputSync {
198
217
  unsubscribeFromNetwork(): void {
199
218
  this.logger.verbose("BlockInputSync disabled.");
200
219
  this.clearRateLimitBackoffTimer();
220
+ this.clearDownloadRetryTimer();
201
221
  this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
222
+ this.chain.clock.off(ClockEvent.slot, this.pruneUnresolvedBlocks);
202
223
  this.payloadPollAbortController?.abort();
203
224
  this.payloadPollAbortController = undefined;
204
225
  this.deferredPayloadRoots.clear();
@@ -346,6 +367,9 @@ export class BlockInputSync {
346
367
  this.addByRootHex(missingDependency.rootHex, data.peer);
347
368
  }
348
369
  this.addByBlockInput(data.blockInput, data.peer);
370
+ if (data.source === BlockInputSource.gossip) {
371
+ this.limitRetainedBlocks(data.blockInput, data.peer);
372
+ }
349
373
  this.triggerUnknownBlockSearch();
350
374
  this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.UNKNOWN_PARENT});
351
375
  this.metrics?.blockInputSync.source.inc({source: data.source});
@@ -485,13 +509,7 @@ export class BlockInputSync {
485
509
  pendingBlock.peerIdStrings.add(peerIdStr);
486
510
  }
487
511
 
488
- // TODO: check this prune methodology
489
- // Limit pending blocks to prevent DOS attacks that cause OOM
490
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
491
- if (prunedItemCount > 0) {
492
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
493
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
494
- }
512
+ this.prunePendingBlocks();
495
513
  return added;
496
514
  };
497
515
 
@@ -527,15 +545,68 @@ export class BlockInputSync {
527
545
  pendingBlock.peerIdStrings.add(peerIdStr);
528
546
  }
529
547
 
530
- // TODO: check this prune methodology
531
- // Limit pending blocks to prevent DOS attacks that cause OOM
532
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
533
- if (prunedItemCount > 0) {
534
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
535
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
536
- }
548
+ this.prunePendingBlocks();
537
549
  };
538
550
 
551
+ /**
552
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
553
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
554
+ * A downloaded block is only checked against its root and proposer signature, not that the proposer is due at its
555
+ * slot, so this only applies while blocks and the roots they wait on fill at most half the cap, otherwise they could
556
+ * pin it and evict every new root on insertion.
557
+ */
558
+ private prunePendingBlocks(): void {
559
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
560
+ return;
561
+ }
562
+
563
+ const awaitedRoots = new Set<RootHex>();
564
+ for (const pendingBlock of this.pendingBlocks.values()) {
565
+ if (isPendingBlockInput(pendingBlock)) {
566
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
567
+ }
568
+ }
569
+ const isKept = (rootHex: RootHex, pendingBlock: BlockInputSyncCacheItem): boolean =>
570
+ isPendingBlockInput(pendingBlock) || awaitedRoots.has(rootHex);
571
+ let keptCount = 0;
572
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
573
+ if (isKept(rootHex, pendingBlock)) {
574
+ keptCount++;
575
+ }
576
+ }
577
+
578
+ let prunedItemCount = 0;
579
+ if (keptCount <= this.maxPendingBlocks / 2) {
580
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
581
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
582
+ break;
583
+ }
584
+ if (!isKept(rootHex, pendingBlock)) {
585
+ this.pendingBlocks.delete(rootHex);
586
+ prunedItemCount++;
587
+ }
588
+ }
589
+ }
590
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
591
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
592
+ break;
593
+ }
594
+ this.pendingBlocks.delete(rootHex);
595
+ prunedItemCount++;
596
+ // The block input cache is only trimmed on import, a block whose parent never resolves would stay there
597
+ if (
598
+ isPendingBlockInput(pendingBlock) &&
599
+ pendingBlock.status !== PendingBlockInputStatus.processing &&
600
+ this.getMissingBlockDependency(pendingBlock.blockInput).kind === "parentBlock"
601
+ ) {
602
+ this.chain.seenBlockInputCache.remove(rootHex);
603
+ }
604
+ }
605
+
606
+ this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
607
+ this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
608
+ }
609
+
539
610
  private addByPayloadRootHex = (rootHex: RootHex, peerIdStr?: PeerIdStr, slot?: Slot): boolean => {
540
611
  if (this.knownBadBlocks.has(rootHex)) {
541
612
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -666,6 +737,79 @@ export class BlockInputSync {
666
737
  this.scheduleRateLimitBackoffRetry();
667
738
  };
668
739
 
740
+ /**
741
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
742
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
743
+ */
744
+ private limitRetainedBlocks(blockInput: IBlockInput, peerIdStr: PeerIdStr): void {
745
+ const pendingBlock = this.pendingBlocks.get(blockInput.blockRootHex);
746
+ if (pendingBlock === undefined || !isPendingBlockInput(pendingBlock) || pendingBlock.retainedBy !== undefined) {
747
+ return;
748
+ }
749
+ pendingBlock.retainedBy = peerIdStr;
750
+ pendingBlock.retainedBytes = this.config
751
+ .getForkTypes(blockInput.slot)
752
+ .SignedBeaconBlock.value_serializedSize(blockInput.getBlock());
753
+
754
+ const retainedBlocks: PendingBlockInput[] = [];
755
+ let retainedBytes = 0;
756
+ for (const item of this.pendingBlocks.values()) {
757
+ if (isPendingBlockInput(item) && item.retainedBy === peerIdStr && this.isWaitingOnParent(item)) {
758
+ retainedBlocks.push(item);
759
+ retainedBytes += item.retainedBytes ?? 0;
760
+ }
761
+ }
762
+ // One block of the max gossip size fits, honest blocks are far smaller
763
+ for (const item of retainedBlocks) {
764
+ if (retainedBytes <= this.config.MAX_PAYLOAD_SIZE) {
765
+ break;
766
+ }
767
+ retainedBytes -= item.retainedBytes ?? 0;
768
+ this.removeUnresolvedBlock(item, DroppedItemReason.peerBudget);
769
+ }
770
+ }
771
+
772
+ /**
773
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
774
+ */
775
+ private pruneUnresolvedBlocks = (): void => {
776
+ const nowSec = Date.now() / 1000;
777
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
778
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
779
+ for (const pendingBlock of this.pendingBlocks.values()) {
780
+ if (
781
+ isPendingBlockInput(pendingBlock) &&
782
+ nowSec - pendingBlock.timeAddedSec > maxSecInCache &&
783
+ this.isWaitingOnParent(pendingBlock)
784
+ ) {
785
+ this.removeUnresolvedBlock(pendingBlock, DroppedItemReason.agedOut);
786
+ }
787
+ }
788
+ };
789
+
790
+ private isWaitingOnParent(pendingBlock: PendingBlockInput): boolean {
791
+ if (pendingBlock.status === PendingBlockInputStatus.processing) {
792
+ return false;
793
+ }
794
+ const {kind} = this.getMissingBlockDependency(pendingBlock.blockInput);
795
+ return kind === "parentBlock" || kind === "parentPayload";
796
+ }
797
+
798
+ /**
799
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
800
+ */
801
+ private removeUnresolvedBlock(pendingBlock: PendingBlockInput, reason: DroppedItemReason): void {
802
+ const rootHex = pendingBlock.blockInput.blockRootHex;
803
+ this.pendingBlocks.delete(rootHex);
804
+ this.chain.seenBlockInputCache.remove(rootHex);
805
+ this.metrics?.blockInputSync.removedBlocks.inc({reason});
806
+ this.logger.debug("Removed unresolved BlockInputSync block", {
807
+ slot: pendingBlock.blockInput.slot,
808
+ root: rootHex,
809
+ reason,
810
+ });
811
+ }
812
+
669
813
  /**
670
814
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
671
815
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -814,8 +958,19 @@ export class BlockInputSync {
814
958
  if (!hasConnectedPeers) {
815
959
  this.logger.debug("No connected peers, skipping unknown block download.");
816
960
  } else {
961
+ // Blocks and roots a pending block waits on are downloaded first, any gossip message with an unknown root adds
962
+ // another root, and they all share the per-peer request budget
963
+ const awaitedRoots = new Set<RootHex>();
964
+ for (const pendingBlock of this.pendingBlocks.values()) {
965
+ if (isPendingBlockInput(pendingBlock)) {
966
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
967
+ }
968
+ }
969
+ const isAwaited = (block: BlockInputSyncCacheItem): boolean =>
970
+ isPendingBlockInput(block) || awaitedRoots.has(block.rootHex);
971
+
817
972
  // Most of the time there is exactly 1 unknown block
818
- for (const block of unknowns) {
973
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
819
974
  this.downloadBlock(block).catch((e) => {
820
975
  this.logger.debug("Unexpected error - downloadBlock", {root: getBlockInputSyncCacheItemRootHex(block)}, e);
821
976
  });
@@ -898,6 +1053,31 @@ export class BlockInputSync {
898
1053
  }
899
1054
  }
900
1055
 
1056
+ private scheduleDownloadRetry(retryAtMs: number): void {
1057
+ if (this.downloadRetryAtMs !== undefined && this.downloadRetryAtMs <= retryAtMs) {
1058
+ return;
1059
+ }
1060
+
1061
+ this.clearDownloadRetryTimer();
1062
+ this.downloadRetryAtMs = retryAtMs;
1063
+ this.downloadRetryTimeout = setTimeout(
1064
+ () => {
1065
+ this.downloadRetryTimeout = undefined;
1066
+ this.downloadRetryAtMs = undefined;
1067
+ this.triggerUnknownBlockSearch();
1068
+ },
1069
+ Math.max(0, retryAtMs - Date.now())
1070
+ );
1071
+ }
1072
+
1073
+ private clearDownloadRetryTimer(): void {
1074
+ if (this.downloadRetryTimeout !== undefined) {
1075
+ clearTimeout(this.downloadRetryTimeout);
1076
+ this.downloadRetryTimeout = undefined;
1077
+ }
1078
+ this.downloadRetryAtMs = undefined;
1079
+ }
1080
+
901
1081
  /**
902
1082
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
903
1083
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -1019,6 +1199,10 @@ export class BlockInputSync {
1019
1199
  if (block.status !== PendingBlockInputStatus.pending) {
1020
1200
  return;
1021
1201
  }
1202
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1203
+ this.scheduleDownloadRetry(block.retryAtMs);
1204
+ return;
1205
+ }
1022
1206
 
1023
1207
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
1024
1208
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
@@ -1099,6 +1283,7 @@ export class BlockInputSync {
1099
1283
  const pendingBlock = this.pendingBlocks.get(rootHex);
1100
1284
  if (pendingBlock) {
1101
1285
  pendingBlock.status = PendingBlockInputStatus.pending;
1286
+ pendingBlock.retryAtMs = res.err.retryAt;
1102
1287
  }
1103
1288
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
1104
1289
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -1109,11 +1294,31 @@ export class BlockInputSync {
1109
1294
  return;
1110
1295
  }
1111
1296
 
1297
+ if (
1298
+ res.err instanceof DownloadByRootError &&
1299
+ res.err.type.code === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT
1300
+ ) {
1301
+ this.logger.debug("Downloaded block is before finalized slot", logCtx, res.err);
1302
+ this.removeAllDescendants(block, DroppedItemReason.belowFinalized);
1303
+ return;
1304
+ }
1305
+
1112
1306
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
1113
1307
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
1114
1308
  const pendingBlock = this.pendingBlocks.get(rootHex);
1115
- if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1309
+ // A partial download replaces the entry with a pending one that does not carry the failure count
1310
+ if (
1311
+ pendingBlock &&
1312
+ (pendingBlock.status === PendingBlockInputStatus.fetching ||
1313
+ pendingBlock.status === PendingBlockInputStatus.pending)
1314
+ ) {
1116
1315
  pendingBlock.status = PendingBlockInputStatus.pending;
1316
+ // Not retried on every search, any gossip message with an unknown root triggers one
1317
+ pendingBlock.failedDownloads = (block.failedDownloads ?? 0) + 1;
1318
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
1319
+ pendingBlock.retryAtMs =
1320
+ Date.now() + Math.min(DOWNLOAD_RETRY_BASE_MS * 2 ** (pendingBlock.failedDownloads - 1), slotDurationMs);
1321
+ this.scheduleDownloadRetry(pendingBlock.retryAtMs);
1117
1322
  }
1118
1323
  }
1119
1324
  }
@@ -1305,7 +1510,7 @@ export class BlockInputSync {
1305
1510
  const pendingPayloadByRoot: PendingPayloadRootHex = {
1306
1511
  status: PendingPayloadInputStatus.pending,
1307
1512
  rootHex,
1308
- slot: pendingPayload.envelope.message.payload.slotNumber,
1513
+ slot: payloadInput.slot,
1309
1514
  timeAddedSec: pendingPayload.timeAddedSec,
1310
1515
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1311
1516
  };
@@ -1671,6 +1876,27 @@ export class BlockInputSync {
1671
1876
  } else {
1672
1877
  excludedPeers.add(peerId);
1673
1878
  }
1879
+
1880
+ if (e instanceof ExecutionPayloadEnvelopeError) {
1881
+ switch (e.type.code) {
1882
+ // Caused by local state, the downloaded envelope may still be valid
1883
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1884
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1885
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1886
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1887
+ break;
1888
+ // Every copy fails once the block is finalized, only a wrong slot makes the served copy invalid
1889
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1890
+ if (envelope?.message.payload.slotNumber !== payloadInput?.slot) {
1891
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1892
+ }
1893
+ break;
1894
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1895
+ default:
1896
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1897
+ break;
1898
+ }
1899
+ }
1674
1900
  } finally {
1675
1901
  this.peerBalancer.onRequestCompleted(peerId);
1676
1902
  }
@@ -1773,7 +1999,20 @@ export class BlockInputSync {
1773
1999
 
1774
2000
  let i = 0;
1775
2001
  let deferredByRateLimit = false;
2002
+ let requestedWhenReconstructable = false;
1776
2003
  while (i++ < this.getMaxDownloadAttempts()) {
2004
+ const reconstructable =
2005
+ isPendingBlockInput(cacheItem) &&
2006
+ isBlockInputColumns(cacheItem.blockInput) &&
2007
+ cacheItem.blockInput.hasBlockAndAllData();
2008
+ // Reconstruction recovers whole rows however many columns are missing, so only one more request is worth it,
2009
+ // further peers could each hold the import until their response times out
2010
+ if (reconstructable) {
2011
+ if (requestedWhenReconstructable) {
2012
+ break;
2013
+ }
2014
+ requestedWhenReconstructable = true;
2015
+ }
1777
2016
  const pendingColumns =
1778
2017
  isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
1779
2018
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
@@ -1788,6 +2027,10 @@ export class BlockInputSync {
1788
2027
  now
1789
2028
  );
1790
2029
  if (peerMeta === null) {
2030
+ if (reconstructable) {
2031
+ break;
2032
+ }
2033
+
1791
2034
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
1792
2035
  if (retryAt !== null) {
1793
2036
  throw new UnknownBlockRateLimitedError(
@@ -1832,8 +2075,16 @@ export class BlockInputSync {
1832
2075
  for (const warning of warnings) {
1833
2076
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
1834
2077
  this.metrics?.blockInputSync.downloadByRoot.warn.inc({code: warning.type.code, client: peerClient});
2078
+ // A partial response is legal, columns that were not requested are not
2079
+ if (warning.type.code === DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED) {
2080
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, warning.type.code);
2081
+ excludedPeers.add(peerId);
2082
+ }
2083
+ // Not picked again for this block, it would be preferred as a previous source of it
2084
+ if (warning.type.code === DownloadByRootErrorCode.NOT_ENOUGH_SIDECARS_RECEIVED) {
2085
+ excludedPeers.add(peerId);
2086
+ }
1835
2087
  }
1836
- // TODO: penalize peer?
1837
2088
  }
1838
2089
  } catch (e) {
1839
2090
  this.logger.debug(
@@ -1842,10 +2093,36 @@ export class BlockInputSync {
1842
2093
  e as Error
1843
2094
  );
1844
2095
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
1845
- // TODO: penalize peer?
1846
2096
  if (e instanceof DownloadByRootError) {
1847
2097
  const errorCode = e.type.code;
1848
2098
  downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2099
+ if (errorCode === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
2100
+ throw e;
2101
+ }
2102
+ // Low as in range sync, not Fatal as peers may serve unverified copies of a root with a bad signature
2103
+ if (
2104
+ errorCode === DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT ||
2105
+ errorCode === DownloadByRootErrorCode.PROPOSAL_SIGNATURE_INVALID ||
2106
+ errorCode === DownloadByRootErrorCode.UNKNOWN_PROPOSER
2107
+ ) {
2108
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2109
+ }
2110
+ excludedPeers.add(peerId);
2111
+ } else if (e instanceof DataColumnSidecarValidationError) {
2112
+ const errorCode = e.type.code;
2113
+ downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2114
+ // Not PROPOSAL_SIGNATURE_INVALID or INCORRECT_HEADER_ROOT, which compares signatures too: the spec does not
2115
+ // require verifying the header signature of req/resp columns, so honest peers may serve a bad one
2116
+ switch (errorCode) {
2117
+ case DataColumnSidecarErrorCode.INCORRECT_BLOCK:
2118
+ case DataColumnSidecarErrorCode.INVALID_INDEX:
2119
+ case DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT:
2120
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
2121
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
2122
+ case DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID:
2123
+ case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
2124
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2125
+ }
1849
2126
  excludedPeers.add(peerId);
1850
2127
  } else if (e instanceof RequestError) {
1851
2128
  // should look into req_resp metrics in this case
@@ -1898,6 +2175,30 @@ export class BlockInputSync {
1898
2175
 
1899
2176
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
1900
2177
 
2178
+ if (
2179
+ isPendingBlockInput(cacheItem) &&
2180
+ isBlockInputColumns(cacheItem.blockInput) &&
2181
+ cacheItem.blockInput.hasBlockAndAllData()
2182
+ ) {
2183
+ // Peers cannot serve the remaining columns now, half of them is enough to reconstruct the rest
2184
+ this.logger.verbose("BlockInputSync.fetchBlockInput: reconstructing columns peers could not serve", {
2185
+ slot,
2186
+ rootHex,
2187
+ missing: cacheItem.blockInput.getMissingSampledColumnMeta().missing.length,
2188
+ });
2189
+ this.chain.columnReconstructionTracker.triggerColumnReconstruction(cacheItem.blockInput);
2190
+ cacheItem = {...cacheItem, status: PendingBlockInputStatus.downloaded, timeSyncedSec: Date.now() / 1000};
2191
+ if (this.pendingBlocks.has(rootHex)) {
2192
+ this.pendingBlocks.set(rootHex, cacheItem);
2193
+ }
2194
+ const result = this.chain.forkChoice.hasBlockHex(cacheItem.blockInput.parentRootHex)
2195
+ ? FetchResult.SuccessResolved
2196
+ : FetchResult.SuccessMissingParent;
2197
+ this.metrics?.blockInputSync.fetchTime.observe({result}, Date.now() / 1000 - fetchStartSec);
2198
+ this.metrics?.blockInputSync.fetchPeers.set({result}, i - 1);
2199
+ return cacheItem;
2200
+ }
2201
+
1901
2202
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
1902
2203
  if (retryAt !== null) {
1903
2204
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -2051,11 +2352,13 @@ export class UnknownBlockPeerBalancer {
2051
2352
  readonly peersMeta: Map<PeerIdStr, PeerSyncMeta>;
2052
2353
  readonly activeRequests: Map<PeerIdStr, number>;
2053
2354
  readonly rateLimitedUntilByPeer: Map<PeerIdStr, number>;
2355
+ readonly requestTimesByPeer: Map<PeerIdStr, number[]>;
2054
2356
 
2055
2357
  constructor() {
2056
2358
  this.peersMeta = new Map();
2057
2359
  this.activeRequests = new Map();
2058
2360
  this.rateLimitedUntilByPeer = new Map();
2361
+ this.requestTimesByPeer = new Map();
2059
2362
  }
2060
2363
 
2061
2364
  /** Trigger on each peer re-status */
@@ -2071,6 +2374,7 @@ export class UnknownBlockPeerBalancer {
2071
2374
  this.peersMeta.delete(peerId);
2072
2375
  this.activeRequests.delete(peerId);
2073
2376
  this.rateLimitedUntilByPeer.delete(peerId);
2377
+ this.requestTimesByPeer.delete(peerId);
2074
2378
  }
2075
2379
 
2076
2380
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
@@ -2078,6 +2382,7 @@ export class UnknownBlockPeerBalancer {
2078
2382
  this.peersMeta.clear();
2079
2383
  this.activeRequests.clear();
2080
2384
  this.rateLimitedUntilByPeer.clear();
2385
+ this.requestTimesByPeer.clear();
2081
2386
  }
2082
2387
 
2083
2388
  onRateLimited(peerId: PeerIdStr, rateLimitedUntilMs: number): void {
@@ -2144,7 +2449,7 @@ export class UnknownBlockPeerBalancer {
2144
2449
  );
2145
2450
 
2146
2451
  const bestPeerId = sortedEligiblePeers[0];
2147
- this.onRequest(bestPeerId);
2452
+ this.onRequest(bestPeerId, now);
2148
2453
  return this.peersMeta.get(bestPeerId) ?? null;
2149
2454
  }
2150
2455
 
@@ -2152,8 +2457,18 @@ export class UnknownBlockPeerBalancer {
2152
2457
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
2153
2458
  * make this public for testing
2154
2459
  */
2155
- onRequest(peerId: PeerIdStr): void {
2460
+ onRequest(peerId: PeerIdStr, now = Date.now()): void {
2156
2461
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
2462
+
2463
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter(
2464
+ (time) => now - time < REQUESTS_PER_PEER_WINDOW_MS
2465
+ );
2466
+ requestTimes.push(now);
2467
+ this.requestTimesByPeer.set(peerId, requestTimes);
2468
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
2469
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
2470
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2471
+ }
2157
2472
  }
2158
2473
 
2159
2474
  /**
@@ -121,7 +121,12 @@ export function cacheByRangeResponses({
121
121
  parentPayload,
122
122
  custodyConfig,
123
123
  seenTimestampSec,
124
- }: CacheByRangeResponsesProps): {blocks: IBlockInput[]; payloadEnvelopes: Map<Slot, PayloadEnvelopeInput> | null} {
124
+ }: CacheByRangeResponsesProps): {
125
+ blocks: IBlockInput[];
126
+ payloadEnvelopes: Map<Slot, PayloadEnvelopeInput> | null;
127
+ /** First fulu column whose header signature differs from its cached block, no later column is added */
128
+ signatureMismatch: {blockInput: IBlockInput; columnSidecar: fulu.DataColumnSidecar} | null;
129
+ } {
125
130
  const source = BlockInputSource.byRange;
126
131
  const updatedBatchBlocks = new Map<Slot, IBlockInput>(batchBlocks.map((block) => [block.slot, block]));
127
132
 
@@ -217,6 +222,7 @@ export function cacheByRangeResponses({
217
222
  }
218
223
  }
219
224
 
225
+ let signatureMismatch: {blockInput: IBlockInput; columnSidecar: fulu.DataColumnSidecar} | null = null;
220
226
  for (const {blockRoot, columnSidecars} of responses.validatedColumnSidecars ?? []) {
221
227
  const firstColumn = columnSidecars[0];
222
228
  if (!firstColumn) {
@@ -264,6 +270,17 @@ export function cacheByRangeResponses({
264
270
  actual: existing.type,
265
271
  });
266
272
  }
273
+
274
+ // Honest sidecars carry the block signature. The cached block may be unverified, the caller decides which side
275
+ // is invalid. A different root is reported by addColumn.
276
+ if (
277
+ existing.blockRootHex === blockRootHex &&
278
+ !byteArrayEquals(existing.getBlock().signature, fuluColumns[0].signedBlockHeader.signature)
279
+ ) {
280
+ signatureMismatch = {blockInput: existing, columnSidecar: fuluColumns[0]};
281
+ break;
282
+ }
283
+
267
284
  for (const columnSidecar of fuluColumns) {
268
285
  // will throw if root hex does not match (meaning we are following the wrong chain)
269
286
  existing.addColumn(
@@ -279,7 +296,7 @@ export function cacheByRangeResponses({
279
296
  }
280
297
  }
281
298
 
282
- return {blocks: Array.from(updatedBatchBlocks.values()), payloadEnvelopes};
299
+ return {blocks: Array.from(updatedBatchBlocks.values()), payloadEnvelopes, signatureMismatch};
283
300
  }
284
301
 
285
302
  export async function downloadByRange({
@@ -895,7 +912,7 @@ export async function validateColumnsByRangeResponse(
895
912
  peerDasMetrics
896
913
  )
897
914
  : validateFuluBlockDataColumnSidecars(
898
- null, // do not pass chain here so we do not validate header signature
915
+ null, // skip BLS, cacheByRangeResponses matches the header signature against the block
899
916
  slot,
900
917
  blockRoot,
901
918
  blobCount,
@@ -1009,6 +1026,8 @@ export enum DownloadByRangeErrorCode {
1009
1026
 
1010
1027
  /** Block segment + envelopes failed chain-segment linearity / FULL-chain checks */
1011
1028
  INVALID_CHAIN_SEGMENT = "DOWNLOAD_BY_RANGE_ERROR_INVALID_CHAIN_SEGMENT",
1029
+ /** A column header signature differs from a cached block whose proposer signature is invalid or unverifiable */
1030
+ INVALID_CACHED_BLOCK = "DOWNLOAD_BY_RANGE_ERROR_INVALID_CACHED_BLOCK",
1012
1031
  }
1013
1032
 
1014
1033
  export type DownloadByRangeErrorType =
@@ -1105,6 +1124,13 @@ export type DownloadByRangeErrorType =
1105
1124
  code: DownloadByRangeErrorCode.INVALID_CHAIN_SEGMENT;
1106
1125
  slot: Slot;
1107
1126
  reason: string;
1127
+ }
1128
+ | {
1129
+ code: DownloadByRangeErrorCode.INVALID_CACHED_BLOCK;
1130
+ slot: Slot;
1131
+ blockRoot: string;
1132
+ /** Set only when the block proposer signature is invalid */
1133
+ blockPeer?: PeerIdStr;
1108
1134
  };
1109
1135
 
1110
1136
  export class DownloadByRangeError extends LodestarError<DownloadByRangeErrorType> {}