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

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 (175) 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 +13 -4
  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/attestationError.d.ts +15 -1
  32. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  33. package/lib/chain/errors/attestationError.js +8 -0
  34. package/lib/chain/errors/attestationError.js.map +1 -1
  35. package/lib/chain/errors/executionPayloadBid.d.ts +3 -2
  36. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  37. package/lib/chain/errors/executionPayloadBid.js +1 -1
  38. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  39. package/lib/chain/errors/executionPayloadEnvelope.d.ts +48 -0
  40. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  41. package/lib/chain/errors/executionPayloadEnvelope.js +7 -0
  42. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  43. package/lib/chain/interface.d.ts +1 -1
  44. package/lib/chain/interface.d.ts.map +1 -1
  45. package/lib/chain/opPools/opPool.js +6 -6
  46. package/lib/chain/opPools/opPool.js.map +1 -1
  47. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  48. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  49. package/lib/chain/seenCache/seenAttesters.js +1 -1
  50. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  51. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  52. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  53. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  54. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  55. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts +13 -4
  56. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts.map +1 -1
  57. package/lib/chain/seenCache/seenExecutionPayloadBids.js +13 -12
  58. package/lib/chain/seenCache/seenExecutionPayloadBids.js.map +1 -1
  59. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  60. package/lib/chain/validation/aggregateAndProof.js +24 -7
  61. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  62. package/lib/chain/validation/attestation.d.ts.map +1 -1
  63. package/lib/chain/validation/attestation.js +32 -16
  64. package/lib/chain/validation/attestation.js.map +1 -1
  65. package/lib/chain/validation/block.d.ts.map +1 -1
  66. package/lib/chain/validation/block.js +9 -1
  67. package/lib/chain/validation/block.js.map +1 -1
  68. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  69. package/lib/chain/validation/executionPayloadBid.js +30 -40
  70. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  71. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  72. package/lib/chain/validation/executionPayloadEnvelope.js +79 -4
  73. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  74. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  75. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  76. package/lib/chain/validatorMonitor.js +43 -43
  77. package/lib/chain/validatorMonitor.js.map +1 -1
  78. package/lib/network/gossip/gossipsub.js +2 -2
  79. package/lib/network/gossip/gossipsub.js.map +1 -1
  80. package/lib/network/gossip/topic.d.ts +1 -7
  81. package/lib/network/gossip/topic.d.ts.map +1 -1
  82. package/lib/network/gossip/topic.js +0 -13
  83. package/lib/network/gossip/topic.js.map +1 -1
  84. package/lib/network/network.d.ts +1 -0
  85. package/lib/network/network.d.ts.map +1 -1
  86. package/lib/network/network.js +20 -11
  87. package/lib/network/network.js.map +1 -1
  88. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  89. package/lib/network/processor/gossipHandlers.js +19 -6
  90. package/lib/network/processor/gossipHandlers.js.map +1 -1
  91. package/lib/network/processor/gossipValidatorFn.d.ts.map +1 -1
  92. package/lib/network/processor/gossipValidatorFn.js +4 -1
  93. package/lib/network/processor/gossipValidatorFn.js.map +1 -1
  94. package/lib/network/processor/index.d.ts.map +1 -1
  95. package/lib/network/processor/index.js +4 -2
  96. package/lib/network/processor/index.js.map +1 -1
  97. package/lib/network/reqresp/utils/collect.d.ts +4 -4
  98. package/lib/network/reqresp/utils/collect.d.ts.map +1 -1
  99. package/lib/network/reqresp/utils/collect.js +9 -8
  100. package/lib/network/reqresp/utils/collect.js.map +1 -1
  101. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts +1 -1
  102. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts.map +1 -1
  103. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js +2 -2
  104. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js.map +1 -1
  105. package/lib/sync/range/batch.d.ts +6 -0
  106. package/lib/sync/range/batch.d.ts.map +1 -1
  107. package/lib/sync/range/batch.js +17 -0
  108. package/lib/sync/range/batch.js.map +1 -1
  109. package/lib/sync/range/chain.d.ts.map +1 -1
  110. package/lib/sync/range/chain.js +8 -1
  111. package/lib/sync/range/chain.js.map +1 -1
  112. package/lib/sync/range/range.d.ts.map +1 -1
  113. package/lib/sync/range/range.js +43 -3
  114. package/lib/sync/range/range.js.map +1 -1
  115. package/lib/sync/types.d.ts +12 -1
  116. package/lib/sync/types.d.ts.map +1 -1
  117. package/lib/sync/types.js +2 -0
  118. package/lib/sync/types.js.map +1 -1
  119. package/lib/sync/unknownBlock.d.ts +28 -1
  120. package/lib/sync/unknownBlock.d.ts.map +1 -1
  121. package/lib/sync/unknownBlock.js +234 -22
  122. package/lib/sync/unknownBlock.js.map +1 -1
  123. package/lib/sync/utils/downloadByRange.d.ts +14 -1
  124. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  125. package/lib/sync/utils/downloadByRange.js +12 -2
  126. package/lib/sync/utils/downloadByRange.js.map +1 -1
  127. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  128. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  129. package/lib/sync/utils/downloadByRoot.js +43 -1
  130. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  131. package/lib/util/eventLoop.d.ts +3 -3
  132. package/lib/util/eventLoop.d.ts.map +1 -1
  133. package/lib/util/eventLoop.js +3 -3
  134. package/lib/util/eventLoop.js.map +1 -1
  135. package/package.json +17 -17
  136. package/src/api/impl/beacon/blocks/index.ts +52 -28
  137. package/src/api/impl/beacon/pool/index.ts +9 -7
  138. package/src/api/impl/beacon/state/utils.ts +2 -1
  139. package/src/api/impl/debug/index.ts +6 -2
  140. package/src/api/impl/validator/index.ts +15 -5
  141. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  142. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  143. package/src/chain/blocks/index.ts +3 -31
  144. package/src/chain/chain.ts +95 -37
  145. package/src/chain/errors/attestationError.ts +11 -1
  146. package/src/chain/errors/executionPayloadBid.ts +3 -2
  147. package/src/chain/errors/executionPayloadEnvelope.ts +50 -0
  148. package/src/chain/interface.ts +1 -1
  149. package/src/chain/opPools/opPool.ts +6 -6
  150. package/src/chain/seenCache/seenAttesters.ts +1 -1
  151. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  152. package/src/chain/seenCache/seenExecutionPayloadBids.ts +35 -15
  153. package/src/chain/validation/aggregateAndProof.ts +24 -9
  154. package/src/chain/validation/attestation.ts +31 -20
  155. package/src/chain/validation/block.ts +9 -1
  156. package/src/chain/validation/executionPayloadBid.ts +40 -42
  157. package/src/chain/validation/executionPayloadEnvelope.ts +87 -3
  158. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  159. package/src/chain/validatorMonitor.ts +43 -43
  160. package/src/network/gossip/gossipsub.ts +2 -2
  161. package/src/network/gossip/topic.ts +1 -14
  162. package/src/network/network.ts +33 -11
  163. package/src/network/processor/gossipHandlers.ts +25 -13
  164. package/src/network/processor/gossipValidatorFn.ts +4 -0
  165. package/src/network/processor/index.ts +7 -2
  166. package/src/network/reqresp/utils/collect.ts +16 -8
  167. package/src/network/reqresp/utils/collectSequentialBlocksInRange.ts +3 -2
  168. package/src/sync/range/batch.ts +20 -0
  169. package/src/sync/range/chain.ts +8 -0
  170. package/src/sync/range/range.ts +56 -3
  171. package/src/sync/types.ts +11 -0
  172. package/src/sync/unknownBlock.ts +272 -22
  173. package/src/sync/utils/downloadByRange.ts +29 -3
  174. package/src/sync/utils/downloadByRoot.ts +68 -2
  175. package/src/util/eventLoop.ts +3 -3
@@ -633,6 +633,26 @@ export class Batch {
633
633
  };
634
634
  }
635
635
 
636
+ /**
637
+ * Downloading -> AwaitingDownload
638
+ *
639
+ * The batch may hold an evicted invalid block, drop every downloaded block and request the whole batch again
640
+ */
641
+ downloadingInvalidBlock(peer: PeerIdStr): void {
642
+ if (this.state.status !== BatchStatus.Downloading) {
643
+ throw new BatchError(this.wrongStatusErrorType(BatchStatus.Downloading));
644
+ }
645
+
646
+ this.failedDownloadAttempts.push(peer);
647
+ if (this.failedDownloadAttempts.length > MAX_BATCH_DOWNLOAD_ATTEMPTS) {
648
+ throw new BatchError(this.errorType({code: BatchErrorCode.MAX_DOWNLOAD_ATTEMPTS}));
649
+ }
650
+
651
+ this.successfulDownloads.clear();
652
+ this.state = {status: BatchStatus.AwaitingDownload, blocks: [], payloadEnvelopes: null};
653
+ this.resetRequests();
654
+ }
655
+
636
656
  /**
637
657
  * Downloading -> AwaitingDownload (without counting as a failed attempt).
638
658
  * Used when the peer rate-limited us — the request was never actually served.
@@ -602,6 +602,14 @@ export class SyncChain {
602
602
  this.scheduleRateLimitBackoffRetry();
603
603
  batch.downloadingRateLimited();
604
604
  this.triggerBatchDownloader();
605
+ } else if (
606
+ res.err instanceof DownloadByRangeError &&
607
+ res.err.type.code === DownloadByRangeErrorCode.INVALID_CACHED_BLOCK
608
+ ) {
609
+ if (res.err.type.blockPeer !== undefined) {
610
+ this.reportPeer(res.err.type.blockPeer, PeerAction.LowToleranceError, res.err.message);
611
+ }
612
+ batch.downloadingInvalidBlock(res.err.type.blockPeer ?? peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
605
613
  } else {
606
614
  batch.downloadingError(peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
607
615
  }
@@ -3,13 +3,20 @@ import {StrictEventEmitter} from "strict-event-emitter-types";
3
3
  import {BeaconConfig} from "@lodestar/config";
4
4
  import {IBeaconStateViewGloas, computeStartSlotAtEpoch, isStatePostGloas} from "@lodestar/state-transition";
5
5
  import {Epoch, Status, fulu, ssz} from "@lodestar/types";
6
- import {Logger, byteArrayEquals, prettyPrintIndices, toRootHex} from "@lodestar/utils";
6
+ import {Logger, byteArrayEquals, prettyPrintIndices, toHex, toRootHex} from "@lodestar/utils";
7
7
  import {IBlockInput} from "../../chain/blocks/blockInput/types.js";
8
8
  import {PayloadError, PayloadErrorCode} from "../../chain/blocks/importExecutionPayload.js";
9
9
  import {AttestationImportOpt, ImportBlockOpts} from "../../chain/blocks/index.js";
10
10
  import {assertLinearChainSegment} from "../../chain/blocks/utils/chainSegment.js";
11
- import {BlockError} from "../../chain/errors/index.js";
11
+ import {
12
+ BlockError,
13
+ BlockErrorCode,
14
+ BlockGossipError,
15
+ DataColumnSidecarErrorCode,
16
+ DataColumnSidecarValidationError,
17
+ } from "../../chain/errors/index.js";
12
18
  import {IBeaconChain} from "../../chain/index.js";
19
+ import {verifyBlockProposerSignature} from "../../chain/validation/block.js";
13
20
  import {Metrics} from "../../metrics/index.js";
14
21
  import {INetwork} from "../../network/index.js";
15
22
  import {PeerIdStr} from "../../util/peerId.js";
@@ -291,7 +298,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
291
298
  ...requests,
292
299
  });
293
300
  const {responses, payloadEnvelopes: downloadedPayloadEnvelopes} = result;
294
- const {blocks, payloadEnvelopes} = cacheByRangeResponses({
301
+ const {blocks, payloadEnvelopes, signatureMismatch} = cacheByRangeResponses({
295
302
  cache: this.chain.seenBlockInputCache,
296
303
  seenPayloadEnvelopeInputCache: this.chain.seenPayloadEnvelopeInputCache,
297
304
  peerIdStr: peer.peerId,
@@ -304,6 +311,52 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
304
311
  seenTimestampSec: Date.now() / 1000,
305
312
  });
306
313
 
314
+ if (signatureMismatch !== null) {
315
+ const {blockInput, columnSidecar} = signatureMismatch;
316
+ const block = blockInput.getBlock();
317
+ let isValidBlockSignature: boolean | null = true;
318
+ try {
319
+ await verifyBlockProposerSignature(this.chain, block, blockInput.blockRootHex);
320
+ } catch (e) {
321
+ isValidBlockSignature =
322
+ e instanceof BlockGossipError && e.type.code === BlockErrorCode.PROPOSAL_SIGNATURE_INVALID ? false : null;
323
+ }
324
+
325
+ if (isValidBlockSignature) {
326
+ throw new DataColumnSidecarValidationError(
327
+ {
328
+ code: DataColumnSidecarErrorCode.INCORRECT_BLOCK,
329
+ slot: blockInput.slot,
330
+ columnIndex: columnSidecar.index,
331
+ expected: toHex(block.signature),
332
+ actual: toHex(columnSidecar.signedBlockHeader.signature),
333
+ },
334
+ "DataColumnSidecar header signature doesn't match block signature"
335
+ );
336
+ }
337
+
338
+ // Later downloads reuse a cached block, evict it and the other unverified blocks of a peer
339
+ // proven to serve invalid signatures
340
+ const blockPeer = isValidBlockSignature === false ? blockInput.getBlockSource().peerIdStr : undefined;
341
+ const cache = this.chain.seenBlockInputCache;
342
+ for (const b of blocks) {
343
+ const isSuspect = b === blockInput || (blockPeer !== undefined && b.getBlockSource().peerIdStr === blockPeer);
344
+ if (
345
+ isSuspect &&
346
+ cache.get(b.blockRootHex) === b &&
347
+ !cache.isVerifiedProposerSignature(b.slot, b.blockRootHex, b.getBlock().signature)
348
+ ) {
349
+ cache.remove(b.blockRootHex);
350
+ }
351
+ }
352
+ throw new DownloadByRangeError({
353
+ code: DownloadByRangeErrorCode.INVALID_CACHED_BLOCK,
354
+ slot: blockInput.slot,
355
+ blockRoot: blockInput.blockRootHex,
356
+ blockPeer,
357
+ });
358
+ }
359
+
307
360
  const segmentBlocks = blocks.filter((b) => b.hasBlock()).sort((a, b) => a.slot - b.slot);
308
361
  const envelopeSlots = payloadEnvelopes
309
362
  ? Array.from(payloadEnvelopes.entries())
package/src/sync/types.ts CHANGED
@@ -107,6 +107,8 @@ export enum DroppedItemReason {
107
107
  invalidSignature = "invalid_signature",
108
108
  /** an unexpected / unhandled error code led to removal */
109
109
  unknown = "unknown",
110
+ /** a block waiting on its parent was evicted because the peer that gossiped it exceeded its byte budget */
111
+ peerBudget = "peer_budget",
110
112
  }
111
113
 
112
114
  export enum PendingPayloadInputStatus {
@@ -123,6 +125,12 @@ export type PendingBlockInput = {
123
125
  timeAddedSec: number;
124
126
  timeSyncedSec?: number;
125
127
  peerIdStrings: Set<string>;
128
+ /** Peer that gossiped a block retained for unknown parent sync */
129
+ retainedBy?: string;
130
+ retainedBytes?: number;
131
+ failedDownloads?: number;
132
+ /** A failed download is not retried before this time */
133
+ retryAtMs?: number;
126
134
  };
127
135
 
128
136
  export type PendingRootHex = {
@@ -131,6 +139,9 @@ export type PendingRootHex = {
131
139
  timeAddedSec: number;
132
140
  timeSyncedSec?: number;
133
141
  peerIdStrings: Set<string>;
142
+ failedDownloads?: number;
143
+ /** A failed download is not retried before this time */
144
+ retryAtMs?: number;
134
145
  };
135
146
 
136
147
  export type BlockInputSyncCacheItem = PendingBlockInput | PendingRootHex;
@@ -10,7 +10,12 @@ 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
+ ExecutionPayloadEnvelopeError,
17
+ ExecutionPayloadEnvelopeErrorCode,
18
+ } from "../chain/errors/index.js";
14
19
  import {ChainEvent, ChainEventData, IBeaconChain} from "../chain/index.js";
15
20
  import {validateGloasBlockDataColumnSidecars} from "../chain/validation/dataColumnSidecar.js";
16
21
  import {validateGossipExecutionPayloadEnvelope} from "../chain/validation/executionPayloadEnvelope.js";
@@ -47,13 +52,22 @@ import {
47
52
  isPendingPayloadEnvelope,
48
53
  isPendingPayloadInput,
49
54
  } from "./types.js";
50
- import {DownloadByRootError, downloadByRoot} from "./utils/downloadByRoot.js";
55
+ import {DownloadByRootError, DownloadByRootErrorCode, downloadByRoot} from "./utils/downloadByRoot.js";
51
56
  import {getAllDescendantBlocks, getUnknownAndAncestorBlocks} from "./utils/pendingBlocksTree.js";
52
57
  import {getRateLimitedUntilMs} from "./utils/rateLimit.js";
53
58
 
54
59
  const MAX_ATTEMPTS_PER_BLOCK = 5;
55
60
  const MAX_KNOWN_BAD_BLOCKS = 500;
56
61
  const MAX_PENDING_BLOCKS = 100;
62
+ /**
63
+ * A failed download is retried after this delay, doubling per failure up to one slot.
64
+ */
65
+ const DOWNLOAD_RETRY_BASE_MS = 1_000;
66
+ /**
67
+ * Requests per peer per window, half the BeaconBlocksByRoot quota peers enforce, they disconnect a peer that exceeds it.
68
+ */
69
+ const MAX_REQUESTS_PER_PEER = 64;
70
+ const REQUESTS_PER_PEER_WINDOW_MS = 10_000;
57
71
  /**
58
72
  * A pending payload without slot can only stay at most 2 epochs.
59
73
  */
@@ -127,6 +141,8 @@ export class BlockInputSync {
127
141
  private subscribedToNetworkEvents = false;
128
142
  private peerBalancer: UnknownBlockPeerBalancer;
129
143
  private rateLimitBackoffTimeout: NodeJS.Timeout | undefined;
144
+ private downloadRetryTimeout: NodeJS.Timeout | undefined;
145
+ private downloadRetryAtMs: number | undefined;
130
146
  /**
131
147
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
132
148
  */
@@ -178,6 +194,7 @@ export class BlockInputSync {
178
194
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
179
195
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
180
196
  this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
197
+ this.chain.clock.on(ClockEvent.slot, this.pruneUnresolvedBlocks);
181
198
 
182
199
  // Seed the balancer with peers that connected before we subscribed
183
200
  for (const peerId of this.network.getConnectedPeers()) {
@@ -198,7 +215,9 @@ export class BlockInputSync {
198
215
  unsubscribeFromNetwork(): void {
199
216
  this.logger.verbose("BlockInputSync disabled.");
200
217
  this.clearRateLimitBackoffTimer();
218
+ this.clearDownloadRetryTimer();
201
219
  this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
220
+ this.chain.clock.off(ClockEvent.slot, this.pruneUnresolvedBlocks);
202
221
  this.payloadPollAbortController?.abort();
203
222
  this.payloadPollAbortController = undefined;
204
223
  this.deferredPayloadRoots.clear();
@@ -346,6 +365,9 @@ export class BlockInputSync {
346
365
  this.addByRootHex(missingDependency.rootHex, data.peer);
347
366
  }
348
367
  this.addByBlockInput(data.blockInput, data.peer);
368
+ if (data.source === BlockInputSource.gossip) {
369
+ this.limitRetainedBlocks(data.blockInput, data.peer);
370
+ }
349
371
  this.triggerUnknownBlockSearch();
350
372
  this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.UNKNOWN_PARENT});
351
373
  this.metrics?.blockInputSync.source.inc({source: data.source});
@@ -376,7 +398,8 @@ export class BlockInputSync {
376
398
  // because the payload at the finalized block is not finalized
377
399
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
378
400
  const nowSec = Date.now() / 1000;
379
- const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * this.config.SLOT_DURATION_MS) / 1000;
401
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
402
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
380
403
 
381
404
  let belowFinalizedPayloads = 0;
382
405
  let agedOutPayloads = 0;
@@ -484,13 +507,7 @@ export class BlockInputSync {
484
507
  pendingBlock.peerIdStrings.add(peerIdStr);
485
508
  }
486
509
 
487
- // TODO: check this prune methodology
488
- // Limit pending blocks to prevent DOS attacks that cause OOM
489
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
490
- if (prunedItemCount > 0) {
491
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
492
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
493
- }
510
+ this.prunePendingBlocks();
494
511
  return added;
495
512
  };
496
513
 
@@ -526,15 +543,68 @@ export class BlockInputSync {
526
543
  pendingBlock.peerIdStrings.add(peerIdStr);
527
544
  }
528
545
 
529
- // TODO: check this prune methodology
530
- // Limit pending blocks to prevent DOS attacks that cause OOM
531
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
532
- if (prunedItemCount > 0) {
533
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
534
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
535
- }
546
+ this.prunePendingBlocks();
536
547
  };
537
548
 
549
+ /**
550
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
551
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
552
+ * A downloaded block is only checked against its root and proposer signature, not that the proposer is due at its
553
+ * slot, so this only applies while blocks and the roots they wait on fill at most half the cap, otherwise they could
554
+ * pin it and evict every new root on insertion.
555
+ */
556
+ private prunePendingBlocks(): void {
557
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
558
+ return;
559
+ }
560
+
561
+ const awaitedRoots = new Set<RootHex>();
562
+ for (const pendingBlock of this.pendingBlocks.values()) {
563
+ if (isPendingBlockInput(pendingBlock)) {
564
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
565
+ }
566
+ }
567
+ const isKept = (rootHex: RootHex, pendingBlock: BlockInputSyncCacheItem): boolean =>
568
+ isPendingBlockInput(pendingBlock) || awaitedRoots.has(rootHex);
569
+ let keptCount = 0;
570
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
571
+ if (isKept(rootHex, pendingBlock)) {
572
+ keptCount++;
573
+ }
574
+ }
575
+
576
+ let prunedItemCount = 0;
577
+ if (keptCount <= this.maxPendingBlocks / 2) {
578
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
579
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
580
+ break;
581
+ }
582
+ if (!isKept(rootHex, pendingBlock)) {
583
+ this.pendingBlocks.delete(rootHex);
584
+ prunedItemCount++;
585
+ }
586
+ }
587
+ }
588
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
589
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
590
+ break;
591
+ }
592
+ this.pendingBlocks.delete(rootHex);
593
+ prunedItemCount++;
594
+ // The block input cache is only trimmed on import, a block whose parent never resolves would stay there
595
+ if (
596
+ isPendingBlockInput(pendingBlock) &&
597
+ pendingBlock.status !== PendingBlockInputStatus.processing &&
598
+ this.getMissingBlockDependency(pendingBlock.blockInput).kind === "parentBlock"
599
+ ) {
600
+ this.chain.seenBlockInputCache.remove(rootHex);
601
+ }
602
+ }
603
+
604
+ this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
605
+ this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
606
+ }
607
+
538
608
  private addByPayloadRootHex = (rootHex: RootHex, peerIdStr?: PeerIdStr, slot?: Slot): boolean => {
539
609
  if (this.knownBadBlocks.has(rootHex)) {
540
610
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -665,6 +735,79 @@ export class BlockInputSync {
665
735
  this.scheduleRateLimitBackoffRetry();
666
736
  };
667
737
 
738
+ /**
739
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
740
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
741
+ */
742
+ private limitRetainedBlocks(blockInput: IBlockInput, peerIdStr: PeerIdStr): void {
743
+ const pendingBlock = this.pendingBlocks.get(blockInput.blockRootHex);
744
+ if (pendingBlock === undefined || !isPendingBlockInput(pendingBlock) || pendingBlock.retainedBy !== undefined) {
745
+ return;
746
+ }
747
+ pendingBlock.retainedBy = peerIdStr;
748
+ pendingBlock.retainedBytes = this.config
749
+ .getForkTypes(blockInput.slot)
750
+ .SignedBeaconBlock.value_serializedSize(blockInput.getBlock());
751
+
752
+ const retainedBlocks: PendingBlockInput[] = [];
753
+ let retainedBytes = 0;
754
+ for (const item of this.pendingBlocks.values()) {
755
+ if (isPendingBlockInput(item) && item.retainedBy === peerIdStr && this.isWaitingOnParent(item)) {
756
+ retainedBlocks.push(item);
757
+ retainedBytes += item.retainedBytes ?? 0;
758
+ }
759
+ }
760
+ // One block of the max gossip size fits, honest blocks are far smaller
761
+ for (const item of retainedBlocks) {
762
+ if (retainedBytes <= this.config.MAX_PAYLOAD_SIZE) {
763
+ break;
764
+ }
765
+ retainedBytes -= item.retainedBytes ?? 0;
766
+ this.removeUnresolvedBlock(item, DroppedItemReason.peerBudget);
767
+ }
768
+ }
769
+
770
+ /**
771
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
772
+ */
773
+ private pruneUnresolvedBlocks = (): void => {
774
+ const nowSec = Date.now() / 1000;
775
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
776
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
777
+ for (const pendingBlock of this.pendingBlocks.values()) {
778
+ if (
779
+ isPendingBlockInput(pendingBlock) &&
780
+ nowSec - pendingBlock.timeAddedSec > maxSecInCache &&
781
+ this.isWaitingOnParent(pendingBlock)
782
+ ) {
783
+ this.removeUnresolvedBlock(pendingBlock, DroppedItemReason.agedOut);
784
+ }
785
+ }
786
+ };
787
+
788
+ private isWaitingOnParent(pendingBlock: PendingBlockInput): boolean {
789
+ if (pendingBlock.status === PendingBlockInputStatus.processing) {
790
+ return false;
791
+ }
792
+ const {kind} = this.getMissingBlockDependency(pendingBlock.blockInput);
793
+ return kind === "parentBlock" || kind === "parentPayload";
794
+ }
795
+
796
+ /**
797
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
798
+ */
799
+ private removeUnresolvedBlock(pendingBlock: PendingBlockInput, reason: DroppedItemReason): void {
800
+ const rootHex = pendingBlock.blockInput.blockRootHex;
801
+ this.pendingBlocks.delete(rootHex);
802
+ this.chain.seenBlockInputCache.remove(rootHex);
803
+ this.metrics?.blockInputSync.removedBlocks.inc({reason});
804
+ this.logger.debug("Removed unresolved BlockInputSync block", {
805
+ slot: pendingBlock.blockInput.slot,
806
+ root: rootHex,
807
+ reason,
808
+ });
809
+ }
810
+
668
811
  /**
669
812
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
670
813
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -813,8 +956,19 @@ export class BlockInputSync {
813
956
  if (!hasConnectedPeers) {
814
957
  this.logger.debug("No connected peers, skipping unknown block download.");
815
958
  } else {
959
+ // Blocks and roots a pending block waits on are downloaded first, any gossip message with an unknown root adds
960
+ // another root, and they all share the per-peer request budget
961
+ const awaitedRoots = new Set<RootHex>();
962
+ for (const pendingBlock of this.pendingBlocks.values()) {
963
+ if (isPendingBlockInput(pendingBlock)) {
964
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
965
+ }
966
+ }
967
+ const isAwaited = (block: BlockInputSyncCacheItem): boolean =>
968
+ isPendingBlockInput(block) || awaitedRoots.has(block.rootHex);
969
+
816
970
  // Most of the time there is exactly 1 unknown block
817
- for (const block of unknowns) {
971
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
818
972
  this.downloadBlock(block).catch((e) => {
819
973
  this.logger.debug("Unexpected error - downloadBlock", {root: getBlockInputSyncCacheItemRootHex(block)}, e);
820
974
  });
@@ -897,6 +1051,31 @@ export class BlockInputSync {
897
1051
  }
898
1052
  }
899
1053
 
1054
+ private scheduleDownloadRetry(retryAtMs: number): void {
1055
+ if (this.downloadRetryAtMs !== undefined && this.downloadRetryAtMs <= retryAtMs) {
1056
+ return;
1057
+ }
1058
+
1059
+ this.clearDownloadRetryTimer();
1060
+ this.downloadRetryAtMs = retryAtMs;
1061
+ this.downloadRetryTimeout = setTimeout(
1062
+ () => {
1063
+ this.downloadRetryTimeout = undefined;
1064
+ this.downloadRetryAtMs = undefined;
1065
+ this.triggerUnknownBlockSearch();
1066
+ },
1067
+ Math.max(0, retryAtMs - Date.now())
1068
+ );
1069
+ }
1070
+
1071
+ private clearDownloadRetryTimer(): void {
1072
+ if (this.downloadRetryTimeout !== undefined) {
1073
+ clearTimeout(this.downloadRetryTimeout);
1074
+ this.downloadRetryTimeout = undefined;
1075
+ }
1076
+ this.downloadRetryAtMs = undefined;
1077
+ }
1078
+
900
1079
  /**
901
1080
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
902
1081
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -1018,6 +1197,10 @@ export class BlockInputSync {
1018
1197
  if (block.status !== PendingBlockInputStatus.pending) {
1019
1198
  return;
1020
1199
  }
1200
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1201
+ this.scheduleDownloadRetry(block.retryAtMs);
1202
+ return;
1203
+ }
1021
1204
 
1022
1205
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
1023
1206
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
@@ -1098,6 +1281,7 @@ export class BlockInputSync {
1098
1281
  const pendingBlock = this.pendingBlocks.get(rootHex);
1099
1282
  if (pendingBlock) {
1100
1283
  pendingBlock.status = PendingBlockInputStatus.pending;
1284
+ pendingBlock.retryAtMs = res.err.retryAt;
1101
1285
  }
1102
1286
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
1103
1287
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -1108,11 +1292,31 @@ export class BlockInputSync {
1108
1292
  return;
1109
1293
  }
1110
1294
 
1295
+ if (
1296
+ res.err instanceof DownloadByRootError &&
1297
+ res.err.type.code === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT
1298
+ ) {
1299
+ this.logger.debug("Downloaded block is before finalized slot", logCtx, res.err);
1300
+ this.removeAllDescendants(block, DroppedItemReason.belowFinalized);
1301
+ return;
1302
+ }
1303
+
1111
1304
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
1112
1305
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
1113
1306
  const pendingBlock = this.pendingBlocks.get(rootHex);
1114
- if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1307
+ // A partial download replaces the entry with a pending one that does not carry the failure count
1308
+ if (
1309
+ pendingBlock &&
1310
+ (pendingBlock.status === PendingBlockInputStatus.fetching ||
1311
+ pendingBlock.status === PendingBlockInputStatus.pending)
1312
+ ) {
1115
1313
  pendingBlock.status = PendingBlockInputStatus.pending;
1314
+ // Not retried on every search, any gossip message with an unknown root triggers one
1315
+ pendingBlock.failedDownloads = (block.failedDownloads ?? 0) + 1;
1316
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
1317
+ pendingBlock.retryAtMs =
1318
+ Date.now() + Math.min(DOWNLOAD_RETRY_BASE_MS * 2 ** (pendingBlock.failedDownloads - 1), slotDurationMs);
1319
+ this.scheduleDownloadRetry(pendingBlock.retryAtMs);
1116
1320
  }
1117
1321
  }
1118
1322
  }
@@ -1304,7 +1508,7 @@ export class BlockInputSync {
1304
1508
  const pendingPayloadByRoot: PendingPayloadRootHex = {
1305
1509
  status: PendingPayloadInputStatus.pending,
1306
1510
  rootHex,
1307
- slot: pendingPayload.envelope.message.payload.slotNumber,
1511
+ slot: payloadInput.slot,
1308
1512
  timeAddedSec: pendingPayload.timeAddedSec,
1309
1513
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1310
1514
  };
@@ -1670,6 +1874,27 @@ export class BlockInputSync {
1670
1874
  } else {
1671
1875
  excludedPeers.add(peerId);
1672
1876
  }
1877
+
1878
+ 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) {
1889
+ 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;
1896
+ }
1897
+ }
1673
1898
  } finally {
1674
1899
  this.peerBalancer.onRequestCompleted(peerId);
1675
1900
  }
@@ -1845,6 +2070,17 @@ export class BlockInputSync {
1845
2070
  if (e instanceof DownloadByRootError) {
1846
2071
  const errorCode = e.type.code;
1847
2072
  downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2073
+ if (errorCode === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
2074
+ throw e;
2075
+ }
2076
+ // Low as in range sync, not Fatal as peers may serve unverified copies of a root with a bad signature
2077
+ if (
2078
+ errorCode === DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT ||
2079
+ errorCode === DownloadByRootErrorCode.PROPOSAL_SIGNATURE_INVALID ||
2080
+ errorCode === DownloadByRootErrorCode.UNKNOWN_PROPOSER
2081
+ ) {
2082
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2083
+ }
1848
2084
  excludedPeers.add(peerId);
1849
2085
  } else if (e instanceof RequestError) {
1850
2086
  // should look into req_resp metrics in this case
@@ -2050,11 +2286,13 @@ export class UnknownBlockPeerBalancer {
2050
2286
  readonly peersMeta: Map<PeerIdStr, PeerSyncMeta>;
2051
2287
  readonly activeRequests: Map<PeerIdStr, number>;
2052
2288
  readonly rateLimitedUntilByPeer: Map<PeerIdStr, number>;
2289
+ readonly requestTimesByPeer: Map<PeerIdStr, number[]>;
2053
2290
 
2054
2291
  constructor() {
2055
2292
  this.peersMeta = new Map();
2056
2293
  this.activeRequests = new Map();
2057
2294
  this.rateLimitedUntilByPeer = new Map();
2295
+ this.requestTimesByPeer = new Map();
2058
2296
  }
2059
2297
 
2060
2298
  /** Trigger on each peer re-status */
@@ -2070,6 +2308,7 @@ export class UnknownBlockPeerBalancer {
2070
2308
  this.peersMeta.delete(peerId);
2071
2309
  this.activeRequests.delete(peerId);
2072
2310
  this.rateLimitedUntilByPeer.delete(peerId);
2311
+ this.requestTimesByPeer.delete(peerId);
2073
2312
  }
2074
2313
 
2075
2314
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
@@ -2077,6 +2316,7 @@ export class UnknownBlockPeerBalancer {
2077
2316
  this.peersMeta.clear();
2078
2317
  this.activeRequests.clear();
2079
2318
  this.rateLimitedUntilByPeer.clear();
2319
+ this.requestTimesByPeer.clear();
2080
2320
  }
2081
2321
 
2082
2322
  onRateLimited(peerId: PeerIdStr, rateLimitedUntilMs: number): void {
@@ -2143,7 +2383,7 @@ export class UnknownBlockPeerBalancer {
2143
2383
  );
2144
2384
 
2145
2385
  const bestPeerId = sortedEligiblePeers[0];
2146
- this.onRequest(bestPeerId);
2386
+ this.onRequest(bestPeerId, now);
2147
2387
  return this.peersMeta.get(bestPeerId) ?? null;
2148
2388
  }
2149
2389
 
@@ -2151,8 +2391,18 @@ export class UnknownBlockPeerBalancer {
2151
2391
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
2152
2392
  * make this public for testing
2153
2393
  */
2154
- onRequest(peerId: PeerIdStr): void {
2394
+ onRequest(peerId: PeerIdStr, now = Date.now()): void {
2155
2395
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
2396
+
2397
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter(
2398
+ (time) => now - time < REQUESTS_PER_PEER_WINDOW_MS
2399
+ );
2400
+ requestTimes.push(now);
2401
+ this.requestTimesByPeer.set(peerId, requestTimes);
2402
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
2403
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
2404
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2405
+ }
2156
2406
  }
2157
2407
 
2158
2408
  /**