@lodestar/beacon-node 1.52.0-dev.20cca3c9f1 → 1.52.0-dev.263ed9ded6

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 (128) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +4 -3
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/beacon/pool/index.js +1 -1
  5. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  6. package/lib/api/impl/validator/index.d.ts.map +1 -1
  7. package/lib/api/impl/validator/index.js +72 -40
  8. package/lib/api/impl/validator/index.js.map +1 -1
  9. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  10. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  11. package/lib/chain/chain.d.ts +1 -1
  12. package/lib/chain/chain.d.ts.map +1 -1
  13. package/lib/chain/chain.js +9 -16
  14. package/lib/chain/chain.js.map +1 -1
  15. package/lib/chain/errors/executionPayloadBid.d.ts +5 -0
  16. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  17. package/lib/chain/errors/executionPayloadBid.js +1 -0
  18. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  19. package/lib/chain/produceBlock/produceBlockBody.d.ts +5 -2
  20. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  21. package/lib/chain/produceBlock/produceBlockBody.js +31 -49
  22. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  23. package/lib/chain/validation/attesterSlashing.d.ts.map +1 -1
  24. package/lib/chain/validation/attesterSlashing.js +4 -2
  25. package/lib/chain/validation/attesterSlashing.js.map +1 -1
  26. package/lib/chain/validation/executionPayloadBid.js +11 -1
  27. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  28. package/lib/chain/validation/payloadAttestationMessage.js +2 -2
  29. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  30. package/lib/chain/validation/proposerSlashing.js +4 -2
  31. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  32. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts +2 -2
  33. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts.map +1 -1
  34. package/lib/chain/validation/signatureSets/contributionAndProof.js +2 -2
  35. package/lib/chain/validation/signatureSets/contributionAndProof.js.map +1 -1
  36. package/lib/chain/validation/signatureSets/syncCommittee.d.ts +2 -2
  37. package/lib/chain/validation/signatureSets/syncCommittee.d.ts.map +1 -1
  38. package/lib/chain/validation/signatureSets/syncCommittee.js +2 -2
  39. package/lib/chain/validation/signatureSets/syncCommittee.js.map +1 -1
  40. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts +2 -2
  41. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts.map +1 -1
  42. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js +2 -2
  43. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js.map +1 -1
  44. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts +2 -2
  45. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts.map +1 -1
  46. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js +2 -2
  47. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js.map +1 -1
  48. package/lib/chain/validation/syncCommittee.d.ts +1 -1
  49. package/lib/chain/validation/syncCommittee.d.ts.map +1 -1
  50. package/lib/chain/validation/syncCommittee.js +5 -5
  51. package/lib/chain/validation/syncCommittee.js.map +1 -1
  52. package/lib/chain/validation/syncCommitteeContributionAndProof.js +3 -3
  53. package/lib/chain/validation/syncCommitteeContributionAndProof.js.map +1 -1
  54. package/lib/network/core/events.d.ts +6 -2
  55. package/lib/network/core/events.d.ts.map +1 -1
  56. package/lib/network/core/events.js +9 -0
  57. package/lib/network/core/events.js.map +1 -1
  58. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  59. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  60. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  61. package/lib/network/network.js +6 -6
  62. package/lib/network/network.js.map +1 -1
  63. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  64. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  65. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  66. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  67. package/lib/sync/range/batch.d.ts +4 -0
  68. package/lib/sync/range/batch.d.ts.map +1 -1
  69. package/lib/sync/range/batch.js +12 -0
  70. package/lib/sync/range/batch.js.map +1 -1
  71. package/lib/sync/range/chain.d.ts +17 -2
  72. package/lib/sync/range/chain.d.ts.map +1 -1
  73. package/lib/sync/range/chain.js +52 -19
  74. package/lib/sync/range/chain.js.map +1 -1
  75. package/lib/sync/range/range.d.ts.map +1 -1
  76. package/lib/sync/range/range.js +1 -0
  77. package/lib/sync/range/range.js.map +1 -1
  78. package/lib/sync/range/utils/batches.d.ts +20 -4
  79. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  80. package/lib/sync/range/utils/batches.js +31 -13
  81. package/lib/sync/range/utils/batches.js.map +1 -1
  82. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  83. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  84. package/lib/sync/range/utils/peerBalancer.js +5 -2
  85. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  86. package/lib/sync/utils/downloadByRange.d.ts +8 -0
  87. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  88. package/lib/sync/utils/downloadByRange.js +43 -23
  89. package/lib/sync/utils/downloadByRange.js.map +1 -1
  90. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  91. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  92. package/lib/util/asyncIterableToEvents.js +76 -20
  93. package/lib/util/asyncIterableToEvents.js.map +1 -1
  94. package/lib/util/dataColumns.d.ts +1 -1
  95. package/lib/util/dataColumns.d.ts.map +1 -1
  96. package/lib/util/dataColumns.js +4 -1
  97. package/lib/util/dataColumns.js.map +1 -1
  98. package/package.json +16 -16
  99. package/src/api/impl/beacon/blocks/index.ts +4 -3
  100. package/src/api/impl/beacon/pool/index.ts +1 -1
  101. package/src/api/impl/validator/index.ts +105 -57
  102. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  103. package/src/chain/chain.ts +8 -36
  104. package/src/chain/errors/executionPayloadBid.ts +6 -0
  105. package/src/chain/produceBlock/produceBlockBody.ts +44 -64
  106. package/src/chain/validation/attesterSlashing.ts +4 -2
  107. package/src/chain/validation/executionPayloadBid.ts +15 -6
  108. package/src/chain/validation/payloadAttestationMessage.ts +2 -2
  109. package/src/chain/validation/proposerSlashing.ts +4 -2
  110. package/src/chain/validation/signatureSets/contributionAndProof.ts +4 -6
  111. package/src/chain/validation/signatureSets/syncCommittee.ts +2 -3
  112. package/src/chain/validation/signatureSets/syncCommitteeContribution.ts +2 -3
  113. package/src/chain/validation/signatureSets/syncCommitteeSelectionProof.ts +2 -3
  114. package/src/chain/validation/syncCommittee.ts +3 -5
  115. package/src/chain/validation/syncCommitteeContributionAndProof.ts +3 -3
  116. package/src/network/core/events.ts +12 -0
  117. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  118. package/src/network/network.ts +6 -6
  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/utils/downloadByRange.ts +60 -26
  127. package/src/util/asyncIterableToEvents.ts +100 -21
  128. 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
  );
@@ -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;
@@ -10,6 +10,11 @@ export type RequestCancelEvent = {
10
10
  id: number;
11
11
  };
12
12
 
13
+ export type ResponsePullEvent = {
14
+ id: number;
15
+ count: number;
16
+ };
17
+
13
18
  export enum IteratorEventType {
14
19
  next = "iterator.next",
15
20
  done = "iterator.done",
@@ -25,11 +30,22 @@ export type AsyncIterableEventBus<Args, Item> = {
25
30
  emitRequest(data: RequestEvent<Args>): void;
26
31
  emitRequestCancel(data: RequestCancelEvent): void;
27
32
  emitResponse(data: IteratorEvent<Item>): void;
33
+ emitResponsePull(data: ResponsePullEvent): void;
28
34
  onRequest(handler: (data: RequestEvent<Args>) => void): void;
29
35
  onRequestCancel(handler: (data: RequestCancelEvent) => void): void;
30
36
  onResponse(handler: (data: IteratorEvent<Item>) => void): void;
37
+ onResponsePull(handler: (data: ResponsePullEvent) => void): void;
31
38
  };
32
39
 
40
+ /**
41
+ * Credit window: the consumer grants this many items up front and refunds one per item it pulls, so the
42
+ * producer runs at most `window` (plus one in-flight) items ahead regardless of read speed. Bounds
43
+ * consumer-side buffering on the serving bridge. The requester bridge passes Infinity to stay eager: we
44
+ * buffer our own responses into an array anyway, and pacing the worker there only risks the libp2p read
45
+ * buffer overflowing. Must be >= 1.
46
+ */
47
+ export const RESP_BRIDGE_WINDOW = 2;
48
+
33
49
  type PendingItem<T> = {
34
50
  items: LinkedList<T>;
35
51
  done: boolean;
@@ -44,8 +60,15 @@ export class AsyncIterableBridgeCaller<Args, Item> {
44
60
  private readonly pending = new Map<number, PendingItem<Item>>();
45
61
 
46
62
  constructor(
47
- private readonly events: Pick<AsyncIterableEventBus<Args, Item>, "onResponse" | "emitRequest" | "emitRequestCancel">
63
+ private readonly events: Pick<
64
+ AsyncIterableEventBus<Args, Item>,
65
+ "onResponse" | "emitRequest" | "emitRequestCancel" | "emitResponsePull"
66
+ >,
67
+ private readonly window = RESP_BRIDGE_WINDOW
48
68
  ) {
69
+ if (window < 1) {
70
+ throw new Error(`AsyncIterableBridgeCaller window must be >= 1, got ${window}`);
71
+ }
49
72
  events.onResponse(this.onResponse.bind(this));
50
73
  }
51
74
 
@@ -71,12 +94,18 @@ export class AsyncIterableBridgeCaller<Args, Item> {
71
94
  callArgs,
72
95
  id,
73
96
  });
97
+ // Grant the initial window; next() refunds one credit per consumed item. An Infinity window
98
+ // grants unbounded credit up front so the producer never waits (requester bridge, see above).
99
+ self.events.emitResponsePull({id, count: self.window});
74
100
 
75
101
  return {
76
102
  async next() {
77
103
  while (true) {
78
104
  const item = req.items.shift();
79
105
  if (item !== null) {
106
+ if (self.window !== Infinity) {
107
+ self.events.emitResponsePull({id, count: 1});
108
+ }
80
109
  return {value: item, done: false};
81
110
  }
82
111
 
@@ -142,29 +171,52 @@ export class AsyncIterableBridgeCaller<Args, Item> {
142
171
  }
143
172
  }
144
173
 
174
+ type HandlerState<Item> = {
175
+ iterator: AsyncIterator<Item>;
176
+ credit: number;
177
+ cancelled: boolean;
178
+ onCredit: null | (() => void);
179
+ };
180
+
145
181
  export class AsyncIterableBridgeHandler<Args, Item> {
146
- private readonly iterators = new Map<number, AsyncIterator<Item>>();
182
+ private readonly states = new Map<number, HandlerState<Item>>();
147
183
 
148
184
  constructor(
149
- private readonly events: Pick<AsyncIterableEventBus<Args, Item>, "onRequest" | "onRequestCancel" | "emitResponse">,
185
+ private readonly events: Pick<
186
+ AsyncIterableEventBus<Args, Item>,
187
+ "onRequest" | "onRequestCancel" | "emitResponse" | "onResponsePull"
188
+ >,
150
189
  private readonly handler: (args: Args) => AsyncIterable<Item>
151
190
  ) {
152
191
  events.onRequest(this.onRequest.bind(this));
153
192
  events.onRequestCancel(this.onRequestCancel.bind(this));
193
+ events.onResponsePull(this.onResponsePull.bind(this));
154
194
  }
155
195
 
156
196
  get iteratingCount(): number {
157
- return this.iterators.size;
197
+ return this.states.size;
158
198
  }
159
199
 
160
200
  private async onRequest(data: RequestEvent<Args>): Promise<void> {
201
+ let state: HandlerState<Item> | undefined;
161
202
  try {
162
- const iterator = this.handler(data.callArgs)[Symbol.asyncIterator]();
163
- this.iterators.set(data.id, iterator);
203
+ state = {
204
+ iterator: this.handler(data.callArgs)[Symbol.asyncIterator](),
205
+ credit: 0,
206
+ cancelled: false,
207
+ onCredit: null,
208
+ };
209
+ this.states.set(data.id, state);
164
210
 
165
211
  while (true) {
166
- const result = await iterator.next();
167
- if (result.done) {
212
+ await this.waitForCredit(state);
213
+ if (state.cancelled) {
214
+ break;
215
+ }
216
+ state.credit--;
217
+
218
+ const result = await state.iterator.next();
219
+ if (result.done || state.cancelled) {
168
220
  break;
169
221
  }
170
222
 
@@ -175,29 +227,56 @@ export class AsyncIterableBridgeHandler<Args, Item> {
175
227
  });
176
228
  }
177
229
 
178
- this.events.emitResponse({
179
- type: IteratorEventType.done,
180
- id: data.id,
181
- });
230
+ if (!state.cancelled) {
231
+ this.events.emitResponse({
232
+ type: IteratorEventType.done,
233
+ id: data.id,
234
+ });
235
+ }
182
236
  } catch (e) {
183
- this.events.emitResponse({
184
- type: IteratorEventType.error,
185
- id: data.id,
186
- error: toThreadBoundaryError(e as Error),
187
- });
237
+ if (!state?.cancelled) {
238
+ this.events.emitResponse({
239
+ type: IteratorEventType.error,
240
+ id: data.id,
241
+ error: toThreadBoundaryError(e as Error),
242
+ });
243
+ }
188
244
  } finally {
189
- this.iterators.delete(data.id);
245
+ this.states.delete(data.id);
246
+ }
247
+ }
248
+
249
+ private waitForCredit(state: HandlerState<Item>): Promise<void> {
250
+ if (state.credit > 0 || state.cancelled) {
251
+ return Promise.resolve();
252
+ }
253
+ return new Promise<void>((resolve) => {
254
+ state.onCredit = resolve;
255
+ });
256
+ }
257
+
258
+ private onResponsePull(data: ResponsePullEvent): void {
259
+ const state = this.states.get(data.id);
260
+ if (!state) {
261
+ return;
190
262
  }
263
+ state.credit += data.count;
264
+ state.onCredit?.();
265
+ state.onCredit = null;
191
266
  }
192
267
 
193
268
  private onRequestCancel(data: RequestCancelEvent): void {
194
- const iterator = this.iterators.get(data.id);
195
- if (!iterator?.return) {
269
+ const state = this.states.get(data.id);
270
+ if (!state) {
196
271
  return;
197
272
  }
273
+ // Unblock the loop if it is parked on credit so it can observe the cancel and stop
274
+ state.cancelled = true;
275
+ state.onCredit?.();
276
+ state.onCredit = null;
198
277
 
199
278
  // An async generator queues return() behind the next() that is in flight, so at most one more
200
279
  // item is produced before its finally blocks run. Any error surfaces through that next() call.
201
- void iterator.return().catch(() => {});
280
+ void state.iterator.return?.().catch(() => {});
202
281
  }
203
282
  }
@@ -288,7 +288,7 @@ export function getBlobKzgCommitments(
288
288
  * each blob in the block, assemble the sidecars which can be distributed to peers.
289
289
  *
290
290
  * SPEC FUNCTION
291
- * https://github.com/ethereum/consensus-specs/blob/v1.6.0-alpha.4/specs/fulu/validator.md#get_data_column_sidecars
291
+ * https://github.com/ethereum/consensus-specs/blob/v1.7.0-beta.5/specs/fulu/validator.md#get_data_column_sidecars
292
292
  */
293
293
  export function getFuluDataColumnSidecars(
294
294
  signedBlockHeader: SignedBeaconBlockHeader,
@@ -299,6 +299,9 @@ export function getFuluDataColumnSidecars(
299
299
  if (cellsAndKzgProofs.length !== kzgCommitments.length) {
300
300
  throw Error("Invalid cellsAndKzgProofs length for getDataColumnSidecars");
301
301
  }
302
+ if (kzgCommitments.length === 0) {
303
+ return [];
304
+ }
302
305
 
303
306
  const sidecars: fulu.DataColumnSidecar[] = [];
304
307
  for (let columnIndex = 0; columnIndex < NUMBER_OF_COLUMNS; columnIndex++) {