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

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.
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "bugs": {
12
12
  "url": "https://github.com/ChainSafe/lodestar/issues"
13
13
  },
14
- "version": "1.52.0-dev.dad8e3af98",
14
+ "version": "1.52.0-dev.e60753e276",
15
15
  "type": "module",
16
16
  "exports": {
17
17
  ".": {
@@ -104,7 +104,7 @@
104
104
  "@chainsafe/discv5": "^12.0.2",
105
105
  "@chainsafe/enr": "^6.0.2",
106
106
  "@chainsafe/libp2p-noise": "^17.0.0",
107
- "@chainsafe/libp2p-quic": "^2.1.5",
107
+ "@chainsafe/libp2p-quic": "^2.1.6",
108
108
  "@chainsafe/persistent-merkle-tree": "^1.3.1",
109
109
  "@chainsafe/prometheus-gc-stats": "^1.0.0",
110
110
  "@chainsafe/snappy-wasm": "^0.5.2",
@@ -116,28 +116,28 @@
116
116
  "@fastify/swagger": "^9.0.0",
117
117
  "@fastify/swagger-ui": "^5.0.1",
118
118
  "@libp2p/bootstrap": "^12.0.34",
119
- "@libp2p/crypto": "^5.1.25",
120
- "@libp2p/gossipsub": "^17.1.4",
121
- "@libp2p/identify": "^4.1.16",
119
+ "@libp2p/crypto": "^5.2.0",
120
+ "@libp2p/gossipsub": "^17.2.2",
121
+ "@libp2p/identify": "^4.1.19",
122
122
  "@libp2p/interface": "^3.4.0",
123
123
  "@libp2p/mdns": "^12.0.34",
124
124
  "@libp2p/mplex": "^12.0.34",
125
- "@libp2p/peer-id": "^6.0.17",
125
+ "@libp2p/peer-id": "^6.0.18",
126
126
  "@libp2p/prometheus-metrics": "^5.0.31",
127
127
  "@libp2p/tcp": "^11.0.30",
128
- "@libp2p/utils": "^7.4.3",
129
- "@lodestar/api": "^1.52.0-dev.dad8e3af98",
130
- "@lodestar/config": "^1.52.0-dev.dad8e3af98",
131
- "@lodestar/db": "^1.52.0-dev.dad8e3af98",
132
- "@lodestar/fork-choice": "^1.52.0-dev.dad8e3af98",
133
- "@lodestar/logger": "^1.52.0-dev.dad8e3af98",
134
- "@lodestar/native": "^1.52.0-dev.dad8e3af98",
135
- "@lodestar/params": "^1.52.0-dev.dad8e3af98",
136
- "@lodestar/reqresp": "^1.52.0-dev.dad8e3af98",
137
- "@lodestar/state-transition": "^1.52.0-dev.dad8e3af98",
138
- "@lodestar/types": "^1.52.0-dev.dad8e3af98",
139
- "@lodestar/utils": "^1.52.0-dev.dad8e3af98",
140
- "@lodestar/validator": "^1.52.0-dev.dad8e3af98",
128
+ "@libp2p/utils": "^7.4.6",
129
+ "@lodestar/api": "^1.52.0-dev.e60753e276",
130
+ "@lodestar/config": "^1.52.0-dev.e60753e276",
131
+ "@lodestar/db": "^1.52.0-dev.e60753e276",
132
+ "@lodestar/fork-choice": "^1.52.0-dev.e60753e276",
133
+ "@lodestar/logger": "^1.52.0-dev.e60753e276",
134
+ "@lodestar/native": "^1.52.0-dev.e60753e276",
135
+ "@lodestar/params": "^1.52.0-dev.e60753e276",
136
+ "@lodestar/reqresp": "^1.52.0-dev.e60753e276",
137
+ "@lodestar/state-transition": "^1.52.0-dev.e60753e276",
138
+ "@lodestar/types": "^1.52.0-dev.e60753e276",
139
+ "@lodestar/utils": "^1.52.0-dev.e60753e276",
140
+ "@lodestar/validator": "^1.52.0-dev.e60753e276",
141
141
  "@multiformats/multiaddr": "^13.0.1",
142
142
  "datastore-core": "^12.0.1",
143
143
  "datastore-level": "^13.0.1",
@@ -145,7 +145,7 @@
145
145
  "fastify": "^5.8.1",
146
146
  "interface-datastore": "^10.0.1",
147
147
  "jwt-simple": "0.5.6",
148
- "libp2p": "3.4.0",
148
+ "libp2p": "3.5.2",
149
149
  "multiformats": "^13.4.2",
150
150
  "prom-client": "^15.1.0",
151
151
  "qs": "^6.14.2",
@@ -157,10 +157,10 @@
157
157
  },
158
158
  "devDependencies": {
159
159
  "@ethereumjs/rlp": "^4.0.1",
160
- "@libp2p/interface-internal": "^3.2.0",
161
- "@libp2p/logger": "^6.2.15",
162
- "@lodestar/spec-test-util": "^1.52.0-dev.dad8e3af98",
163
- "@lodestar/test-utils": "^1.52.0-dev.dad8e3af98",
160
+ "@libp2p/interface-internal": "^3.2.3",
161
+ "@libp2p/logger": "^6.2.16",
162
+ "@lodestar/spec-test-util": "^1.52.0-dev.e60753e276",
163
+ "@lodestar/test-utils": "^1.52.0-dev.e60753e276",
164
164
  "@types/js-yaml": "^4.0.5",
165
165
  "@types/qs": "^6.9.7",
166
166
  "@types/tmp": "^0.2.3",
@@ -174,5 +174,5 @@
174
174
  "beacon",
175
175
  "blockchain"
176
176
  ],
177
- "gitHead": "3839b605a06b630f1c8e23b3f68a9091e178416e"
177
+ "gitHead": "8ec8339395289208a8990acb658a078631b89f73"
178
178
  }
@@ -50,6 +50,15 @@ export async function getHistoricalState(
50
50
  const transitionTimer = metrics?.stateTransitionTime.startTimer();
51
51
  let blockCount = 0;
52
52
  for await (const block of db.blockArchive.valuesStream({gt: state.slot, lte: slot})) {
53
+ // Pruned history keeps the genesis state but not the blocks after it, without this check the
54
+ // first block would only be rejected after processing every slot in between
55
+ if (
56
+ blockCount === 0 &&
57
+ !byteArrayEquals(block.message.parentRoot, state.computeAnchorCheckpoint().checkpoint.root)
58
+ ) {
59
+ metrics?.regenErrorCount.inc({reason: RegenErrorType.blockProcessing});
60
+ throw Error(`Archived blocks do not extend nearest state slot=${state.slot} blockSlot=${block.message.slot}`);
61
+ }
53
62
  try {
54
63
  state = state.stateTransition(
55
64
  {block},
@@ -1,4 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
+ import {GENESIS_SLOT} from "@lodestar/params";
2
3
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
3
4
  import {Epoch, Slot} from "@lodestar/types";
4
5
  import {Logger, prettyPrintIndices} from "@lodestar/utils";
@@ -13,6 +14,9 @@ import {Metrics} from "../../../metrics/index.js";
13
14
  */
14
15
  export const MAX_PRUNE_BLOCK_SLOTS_PER_RUN = 4096;
15
16
 
17
+ // Genesis is kept so the block and state stay available via the API, e.g. for checkpoint providers
18
+ const FIRST_PRUNABLE_SLOT = GENESIS_SLOT + 1;
19
+
16
20
  export async function pruneHistory(
17
21
  config: ChainForkConfig,
18
22
  db: IBeaconDb,
@@ -30,11 +34,12 @@ export async function pruneHistory(
30
34
  // ensure that during (extremely lol) long periods of non-finality we don't delete unfinalized epoch data
31
35
  finalizedEpoch
32
36
  );
33
- const firstBlockSlot = (await db.blockArchive.firstKey()) ?? 0;
37
+ const [firstBlockSlot = FIRST_PRUNABLE_SLOT] = await db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, limit: 1});
34
38
  const blockCutoffSlot = Math.min(computeStartSlotAtEpoch(blockCutoffEpoch), firstBlockSlot + maxBlockSlots);
35
39
  // The latest archived state is the anchor on restart and can trail finalization by a few epochs
36
40
  const lastArchivedStateSlot = (await db.stateArchive.lastKey()) ?? 0;
37
41
  const stateCutoffSlot = Math.min(computeStartSlotAtEpoch(finalizedEpoch), lastArchivedStateSlot);
42
+ const stateStartSlot = Math.max(statePruneFromSlot, FIRST_PRUNABLE_SLOT);
38
43
 
39
44
  logger.debug("Preparing to prune history", {
40
45
  currentEpoch,
@@ -46,9 +51,9 @@ export async function pruneHistory(
46
51
 
47
52
  const step0 = metrics?.pruneHistory.fetchKeys.startTimer();
48
53
  const [blocks, envelopes, states] = await Promise.all([
49
- db.blockArchive.keys({gte: 0, lt: blockCutoffSlot}),
50
- db.executionPayloadEnvelopeArchive.keys({gte: 0, lt: blockCutoffSlot}),
51
- stateCutoffSlot > statePruneFromSlot ? db.stateArchive.keys({gte: statePruneFromSlot, lt: stateCutoffSlot}) : [],
54
+ db.blockArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
55
+ db.executionPayloadEnvelopeArchive.keys({gte: FIRST_PRUNABLE_SLOT, lt: blockCutoffSlot}),
56
+ stateCutoffSlot > stateStartSlot ? db.stateArchive.keys({gte: stateStartSlot, lt: stateCutoffSlot}) : [],
52
57
  ]);
53
58
  step0?.();
54
59
 
@@ -8,6 +8,7 @@ import {
8
8
  ForkPostGloas,
9
9
  ForkPreGloas,
10
10
  ForkSeq,
11
+ GENESIS_EPOCH,
11
12
  MIN_SYNC_COMMITTEE_PARTICIPANTS,
12
13
  SLOTS_PER_EPOCH,
13
14
  SYNC_COMMITTEE_SIZE,
@@ -16,8 +17,6 @@ import {
16
17
  } from "@lodestar/params";
17
18
  import {
18
19
  type IBeaconStateViewAltair,
19
- computeStartSlotAtEpoch,
20
- computeSyncPeriodAtEpoch,
21
20
  computeSyncPeriodAtSlot,
22
21
  executionPayloadToPayloadHeader,
23
22
  } from "@lodestar/state-transition";
@@ -44,8 +43,7 @@ import {
44
43
  phase0,
45
44
  ssz,
46
45
  } from "@lodestar/types";
47
- import {Logger, MapDef, byteArrayEquals, pruneSetToMax, toRootHex} from "@lodestar/utils";
48
- import {ZERO_HASH} from "../../constants/index.js";
46
+ import {Logger, MapDef, pruneSetToMax, toRootHex} from "@lodestar/utils";
49
47
  import {IBeaconDb} from "../../db/index.js";
50
48
  import {NUM_WITNESS, NUM_WITNESS_ELECTRA} from "../../db/repositories/lightclientSyncCommitteeWitness.js";
51
49
  import {Metrics} from "../../metrics/index.js";
@@ -72,16 +70,9 @@ export type SyncAttestedData = {
72
70
  attestedHeader: LightClientHeader;
73
71
  /** Precomputed root to prevent re-hashing */
74
72
  blockRoot: Uint8Array;
75
- } & (
76
- | {
77
- isFinalized: true;
78
- finalityBranch: Uint8Array[];
79
- finalizedCheckpoint: phase0.Checkpoint;
80
- }
81
- | {
82
- isFinalized: false;
83
- }
84
- );
73
+ finalizedCheckpoint: phase0.Checkpoint;
74
+ finalityBranch: Uint8Array[];
75
+ };
85
76
 
86
77
  type LightClientServerModules = {
87
78
  config: ChainForkConfig;
@@ -435,33 +426,14 @@ export class LightClientServer {
435
426
  // Store header in case it is referenced latter by a future finalized checkpoint
436
427
  await this.db.checkpointHeader.put(blockRoot, header);
437
428
 
438
- // Store finalized checkpoint data
439
- const finalizedCheckpoint = postState.finalizedCheckpoint;
440
- const finalizedCheckpointPeriod = computeSyncPeriodAtEpoch(finalizedCheckpoint.epoch);
441
- const isFinalized =
442
- finalizedCheckpointPeriod === period &&
443
- // Consider the edge case of genesis: Genesis state's finalizedCheckpoint is zero'ed.
444
- // If finalizedCheckpoint is zeroed, consider not finalized (ignore) since there won't exist a
445
- // finalized header for that root
446
- finalizedCheckpoint.epoch !== 0 &&
447
- !byteArrayEquals(finalizedCheckpoint.root, ZERO_HASH);
448
-
449
- this.prevHeadData.set(
450
- blockRootHex,
451
- isFinalized
452
- ? {
453
- isFinalized: true,
454
- attestedHeader: header,
455
- blockRoot,
456
- finalityBranch: postState.getFinalizedRootProof(),
457
- finalizedCheckpoint,
458
- }
459
- : {
460
- isFinalized: false,
461
- attestedHeader: header,
462
- blockRoot,
463
- }
464
- );
429
+ // Store finalized checkpoint data. The finality branch only depends on the post state, so it is
430
+ // collected for every block; see `buildUpdate` for the cases in which it is served.
431
+ this.prevHeadData.set(blockRootHex, {
432
+ attestedHeader: header,
433
+ blockRoot,
434
+ finalizedCheckpoint: postState.finalizedCheckpoint,
435
+ finalityBranch: postState.getFinalizedRootProof(),
436
+ });
465
437
 
466
438
  pruneSetToMax(this.prevHeadData, MAX_PREV_HEAD_DATA);
467
439
  }
@@ -505,7 +477,7 @@ export class LightClientServer {
505
477
  return;
506
478
  }
507
479
 
508
- const {attestedHeader, isFinalized} = attestedData;
480
+ const {attestedHeader} = attestedData;
509
481
  const attestedPeriod = computeSyncPeriodAtSlot(attestedHeader.beacon.slot);
510
482
  if (syncPeriod !== attestedPeriod) {
511
483
  this.logger.debug("attested data period different than signature period", {syncPeriod, attestedPeriod});
@@ -555,41 +527,36 @@ export class LightClientServer {
555
527
  this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_head_update"});
556
528
  }
557
529
 
558
- if (isFinalized) {
559
- const finalizedCheckpointRoot = attestedData.finalizedCheckpoint.root;
560
- let finalizedHeader = await this.getFinalizedHeader(finalizedCheckpointRoot);
561
-
562
- if (
563
- finalizedHeader &&
564
- (!this.finalized ||
565
- finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
566
- syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
567
- ) {
568
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
569
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
570
- }
571
- this.finalized = {
572
- attestedHeader,
573
- finalizedHeader,
574
- syncAggregate,
575
- finalityBranch: attestedData.finalityBranch,
576
- signatureSlot,
577
- };
578
- this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
579
-
580
- if (!isStaleLightClientUpdate) {
581
- // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
582
- this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
583
- version: attestedFork,
584
- data: this.finalized,
585
- });
586
- }
530
+ const builtUpdate = await this.buildUpdate(attestedData, syncAggregate, signatureSlot);
531
+ if (
532
+ builtUpdate?.hasFinality &&
533
+ (!this.finalized ||
534
+ builtUpdate.update.finalizedHeader.beacon.slot > this.finalized.finalizedHeader.beacon.slot ||
535
+ syncAggregateParticipation > sumBits(this.finalized.syncAggregate.syncCommitteeBits))
536
+ ) {
537
+ this.finalized = {
538
+ attestedHeader,
539
+ finalizedHeader: builtUpdate.update.finalizedHeader,
540
+ syncAggregate,
541
+ finalityBranch: builtUpdate.update.finalityBranch,
542
+ signatureSlot,
543
+ };
544
+ this.metrics?.lightclientServer.onSyncAggregate.inc({event: "update_latest_finalized_update"});
545
+
546
+ if (!isStaleLightClientUpdate) {
547
+ // Note: Ignores gossip rule to always emit finality_update with higher finalized_header.slot, for simplicity
548
+ this.emitter.emit(routes.events.EventType.lightClientFinalityUpdate, {
549
+ version: attestedFork,
550
+ data: this.finalized,
551
+ });
587
552
  }
588
553
  }
589
554
 
590
555
  // Check if this update is better, otherwise ignore
591
556
  try {
592
- await this.maybeStoreNewBestUpdate(syncPeriod, syncAggregate, signatureSlot, attestedData);
557
+ if (builtUpdate) {
558
+ await this.maybeStoreNewBestUpdate(syncPeriod, builtUpdate);
559
+ }
593
560
  } catch (e) {
594
561
  this.logger.error(
595
562
  "Error updating best LightClientUpdate",
@@ -605,36 +572,50 @@ export class LightClientServer {
605
572
  */
606
573
  private async maybeStoreNewBestUpdate(
607
574
  syncPeriod: SyncPeriod,
608
- syncAggregate: altair.SyncAggregate,
609
- signatureSlot: Slot,
610
- attestedData: SyncAttestedData
575
+ built: {update: LightClientUpdate; summary: LightClientUpdateSummary}
611
576
  ): Promise<void> {
612
577
  const prevBestUpdate = await this.db.bestLightClientUpdate.get(syncPeriod);
613
- const {attestedHeader} = attestedData;
578
+ if (prevBestUpdate && !isBetterUpdate(built.summary, toLightClientUpdateSummary(prevBestUpdate))) {
579
+ this.metrics?.lightclientServer.updateNotBetter.inc();
580
+ return;
581
+ }
614
582
 
615
- if (prevBestUpdate) {
616
- const prevBestUpdateSummary = toLightClientUpdateSummary(prevBestUpdate);
583
+ // attestedData and the block of syncAggregate may not be in same sync period
584
+ // should not use attested data slot as sync period
585
+ // see https://github.com/ChainSafe/lodestar/issues/3933
586
+ await this.db.bestLightClientUpdate.put(syncPeriod, built.update);
587
+ this.logger.debug("Stored new PartialLightClientUpdate", {
588
+ syncPeriod,
589
+ isFinalized: built.summary.isFinalityUpdate,
590
+ participation: sumBits(built.update.syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
591
+ });
617
592
 
618
- const nextBestUpdate: LightClientUpdateSummary = {
619
- activeParticipants: sumBits(syncAggregate.syncCommitteeBits),
620
- attestedHeaderSlot: attestedHeader.beacon.slot,
621
- signatureSlot,
622
- // The actual finalizedHeader is fetched below. To prevent a DB read we approximate the actual slot.
623
- // If update is not finalized finalizedHeaderSlot does not matter (see is_better_update), so setting
624
- // to zero to set it some number.
625
- finalizedHeaderSlot: attestedData.isFinalized
626
- ? computeStartSlotAtEpoch(attestedData.finalizedCheckpoint.epoch)
627
- : 0,
628
- // All updates include a valid `nextSyncCommitteeBranch`, see below code
629
- isSyncCommitteeUpdate: true,
630
- isFinalityUpdate: attestedData.isFinalized,
631
- };
593
+ // Count total persisted updates per type. DB metrics don't diff between each type.
594
+ // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
595
+ this.metrics?.lightclientServer.onSyncAggregate.inc({
596
+ event: built.summary.isFinalityUpdate ? "store_finalized_update" : "store_nonfinalized_update",
597
+ });
598
+ this.metrics?.lightclientServer.highestSlot.set(
599
+ {item: built.summary.isFinalityUpdate ? "best_finalized_update" : "best_nonfinalized_update"},
600
+ built.update.attestedHeader.beacon.slot
601
+ );
602
+ }
632
603
 
633
- if (!isBetterUpdate(nextBestUpdate, prevBestUpdateSummary)) {
634
- this.metrics?.lightclientServer.updateNotBetter.inc();
635
- return;
636
- }
637
- }
604
+ /**
605
+ * Build the update for `syncAggregate` attesting to `attestedData`.
606
+ *
607
+ * Finality is indicated whenever it can be proven, in one of three ways:
608
+ * - the finalized checkpoint is genesis: the branch is served, the header stays empty, since
609
+ * genesis cannot be proven by a header and the branch alone proves that `finalized_root` is zero
610
+ * - the finalized header is available locally: both the header and the branch are served
611
+ * - the finalized header is not available: neither is served, and `hasFinality` is false
612
+ */
613
+ private async buildUpdate(
614
+ attestedData: SyncAttestedData,
615
+ syncAggregate: altair.SyncAggregate,
616
+ signatureSlot: Slot
617
+ ): Promise<{update: LightClientUpdate; summary: LightClientUpdateSummary; hasFinality: boolean} | null> {
618
+ const {attestedHeader} = attestedData;
638
619
 
639
620
  const syncCommitteeWitness = await this.db.syncCommitteeWitness.get(attestedData.blockRoot);
640
621
  if (!syncCommitteeWitness) {
@@ -662,41 +643,34 @@ export class LightClientServer {
662
643
  throw Error("nextSyncCommittee not available");
663
644
  }
664
645
  const nextSyncCommitteeBranch = getNextSyncCommitteeBranch(syncCommitteeWitness);
665
- const finalizedHeaderAttested = attestedData.isFinalized
666
- ? await this.getFinalizedHeader(attestedData.finalizedCheckpoint.root)
667
- : null;
668
646
 
669
- let isFinalized: boolean, finalityBranch: Uint8Array[], finalizedHeader: LightClientHeader;
647
+ const zeroFinality = this.getZeroFinality(attestedFork, attestedHeader.beacon.slot);
648
+ const {finalizedCheckpoint} = attestedData;
649
+ let finalityBranch = zeroFinality.finalityBranch;
650
+ let finalizedHeader = zeroFinality.finalizedHeader;
651
+ let hasFinality = false;
670
652
 
671
- if (
672
- attestedData.isFinalized &&
673
- finalizedHeaderAttested &&
674
- computeSyncPeriodAtSlot(finalizedHeaderAttested.beacon.slot) === syncPeriod
675
- ) {
676
- isFinalized = true;
653
+ if (finalizedCheckpoint.epoch === GENESIS_EPOCH) {
654
+ // Genesis cannot be proven by a header, the branch alone proves that finalized_root is zero
677
655
  finalityBranch = attestedData.finalityBranch;
678
- finalizedHeader = finalizedHeaderAttested;
679
- // Fork of LightClientUpdate is based off on attested header's fork
680
- if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
681
- finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
682
- }
656
+ hasFinality = true;
683
657
  } else {
684
- isFinalized = false;
685
- let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
- if (!zeroFinality) {
687
- const {finalityBranch, finalizedHeader} = this.config
688
- .getPostAltairForkTypes(attestedHeader.beacon.slot)
689
- .LightClientUpdate.defaultValue();
690
- zeroFinality = {finalityBranch, finalizedHeader};
691
- this.zeroFinalityByFork.set(attestedFork, zeroFinality);
658
+ const finalizedHeaderAttested = await this.getFinalizedHeader(finalizedCheckpoint.root);
659
+ // If the finalized block is not available locally, both stay empty
660
+ if (finalizedHeaderAttested) {
661
+ finalityBranch = attestedData.finalityBranch;
662
+ finalizedHeader = finalizedHeaderAttested;
663
+ hasFinality = true;
664
+ // Fork of LightClientUpdate is based off on attested header's fork
665
+ if (this.config.getForkName(finalizedHeader.beacon.slot) !== attestedFork) {
666
+ finalizedHeader = upgradeLightClientHeader(this.config, attestedFork, finalizedHeader);
667
+ }
692
668
  }
693
- finalityBranch = zeroFinality.finalityBranch;
694
- finalizedHeader = zeroFinality.finalizedHeader;
695
669
  }
696
670
 
697
- const newUpdate = {
671
+ const update = {
698
672
  attestedHeader,
699
- nextSyncCommittee: nextSyncCommittee,
673
+ nextSyncCommittee,
700
674
  nextSyncCommitteeBranch,
701
675
  finalizedHeader,
702
676
  finalityBranch,
@@ -704,25 +678,17 @@ export class LightClientServer {
704
678
  signatureSlot,
705
679
  } as LightClientUpdate;
706
680
 
707
- // attestedData and the block of syncAggregate may not be in same sync period
708
- // should not use attested data slot as sync period
709
- // see https://github.com/ChainSafe/lodestar/issues/3933
710
- await this.db.bestLightClientUpdate.put(syncPeriod, newUpdate);
711
- this.logger.debug("Stored new PartialLightClientUpdate", {
712
- syncPeriod,
713
- isFinalized,
714
- participation: sumBits(syncAggregate.syncCommitteeBits) / SYNC_COMMITTEE_SIZE,
715
- });
681
+ return {update, summary: toLightClientUpdateSummary(update), hasFinality};
682
+ }
716
683
 
717
- // Count total persisted updates per type. DB metrics don't diff between each type.
718
- // The frequency of finalized vs non-finalized is critical to debug if finalizedHeader is not available
719
- this.metrics?.lightclientServer.onSyncAggregate.inc({
720
- event: isFinalized ? "store_finalized_update" : "store_nonfinalized_update",
721
- });
722
- this.metrics?.lightclientServer.highestSlot.set(
723
- {item: isFinalized ? "best_finalized_update" : "best_nonfinalized_update"},
724
- newUpdate.attestedHeader.beacon.slot
725
- );
684
+ private getZeroFinality(attestedFork: ForkName, attestedSlot: Slot): LightClientZeroFinality {
685
+ let zeroFinality = this.zeroFinalityByFork.get(attestedFork);
686
+ if (!zeroFinality) {
687
+ const zero = this.config.getPostAltairForkTypes(attestedSlot).LightClientUpdate.defaultValue();
688
+ zeroFinality = {finalityBranch: zero.finalityBranch, finalizedHeader: zero.finalizedHeader};
689
+ this.zeroFinalityByFork.set(attestedFork, zeroFinality);
690
+ }
691
+ return zeroFinality;
726
692
  }
727
693
 
728
694
  private async storeSyncCommittee(syncCommittee: altair.SyncCommittee, syncCommitteeRoot: Uint8Array): Promise<void> {
@@ -13,6 +13,8 @@ import {PayloadEnvelopeInput, PayloadEnvelopeInputSource} from "../chain/blocks/
13
13
  import {
14
14
  BlockError,
15
15
  BlockErrorCode,
16
+ DataColumnSidecarErrorCode,
17
+ DataColumnSidecarValidationError,
16
18
  ExecutionPayloadEnvelopeError,
17
19
  ExecutionPayloadEnvelopeErrorCode,
18
20
  } from "../chain/errors/index.js";
@@ -1997,7 +1999,20 @@ export class BlockInputSync {
1997
1999
 
1998
2000
  let i = 0;
1999
2001
  let deferredByRateLimit = false;
2002
+ let requestedWhenReconstructable = false;
2000
2003
  while (i++ < this.getMaxDownloadAttempts()) {
2004
+ const reconstructable =
2005
+ isPendingBlockInput(cacheItem) &&
2006
+ isBlockInputColumns(cacheItem.blockInput) &&
2007
+ cacheItem.blockInput.hasBlockAndAllData();
2008
+ // Reconstruction recovers whole rows however many columns are missing, so only one more request is worth it,
2009
+ // further peers could each hold the import until their response times out
2010
+ if (reconstructable) {
2011
+ if (requestedWhenReconstructable) {
2012
+ break;
2013
+ }
2014
+ requestedWhenReconstructable = true;
2015
+ }
2001
2016
  const pendingColumns =
2002
2017
  isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
2003
2018
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
@@ -2012,6 +2027,10 @@ export class BlockInputSync {
2012
2027
  now
2013
2028
  );
2014
2029
  if (peerMeta === null) {
2030
+ if (reconstructable) {
2031
+ break;
2032
+ }
2033
+
2015
2034
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
2016
2035
  if (retryAt !== null) {
2017
2036
  throw new UnknownBlockRateLimitedError(
@@ -2056,8 +2075,16 @@ export class BlockInputSync {
2056
2075
  for (const warning of warnings) {
2057
2076
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
2058
2077
  this.metrics?.blockInputSync.downloadByRoot.warn.inc({code: warning.type.code, client: peerClient});
2078
+ // A partial response is legal, columns that were not requested are not
2079
+ if (warning.type.code === DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED) {
2080
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, warning.type.code);
2081
+ excludedPeers.add(peerId);
2082
+ }
2083
+ // Not picked again for this block, it would be preferred as a previous source of it
2084
+ if (warning.type.code === DownloadByRootErrorCode.NOT_ENOUGH_SIDECARS_RECEIVED) {
2085
+ excludedPeers.add(peerId);
2086
+ }
2059
2087
  }
2060
- // TODO: penalize peer?
2061
2088
  }
2062
2089
  } catch (e) {
2063
2090
  this.logger.debug(
@@ -2066,7 +2093,6 @@ export class BlockInputSync {
2066
2093
  e as Error
2067
2094
  );
2068
2095
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
2069
- // TODO: penalize peer?
2070
2096
  if (e instanceof DownloadByRootError) {
2071
2097
  const errorCode = e.type.code;
2072
2098
  downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
@@ -2082,6 +2108,22 @@ export class BlockInputSync {
2082
2108
  this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2083
2109
  }
2084
2110
  excludedPeers.add(peerId);
2111
+ } else if (e instanceof DataColumnSidecarValidationError) {
2112
+ const errorCode = e.type.code;
2113
+ downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2114
+ // Not PROPOSAL_SIGNATURE_INVALID or INCORRECT_HEADER_ROOT, which compares signatures too: the spec does not
2115
+ // require verifying the header signature of req/resp columns, so honest peers may serve a bad one
2116
+ switch (errorCode) {
2117
+ case DataColumnSidecarErrorCode.INCORRECT_BLOCK:
2118
+ case DataColumnSidecarErrorCode.INVALID_INDEX:
2119
+ case DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT:
2120
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
2121
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
2122
+ case DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID:
2123
+ case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
2124
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2125
+ }
2126
+ excludedPeers.add(peerId);
2085
2127
  } else if (e instanceof RequestError) {
2086
2128
  // should look into req_resp metrics in this case
2087
2129
  downloadByRootMetrics?.error.inc({code: "req_resp", client: peerClient});
@@ -2133,6 +2175,30 @@ export class BlockInputSync {
2133
2175
 
2134
2176
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
2135
2177
 
2178
+ if (
2179
+ isPendingBlockInput(cacheItem) &&
2180
+ isBlockInputColumns(cacheItem.blockInput) &&
2181
+ cacheItem.blockInput.hasBlockAndAllData()
2182
+ ) {
2183
+ // Peers cannot serve the remaining columns now, half of them is enough to reconstruct the rest
2184
+ this.logger.verbose("BlockInputSync.fetchBlockInput: reconstructing columns peers could not serve", {
2185
+ slot,
2186
+ rootHex,
2187
+ missing: cacheItem.blockInput.getMissingSampledColumnMeta().missing.length,
2188
+ });
2189
+ this.chain.columnReconstructionTracker.triggerColumnReconstruction(cacheItem.blockInput);
2190
+ cacheItem = {...cacheItem, status: PendingBlockInputStatus.downloaded, timeSyncedSec: Date.now() / 1000};
2191
+ if (this.pendingBlocks.has(rootHex)) {
2192
+ this.pendingBlocks.set(rootHex, cacheItem);
2193
+ }
2194
+ const result = this.chain.forkChoice.hasBlockHex(cacheItem.blockInput.parentRootHex)
2195
+ ? FetchResult.SuccessResolved
2196
+ : FetchResult.SuccessMissingParent;
2197
+ this.metrics?.blockInputSync.fetchTime.observe({result}, Date.now() / 1000 - fetchStartSec);
2198
+ this.metrics?.blockInputSync.fetchPeers.set({result}, i - 1);
2199
+ return cacheItem;
2200
+ }
2201
+
2136
2202
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
2137
2203
  if (retryAt !== null) {
2138
2204
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -115,9 +115,8 @@ export async function downloadByRoot({
115
115
  });
116
116
  }
117
117
 
118
- const hasAllDataPreDownload = blockInput.hasBlockAndAllData();
119
-
120
- if (isBlockInputColumns(blockInput) && !hasAllDataPreDownload) {
118
+ // Like range sync, download every sampled column, half of them only counts as available for reconstruction
119
+ if (isBlockInputColumns(blockInput) && !blockInput.hasComputedAllData()) {
121
120
  // columnSidecars could be undefined if gossip resulted in full block+columns so we don't download any
122
121
  if (!columnSidecars) {
123
122
  throw new DownloadByRootError({
@@ -154,7 +153,10 @@ export async function downloadByRoot({
154
153
 
155
154
  let status: PendingBlockInputStatus;
156
155
  let timeSyncedSec: number | undefined;
157
- if (blockInput.hasBlockAndAllData()) {
156
+ if (
157
+ blockInput.hasBlock() &&
158
+ (isBlockInputColumns(blockInput) ? blockInput.hasComputedAllData() : blockInput.hasAllData())
159
+ ) {
158
160
  status = PendingBlockInputStatus.downloaded;
159
161
  timeSyncedSec = Date.now() / 1000;
160
162
  } else {
@@ -201,7 +203,7 @@ export async function fetchByRoot({
201
203
  }
202
204
 
203
205
  const forkName = config.getForkName(block.message.slot);
204
- if (!cacheItem.blockInput.hasAllData() && isBlockInputColumns(cacheItem.blockInput)) {
206
+ if (isBlockInputColumns(cacheItem.blockInput) && !cacheItem.blockInput.hasComputedAllData()) {
205
207
  columnSidecarResult = await fetchAndValidateColumns({
206
208
  config,
207
209
  chain,