@lodestar/beacon-node 1.52.0-dev.5745da1108 → 1.52.0-dev.643dd3c5bf

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 (130) hide show
  1. package/lib/api/impl/validator/index.d.ts.map +1 -1
  2. package/lib/api/impl/validator/index.js +2 -4
  3. package/lib/api/impl/validator/index.js.map +1 -1
  4. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  5. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  6. package/lib/chain/chain.d.ts.map +1 -1
  7. package/lib/chain/chain.js +9 -5
  8. package/lib/chain/chain.js.map +1 -1
  9. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  10. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  11. package/lib/chain/errors/executionPayloadBid.js +1 -0
  12. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  13. package/lib/chain/errors/executionPayloadEnvelope.d.ts +7 -0
  14. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  15. package/lib/chain/errors/executionPayloadEnvelope.js +1 -0
  16. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  17. package/lib/chain/prepareNextSlot.d.ts +45 -0
  18. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  19. package/lib/chain/prepareNextSlot.js +265 -69
  20. package/lib/chain/prepareNextSlot.js.map +1 -1
  21. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  22. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  23. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  24. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  25. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  26. package/lib/chain/validation/executionPayloadBid.js +17 -2
  27. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  28. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  29. package/lib/chain/validation/executionPayloadEnvelope.js +21 -5
  30. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  31. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  32. package/lib/chain/validation/voluntaryExit.js +39 -6
  33. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  34. package/lib/execution/engine/blockHash.d.ts +12 -0
  35. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  36. package/lib/execution/engine/blockHash.js +17 -0
  37. package/lib/execution/engine/blockHash.js.map +1 -0
  38. package/lib/execution/engine/mock.d.ts.map +1 -1
  39. package/lib/execution/engine/mock.js +6 -6
  40. package/lib/execution/engine/mock.js.map +1 -1
  41. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  42. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  43. package/lib/execution/engine/payloadIdCache.js +7 -2
  44. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  45. package/lib/metrics/metrics/beacon.d.ts +5 -0
  46. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  47. package/lib/metrics/metrics/beacon.js +5 -0
  48. package/lib/metrics/metrics/beacon.js.map +1 -1
  49. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  50. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  51. package/lib/metrics/metrics/lodestar.js +5 -0
  52. package/lib/metrics/metrics/lodestar.js.map +1 -1
  53. package/lib/network/core/events.d.ts +6 -2
  54. package/lib/network/core/events.d.ts.map +1 -1
  55. package/lib/network/core/events.js +9 -0
  56. package/lib/network/core/events.js.map +1 -1
  57. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  58. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  59. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  60. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  61. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  62. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  63. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  64. package/lib/sync/range/batch.d.ts +4 -0
  65. package/lib/sync/range/batch.d.ts.map +1 -1
  66. package/lib/sync/range/batch.js +12 -0
  67. package/lib/sync/range/batch.js.map +1 -1
  68. package/lib/sync/range/chain.d.ts +17 -2
  69. package/lib/sync/range/chain.d.ts.map +1 -1
  70. package/lib/sync/range/chain.js +52 -19
  71. package/lib/sync/range/chain.js.map +1 -1
  72. package/lib/sync/range/range.d.ts.map +1 -1
  73. package/lib/sync/range/range.js +1 -0
  74. package/lib/sync/range/range.js.map +1 -1
  75. package/lib/sync/range/utils/batches.d.ts +20 -4
  76. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  77. package/lib/sync/range/utils/batches.js +31 -13
  78. package/lib/sync/range/utils/batches.js.map +1 -1
  79. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  80. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  81. package/lib/sync/range/utils/peerBalancer.js +5 -2
  82. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  83. package/lib/sync/types.d.ts +2 -0
  84. package/lib/sync/types.d.ts.map +1 -1
  85. package/lib/sync/types.js.map +1 -1
  86. package/lib/sync/unknownBlock.d.ts.map +1 -1
  87. package/lib/sync/unknownBlock.js +60 -19
  88. package/lib/sync/unknownBlock.js.map +1 -1
  89. package/lib/sync/utils/downloadByRange.d.ts +8 -0
  90. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  91. package/lib/sync/utils/downloadByRange.js +43 -23
  92. package/lib/sync/utils/downloadByRange.js.map +1 -1
  93. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  94. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  95. package/lib/util/asyncIterableToEvents.js +76 -20
  96. package/lib/util/asyncIterableToEvents.js.map +1 -1
  97. package/lib/util/dataColumns.d.ts +1 -1
  98. package/lib/util/dataColumns.d.ts.map +1 -1
  99. package/lib/util/dataColumns.js +4 -1
  100. package/lib/util/dataColumns.js.map +1 -1
  101. package/package.json +17 -17
  102. package/src/api/impl/validator/index.ts +2 -4
  103. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  104. package/src/chain/chain.ts +9 -5
  105. package/src/chain/errors/executionPayloadBid.ts +6 -0
  106. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  107. package/src/chain/prepareNextSlot.ts +347 -89
  108. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  109. package/src/chain/validation/executionPayloadBid.ts +20 -2
  110. package/src/chain/validation/executionPayloadEnvelope.ts +28 -5
  111. package/src/chain/validation/voluntaryExit.ts +44 -6
  112. package/src/execution/engine/blockHash.ts +27 -0
  113. package/src/execution/engine/mock.ts +13 -8
  114. package/src/execution/engine/payloadIdCache.ts +12 -4
  115. package/src/metrics/metrics/beacon.ts +9 -0
  116. package/src/metrics/metrics/lodestar.ts +5 -0
  117. package/src/network/core/events.ts +12 -0
  118. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  119. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  120. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  121. package/src/sync/range/batch.ts +13 -0
  122. package/src/sync/range/chain.ts +64 -17
  123. package/src/sync/range/range.ts +1 -0
  124. package/src/sync/range/utils/batches.ts +38 -13
  125. package/src/sync/range/utils/peerBalancer.ts +4 -1
  126. package/src/sync/types.ts +2 -0
  127. package/src/sync/unknownBlock.ts +65 -21
  128. package/src/sync/utils/downloadByRange.ts +60 -26
  129. package/src/util/asyncIterableToEvents.ts +100 -21
  130. package/src/util/dataColumns.ts +4 -1
@@ -1,5 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
- import {Epoch, Root, Slot} from "@lodestar/types";
2
+ import {Epoch, Root, RootHex, Slot} from "@lodestar/types";
3
3
  import {ErrorAborted, LodestarError, Logger, prettyPrintIndices, toRootHex} from "@lodestar/utils";
4
4
  import {isBlockInputColumns} from "../../chain/blocks/blockInput/blockInput.js";
5
5
  import {BlockInputErrorCode} from "../../chain/blocks/blockInput/errors.js";
@@ -68,6 +68,8 @@ export type SyncChainFns = {
68
68
  onEnd: (err: Error | null, target: ChainTarget | null) => void;
69
69
  /** Deletes an array of BlockInputs from the BlockInputCache */
70
70
  pruneBlockInputs: (blockInputs: IBlockInput[]) => void;
71
+ /** Returns true if the block is known to fork choice */
72
+ hasBlock: (blockRoot: Root) => boolean;
71
73
  };
72
74
 
73
75
  /**
@@ -81,6 +83,15 @@ export type ChainTarget = {
81
83
 
82
84
  export class SyncChainStartError extends Error {}
83
85
 
86
+ export enum SyncChainErrorCode {
87
+ /** The terminal batch has 0 blocks but the target block is not known */
88
+ MISSING_TARGET_BLOCK = "SYNC_CHAIN_ERROR_MISSING_TARGET_BLOCK",
89
+ }
90
+
91
+ type SyncChainErrorType = {code: SyncChainErrorCode.MISSING_TARGET_BLOCK; targetSlot: Slot; targetRoot: RootHex};
92
+
93
+ export class SyncChainError extends LodestarError<SyncChainErrorType> {}
94
+
84
95
  export type SyncChainDebugState = {
85
96
  targetRoot: string | null;
86
97
  targetSlot: number | null;
@@ -136,6 +147,7 @@ export class SyncChain {
136
147
  private readonly reportPeer: SyncChainFns["reportPeer"];
137
148
  private readonly getConnectedPeerSyncMeta: SyncChainFns["getConnectedPeerSyncMeta"];
138
149
  private readonly pruneBlockInputs: SyncChainFns["pruneBlockInputs"];
150
+ private readonly hasBlock: SyncChainFns["hasBlock"];
139
151
 
140
152
  /** AsyncIterable that guarantees processChainSegment is run only at once at anytime */
141
153
  private readonly batchProcessor = new ItTrigger();
@@ -178,6 +190,7 @@ export class SyncChain {
178
190
  this.downloadByRange = fns.downloadByRange;
179
191
  this.reportPeer = fns.reportPeer;
180
192
  this.pruneBlockInputs = fns.pruneBlockInputs;
193
+ this.hasBlock = fns.hasBlock;
181
194
  this.getConnectedPeerSyncMeta = fns.getConnectedPeerSyncMeta;
182
195
  this.config = config;
183
196
  this.clock = clock;
@@ -335,6 +348,32 @@ export class SyncChain {
335
348
 
336
349
  // Returns true if SyncChain has processed all possible blocks with slot <= target.slot
337
350
  if (isSyncChainDone(toArr(this.batches), this.lastEpochWithProcessBlocks, this.target.slot)) {
351
+ // A 0-block terminal batch is only trusted once the target block is known, otherwise a peer returning no
352
+ // blocks for the last range ends the chain short of its target
353
+ const lastAwaitingValidation = toArr(this.batches).findLast(
354
+ (b) => b.state.status === BatchStatus.AwaitingValidation
355
+ );
356
+ if (
357
+ lastAwaitingValidation !== undefined &&
358
+ lastAwaitingValidation.getBlocks().length === 0 &&
359
+ !this.hasBlock(this.target.root)
360
+ ) {
361
+ this.logger.verbose("Terminal 0-block batch without target block", {
362
+ id: this.logId,
363
+ ...lastAwaitingValidation.getMetadata(),
364
+ });
365
+ // Not peer attributable: throws MAX_PROCESSING_ATTEMPTS after MAX_BATCH_PROCESSING_ATTEMPTS without
366
+ // reporting any peer
367
+ lastAwaitingValidation.validationError(
368
+ new SyncChainError({
369
+ code: SyncChainErrorCode.MISSING_TARGET_BLOCK,
370
+ targetSlot: this.target.slot,
371
+ targetRoot: toRootHex(this.target.root),
372
+ })
373
+ );
374
+ this.triggerBatchDownloader();
375
+ continue;
376
+ }
338
377
  break;
339
378
  }
340
379
 
@@ -509,9 +548,12 @@ export class SyncChain {
509
548
  // if last processed epoch is n, we don't want to request batches with epoch > n + MAX_LOOK_AHEAD_EPOCHS
510
549
  // we should have enough batches to process in the buffer: n + 1, ..., n + MAX_LOOK_AHEAD_EPOCHS
511
550
  // let's focus on redownloading these batches first because it may have to reach different peers to get enough sampled columns
551
+ // Note: Don't count batches in the AwaitingValidation state, 0-block batches never advance
552
+ // lastEpochWithProcessBlocks so more than MAX_LOOK_AHEAD_EPOCHS of them in a row would stall sync
553
+ const pendingBatches = batches.filter((batch) => batch.state.status !== BatchStatus.AwaitingValidation);
512
554
  if (
513
- batches.length > 0 &&
514
- Math.max(...batches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
555
+ pendingBatches.length > 0 &&
556
+ Math.max(...pendingBatches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
515
557
  ) {
516
558
  return null;
517
559
  }
@@ -576,6 +618,7 @@ export class SyncChain {
576
618
  }
577
619
  }
578
620
  switch (errCode) {
621
+ case DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS:
579
622
  case DownloadByRangeErrorCode.EXTRA_BLOCKS:
580
623
  case DownloadByRangeErrorCode.OUT_OF_ORDER_BLOCKS:
581
624
  case DownloadByRangeErrorCode.OUT_OF_RANGE_BLOCKS:
@@ -722,39 +765,43 @@ export class SyncChain {
722
765
  } else {
723
766
  this.logger.verbose("Batch process error", logCtx, res.err);
724
767
 
725
- const invalidatePreviousBatches = (): number => {
726
- let invalidatedCount = 0;
768
+ // advanceChain() drops every batch before the last batch with blocks, so the AwaitingValidation batches before
769
+ // `batch` are that batch followed by 0-block batches, see classifyProcessingFault(). With no batch with blocks
770
+ // yet, fall back to the first 0-block batch so a wrong 0-block answer at the start of the chain is retried
771
+ const awaitingValidationBefore = toArr(this.batches).filter(
772
+ (b) => b.startEpoch < batch.startEpoch && b.state.status === BatchStatus.AwaitingValidation
773
+ );
774
+ const parentBatch =
775
+ awaitingValidationBefore.findLast((b) => b.getBlocks().length > 0) ?? awaitingValidationBefore[0];
776
+ // The 0-block batches after `parentBatch` are invalidated with it: an AwaitingValidation batch must not follow a
777
+ // batch that is downloaded again, see validateBatchesStatus()
778
+ const invalidateFromParentBatch = (faultyParentBatch: Batch): void => {
727
779
  for (const pendingBatch of this.batches.values()) {
728
780
  if (
781
+ pendingBatch.startEpoch >= faultyParentBatch.startEpoch &&
729
782
  pendingBatch.startEpoch < batch.startEpoch &&
730
783
  pendingBatch.state.status === BatchStatus.AwaitingValidation
731
784
  ) {
732
785
  this.logger.verbose("Batch validation error", {id: this.logId, ...pendingBatch.getMetadata()});
733
786
  pendingBatch.validationError(res.err);
734
- invalidatedCount++;
735
787
  }
736
788
  }
737
- return invalidatedCount;
738
789
  };
739
790
 
740
- const prevBatch = this.batches.get(batch.startEpoch - EPOCHS_PER_BATCH);
741
- switch (classifyProcessingFault(res.err, batch, prevBatch)) {
791
+ const fault = classifyProcessingFault(res.err, batch, parentBatch);
792
+ switch (fault.kind) {
742
793
  case ProcessingFaultKind.CurrentBatch:
743
794
  batch.processingError(res.err);
744
795
  break;
745
796
 
746
- case ProcessingFaultKind.PreviousBatch:
747
- // If no previous batch was invalidated, it means the error is on this batch
748
- if (invalidatePreviousBatches() === 0) {
749
- batch.processingError(res.err);
750
- } else {
751
- batch.retainForReprocessing();
752
- }
797
+ case ProcessingFaultKind.ParentBatch:
798
+ invalidateFromParentBatch(fault.parentBatch);
799
+ batch.retainForReprocessing();
753
800
  break;
754
801
 
755
802
  case ProcessingFaultKind.Ambiguous:
756
803
  batch.processingError(res.err);
757
- invalidatePreviousBatches();
804
+ invalidateFromParentBatch(fault.parentBatch);
758
805
  break;
759
806
  }
760
807
  }
@@ -461,6 +461,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
461
461
  reportPeer: this.reportPeer,
462
462
  getConnectedPeerSyncMeta: this.getConnectedPeerSyncMeta,
463
463
  pruneBlockInputs: this.pruneBlockInputs,
464
+ hasBlock: (blockRoot) => this.chain.forkChoice.hasBlock(blockRoot),
464
465
  onEnd: this.onSyncChainEnd,
465
466
  },
466
467
  {
@@ -125,39 +125,64 @@ export function isSyncChainDone(batches: Batch[], lastEpochWithProcessBlocks: Ep
125
125
  export enum ProcessingFaultKind {
126
126
  /** This batch's own blocks are bad or incomplete, so redownload this batch. */
127
127
  CurrentBatch = "CurrentBatch",
128
- /** This batch is valid, but a previous batch did not deliver the parent. */
129
- PreviousBatch = "PreviousBatch",
130
- /** The fault could be in this batch or a previous batch, so hedge both ways. */
128
+ /** This batch is valid, but the parent batch did not deliver the parent. */
129
+ ParentBatch = "ParentBatch",
130
+ /** The fault could be in this batch or the parent batch, so hedge both ways. */
131
131
  Ambiguous = "Ambiguous",
132
132
  }
133
133
 
134
+ export type ProcessingFault =
135
+ | {kind: ProcessingFaultKind.CurrentBatch}
136
+ | {kind: ProcessingFaultKind.ParentBatch; parentBatch: Batch}
137
+ | {kind: ProcessingFaultKind.Ambiguous; parentBatch: Batch};
138
+
134
139
  /**
135
140
  * Classify a processChainSegment error for a batch so range sync only redownloads
136
141
  * the batch or batches that could actually be at fault.
137
142
  * Note that range sync is supposed to only handle linear chain, for forky condition we'll handle it via backward sync
138
143
  * in BlockInputSync or the upcoming/TODO beacon_blocks_by_head req/resp.
144
+ *
145
+ * `parentBatch` is the last batch with blocks before `batch`, it may be followed by 0-block batches. If no batch with
146
+ * blocks awaits validation, it is the first 0-block batch before `batch`.
147
+ * Epochs with 0 blocks usually happen on devnets, during periods of poor liveness when no proposer gets a block
148
+ * included for whole epochs. A wrong 0-block response only shows up as an unknown parent in `batch`, so with 0-block
149
+ * batches in between the fault is never pinned on `batch` alone: `parentBatch` and the 0-block batches after it are
150
+ * downloaded again.
139
151
  */
140
- export function classifyProcessingFault(err: Error, batch: Batch, prevBatch: Batch | undefined): ProcessingFaultKind {
152
+ export function classifyProcessingFault(err: Error, batch: Batch, parentBatch: Batch | undefined): ProcessingFault {
141
153
  if (!(err instanceof BlockError)) {
142
- return ProcessingFaultKind.CurrentBatch;
154
+ return {kind: ProcessingFaultKind.CurrentBatch};
143
155
  }
144
156
 
145
157
  const {code} = err.type;
146
158
  if (code !== BlockErrorCode.PARENT_BLOCK_UNKNOWN && code !== BlockErrorCode.PARENT_PAYLOAD_UNKNOWN) {
147
- return ProcessingFaultKind.CurrentBatch;
159
+ return {kind: ProcessingFaultKind.CurrentBatch};
160
+ }
161
+
162
+ if (parentBatch === undefined) {
163
+ return {kind: ProcessingFaultKind.CurrentBatch};
148
164
  }
149
165
 
150
166
  const firstErrorSlot = err.signedBlock.message.slot;
151
167
  if (firstErrorSlot === batch.startSlot) {
152
- // note that range sync is for linear chain, so this is clearly an issue of the previous batch
153
- return prevBatch === undefined ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.PreviousBatch;
168
+ // note that range sync is for linear chain, so this is clearly an issue of the parent batch
169
+ return {kind: ProcessingFaultKind.ParentBatch, parentBatch};
154
170
  }
155
171
 
156
- const prevTailSlot = batch.startSlot - 1;
157
- const prevHasFullTail =
172
+ // `parentBatch` can be followed by 0-block batches, so its tail is the end of its own range
173
+ const parentTailSlot = parentBatch.startSlot + parentBatch.count - 1;
174
+ const parentHasFullTail =
158
175
  code === BlockErrorCode.PARENT_PAYLOAD_UNKNOWN
159
- ? (prevBatch?.getPayloadEnvelopes()?.get(prevTailSlot)?.hasPayloadEnvelope() ?? false)
160
- : (prevBatch?.getBlocks().some((b) => b.slot === prevTailSlot) ?? false);
176
+ ? (parentBatch.getPayloadEnvelopes()?.get(parentTailSlot)?.hasPayloadEnvelope() ?? false)
177
+ : parentBatch.getBlocks().some((b) => b.slot === parentTailSlot);
161
178
 
162
- return prevHasFullTail ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.Ambiguous;
179
+ // With 0-block batches in between, it could be a wrong 0-block batch
180
+ const hasZeroBlockGap = parentTailSlot + 1 < batch.startSlot;
181
+
182
+ // Assumes the tail block / payload delivered by `parentBatch` is canonical. If it is orphaned, `parentBatch` is at
183
+ // fault: `batch` keeps failing until MAX_PROCESSING_ATTEMPTS and a new SyncChain is created.
184
+ if (parentHasFullTail && !hasZeroBlockGap) {
185
+ return {kind: ProcessingFaultKind.CurrentBatch};
186
+ }
187
+ return {kind: ProcessingFaultKind.Ambiguous, parentBatch};
163
188
  }
@@ -52,7 +52,7 @@ export class ChainPeersBalancer {
52
52
 
53
53
  /**
54
54
  * Return the most suitable peer to retry
55
- * Sort peers by (1) less active requests (2) most columns we need.
55
+ * Sort peers by (1) fewer failed attempts for this batch (2) less active requests (3) most columns we need.
56
56
  * Peers that failed this batch or already succeeded for the same request are excluded inside `filterPeers`.
57
57
  */
58
58
  bestPeerToRetryBatch(batch: Batch): PeerSyncMeta | undefined {
@@ -63,9 +63,12 @@ export class ChainPeersBalancer {
63
63
  // TODO(fulu): This is fulu specific and hinders our peer selection PreFulu
64
64
  const pendingDataColumns = columnsRequest?.columns ?? this.custodyConfig.sampledColumns;
65
65
  const eligiblePeers = this.filterPeers(batch, pendingDataColumns, false);
66
+ const triedPeerCounts = batch.getTriedPeerCounts();
66
67
 
67
68
  const sortedBestPeers = sortBy(
68
69
  eligiblePeers,
70
+ // prefer peers not tried for this batch yet
71
+ ({syncInfo}) => triedPeerCounts.get(syncInfo.peerId) ?? 0,
69
72
  ({syncInfo}) => this.activeRequestsByPeer.get(syncInfo.peerId) ?? 0, // prefer peers with least active req
70
73
  ({columns}) => -1 * columns // prefer peers with the most columns
71
74
  );
package/src/sync/types.ts CHANGED
@@ -172,6 +172,8 @@ export type PendingPayloadRootHex = {
172
172
  export type PendingPayloadEnvelope = {
173
173
  status: PendingPayloadInputStatus.waitingForBlock;
174
174
  envelope: SignedExecutionPayloadEnvelope;
175
+ /** Peer that served the envelope, undefined if it was already cached */
176
+ envelopePeerId?: string;
175
177
  timeAddedSec: number;
176
178
  peerIdStrings: Set<string>;
177
179
  };
@@ -1501,10 +1501,22 @@ export class BlockInputSync {
1501
1501
  return;
1502
1502
  }
1503
1503
  if (validationResult.err) {
1504
+ const err = validationResult.err;
1505
+ const {envelopePeerId} = pendingPayload;
1506
+ // Same penalties as for an envelope validated right after download in fetchPayloadInput
1507
+ if (
1508
+ envelopePeerId !== undefined &&
1509
+ err instanceof ExecutionPayloadEnvelopeError &&
1510
+ (pendingPayload.envelope.message.payload.slotNumber !== payloadInput.slot ||
1511
+ toRootHex(pendingPayload.envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1512
+ ) {
1513
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, err.type.code);
1514
+ }
1515
+
1504
1516
  this.logger.debug(
1505
1517
  "Pending payload envelope failed validation after block import, refetching by root",
1506
1518
  {slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex},
1507
- validationResult.err
1519
+ err
1508
1520
  );
1509
1521
 
1510
1522
  const pendingPayloadByRoot: PendingPayloadRootHex = {
@@ -1514,6 +1526,10 @@ export class BlockInputSync {
1514
1526
  timeAddedSec: pendingPayload.timeAddedSec,
1515
1527
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1516
1528
  };
1529
+ // Do not prefer the peer whose envelope just failed validation
1530
+ if (envelopePeerId !== undefined) {
1531
+ pendingPayloadByRoot.peerIdStrings.delete(envelopePeerId);
1532
+ }
1517
1533
  this.pendingPayloads.set(rootHex, pendingPayloadByRoot);
1518
1534
 
1519
1535
  if (this.network.getConnectedPeers().length > 0) {
@@ -1722,6 +1738,8 @@ export class BlockInputSync {
1722
1738
  ? cacheItem.payloadInput
1723
1739
  : await this.chain.seenPayloadEnvelopeInputCache.getOrReload(rootHex);
1724
1740
  let envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1741
+ // An envelope downloaded in an earlier attempt is validated with the peer of a later one
1742
+ let envelopePeerId: PeerIdStr | undefined;
1725
1743
 
1726
1744
  const fetchStartSec = Date.now() / 1000;
1727
1745
  if (typeof slot === "number") {
@@ -1769,6 +1787,7 @@ export class BlockInputSync {
1769
1787
  try {
1770
1788
  if (!envelope) {
1771
1789
  envelope = await this.fetchExecutionPayloadEnvelope(peerId, blockRoot, rootHex);
1790
+ envelopePeerId = peerId;
1772
1791
  cacheItem.peerIdStrings.add(peerId);
1773
1792
  const slotWasUnknown = typeof slot !== "number";
1774
1793
  slot = envelope.message.payload.slotNumber;
@@ -1792,6 +1811,7 @@ export class BlockInputSync {
1792
1811
  return {
1793
1812
  status: PendingPayloadInputStatus.waitingForBlock,
1794
1813
  envelope,
1814
+ envelopePeerId,
1795
1815
  timeAddedSec: cacheItem.timeAddedSec,
1796
1816
  peerIdStrings: cacheItem.peerIdStrings,
1797
1817
  };
@@ -1877,24 +1897,39 @@ export class BlockInputSync {
1877
1897
  excludedPeers.add(peerId);
1878
1898
  }
1879
1899
 
1900
+ // Honest peers serve the requested root and columns, and every path that stores payload columns verifies them
1901
+ if (e instanceof DownloadByRootError || e instanceof DataColumnSidecarValidationError) {
1902
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, e.type.code);
1903
+ }
1904
+
1880
1905
  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) {
1906
+ // Range sync stores an envelope after checking only its root, slot and block hash, so an honest peer may
1907
+ // serve one that fails the other checks. Compared directly since validation stops at the first failure.
1908
+ if (
1909
+ envelope !== undefined &&
1910
+ payloadInput &&
1911
+ (envelope.message.payload.slotNumber !== payloadInput.slot ||
1912
+ toRootHex(envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1913
+ ) {
1914
+ if (envelopePeerId !== undefined) {
1915
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, e.type.code);
1916
+ }
1917
+ envelope = payloadInput.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1918
+ } else {
1919
+ switch (e.type.code) {
1920
+ // Caused by local state, the downloaded envelope may still be valid
1921
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1922
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1923
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1924
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1925
+ // Every copy fails once the block is finalized
1926
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1927
+ break;
1928
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1929
+ default:
1891
1930
  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;
1931
+ break;
1932
+ }
1898
1933
  }
1899
1934
  }
1900
1935
  } finally {
@@ -1931,7 +1966,12 @@ export class BlockInputSync {
1931
1966
 
1932
1967
  const receivedRootHex = toRootHex(envelope.message.beaconBlockRoot);
1933
1968
  if (receivedRootHex !== rootHex) {
1934
- throw new Error(`Execution payload envelope root mismatch requested=${rootHex} received=${receivedRootHex}`);
1969
+ throw new DownloadByRootError({
1970
+ code: DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT,
1971
+ peer: prettyPrintPeerIdStr(peerIdStr),
1972
+ requestedBlockRoot: rootHex,
1973
+ receivedBlockRoot: receivedRootHex,
1974
+ });
1935
1975
  }
1936
1976
 
1937
1977
  return envelope;
@@ -1960,9 +2000,13 @@ export class BlockInputSync {
1960
2000
  const requestedColumnsSet = new Set(requestedColumns);
1961
2001
  const extraColumns = columnSidecars.filter((columnSidecar) => !requestedColumnsSet.has(columnSidecar.index));
1962
2002
  if (extraColumns.length > 0) {
1963
- throw new Error(
1964
- `Received unexpected payload data columns indices=${prettyPrintIndices(extraColumns.map((column) => column.index))}`
1965
- );
2003
+ throw new DownloadByRootError({
2004
+ code: DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED,
2005
+ peer: prettyPrintPeerIdStr(peerIdStr),
2006
+ slot: payloadInput.slot,
2007
+ blockRoot: payloadInput.blockRootHex,
2008
+ invalidIndices: prettyPrintIndices(extraColumns.map((column) => column.index)),
2009
+ });
1966
2010
  }
1967
2011
 
1968
2012
  // PayloadEnvelopeInput already carries the block slot, root, and commitments, so reuse the
@@ -485,6 +485,25 @@ export async function validateResponses({
485
485
  }
486
486
 
487
487
  if (!columnsRequest) {
488
+ // Same as the 0-block check below, for a post-Gloas batch outside the DA window where no columns are requested
489
+ const payloadEnvelopeCount = payloadEnvelopes?.length ?? 0;
490
+ if (
491
+ payloadEnvelopeCount > 0 &&
492
+ parentPayload === undefined &&
493
+ !validatedResponses.validatedBlocks?.length &&
494
+ !batchBlocks?.length
495
+ ) {
496
+ throw new DownloadByRangeError(
497
+ {
498
+ code: DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS,
499
+ ...requestsLogMeta({blocksRequest}),
500
+ columnSidecarCount: 0,
501
+ payloadEnvelopeCount,
502
+ },
503
+ "Envelopes returned without blocks in BeaconBlocksByRange response"
504
+ );
505
+ }
506
+
488
507
  // Only envelope and/or parent-by-root validation needed
489
508
  if (parentPayload !== undefined) {
490
509
  const parentValidated = await validateParentPayloadColumns(parentPayload, columnSidecars ?? [], peerDasMetrics);
@@ -507,14 +526,27 @@ export async function validateResponses({
507
526
  validatedResponses.validatedBlocks?.length ? validatedResponses.validatedBlocks : undefined
508
527
  );
509
528
 
529
+ // Epoch with 0 blocks: columns and envelopes only exist for a block, so data here means the peer withheld blocks or
530
+ // served junk. The parent payload is not requested either, Batch only does once it has blocks
510
531
  if (!blocksForDataValidation.length) {
511
- throw new DownloadByRangeError(
512
- {
513
- code: DownloadByRangeErrorCode.MISSING_BLOCKS_RESPONSE,
514
- ...requestsLogMeta({columnsRequest}),
515
- },
516
- "No blocks in data request slot range to validate data response against"
517
- );
532
+ const columnSidecarCount = columnSidecars?.length ?? 0;
533
+ const payloadEnvelopeCount = payloadEnvelopes?.length ?? 0;
534
+ if (columnSidecarCount > 0 || payloadEnvelopeCount > 0) {
535
+ throw new DownloadByRangeError(
536
+ {
537
+ code: DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS,
538
+ ...requestsLogMeta({blocksRequest}),
539
+ columnSidecarCount,
540
+ payloadEnvelopeCount,
541
+ },
542
+ "Columns or envelopes returned without blocks in BeaconBlocksByRange response"
543
+ );
544
+ }
545
+
546
+ return {
547
+ result: {responses: validatedResponses, payloadEnvelopes: needsEnvelopeValidation ? new Map() : null},
548
+ warnings,
549
+ };
518
550
  }
519
551
 
520
552
  if (!columnSidecars) {
@@ -606,26 +638,19 @@ export function validateBlockByRangeResponse(
606
638
  ): WarnResult<ValidatedBlock[], DownloadByRangeError> {
607
639
  const {startSlot, count} = blocksRequest;
608
640
 
609
- // An error was thrown here by @twoeths in #8150 but it breaks for epochs with 0 blocks during chain
610
- // liveness issues. See comment https://github.com/ChainSafe/lodestar/issues/8147#issuecomment-3246434697
611
- // There are instances where clients return no blocks though. Need to monitor this via the warns to see
612
- // if what the correct behavior should be
641
+ // A 0-block response is accepted as correct, epochs with 0 blocks happen on devnets with poor liveness.
642
+ // If it was wrong, the next batch fails with an unknown parent and SyncChain handles it,
643
+ // see classifyProcessingFault()
613
644
  if (!blocks.length) {
614
- throw new DownloadByRangeError({
615
- code: DownloadByRangeErrorCode.MISSING_BLOCKS_RESPONSE,
616
- ...requestsLogMeta({blocksRequest}),
617
- });
618
- // TODO: this was causing deadlock again. need to come back and fix this so that its possible to process through
619
- // an empty epoch for periods with poor liveness
620
- // return {
621
- // result: [],
622
- // warnings: [
623
- // new DownloadByRangeError({
624
- // code: DownloadByRangeErrorCode.MISSING_BLOCKS_RESPONSE,
625
- // ...requestsLogMeta({blocksRequest}),
626
- // }),
627
- // ],
628
- // };
645
+ return {
646
+ result: [],
647
+ warnings: [
648
+ new DownloadByRangeError({
649
+ code: DownloadByRangeErrorCode.MISSING_BLOCKS_RESPONSE,
650
+ ...requestsLogMeta({blocksRequest}),
651
+ }),
652
+ ],
653
+ };
629
654
  }
630
655
 
631
656
  if (blocks.length > count) {
@@ -995,6 +1020,8 @@ function requestsLogMeta({blocksRequest, columnsRequest}: DownloadByRangeRequest
995
1020
  export enum DownloadByRangeErrorCode {
996
1021
  MISSING_BLOCKS_RESPONSE = "DOWNLOAD_BY_RANGE_ERROR_MISSING_BLOCK_RESPONSE",
997
1022
  MISSING_COLUMNS_RESPONSE = "DOWNLOAD_BY_RANGE_ERROR_MISSING_COLUMNS_RESPONSE",
1023
+ /** Columns or envelopes were returned for a range with no blocks */
1024
+ DATA_WITHOUT_BLOCKS = "DOWNLOAD_BY_RANGE_ERROR_DATA_WITHOUT_BLOCKS",
998
1025
 
999
1026
  /** Error at the reqresp layer */
1000
1027
  REQ_RESP_ERROR = "DOWNLOAD_BY_RANGE_ERROR_REQ_RESP_ERROR",
@@ -1038,6 +1065,13 @@ export type DownloadByRangeErrorType =
1038
1065
  columnStartSlot?: number;
1039
1066
  columnCount?: number;
1040
1067
  }
1068
+ | {
1069
+ code: DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS;
1070
+ blockStartSlot?: number;
1071
+ blockCount?: number;
1072
+ columnSidecarCount: number;
1073
+ payloadEnvelopeCount: number;
1074
+ }
1041
1075
  | {
1042
1076
  code: DownloadByRangeErrorCode.OUT_OF_RANGE_BLOCKS;
1043
1077
  slot: number;