@lodestar/state-transition 1.45.0 → 1.46.0-dev.20101a8cc1

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 (100) hide show
  1. package/lib/block/processAttestationsAltair.d.ts +4 -1
  2. package/lib/block/processAttestationsAltair.d.ts.map +1 -1
  3. package/lib/block/processAttestationsAltair.js +7 -5
  4. package/lib/block/processAttestationsAltair.js.map +1 -1
  5. package/lib/block/processBuilderDepositRequest.d.ts.map +1 -1
  6. package/lib/block/processBuilderDepositRequest.js +13 -7
  7. package/lib/block/processBuilderDepositRequest.js.map +1 -1
  8. package/lib/block/processOperations.d.ts.map +1 -1
  9. package/lib/block/processOperations.js +17 -1
  10. package/lib/block/processOperations.js.map +1 -1
  11. package/lib/block/processParentExecutionPayload.d.ts.map +1 -1
  12. package/lib/block/processParentExecutionPayload.js +15 -1
  13. package/lib/block/processParentExecutionPayload.js.map +1 -1
  14. package/lib/block/processWithdrawals.js +1 -1
  15. package/lib/block/processWithdrawals.js.map +1 -1
  16. package/lib/cache/epochCache.d.ts.map +1 -1
  17. package/lib/cache/epochCache.js +18 -19
  18. package/lib/cache/epochCache.js.map +1 -1
  19. package/lib/cache/stateCache.d.ts.map +1 -1
  20. package/lib/cache/stateCache.js +2 -4
  21. package/lib/cache/stateCache.js.map +1 -1
  22. package/lib/epoch/processParticipationFlagUpdates.d.ts +2 -2
  23. package/lib/epoch/processParticipationFlagUpdates.d.ts.map +1 -1
  24. package/lib/epoch/processParticipationFlagUpdates.js +13 -0
  25. package/lib/epoch/processParticipationFlagUpdates.js.map +1 -1
  26. package/lib/epoch/processRewardsAndPenalties.d.ts.map +1 -1
  27. package/lib/epoch/processRewardsAndPenalties.js +1 -2
  28. package/lib/epoch/processRewardsAndPenalties.js.map +1 -1
  29. package/lib/lightClient/proofs.d.ts.map +1 -1
  30. package/lib/lightClient/proofs.js +28 -2
  31. package/lib/lightClient/proofs.js.map +1 -1
  32. package/lib/lightClient/spec/index.d.ts.map +1 -1
  33. package/lib/lightClient/spec/index.js +7 -4
  34. package/lib/lightClient/spec/index.js.map +1 -1
  35. package/lib/lightClient/spec/processLightClientUpdate.d.ts.map +1 -1
  36. package/lib/lightClient/spec/processLightClientUpdate.js +8 -2
  37. package/lib/lightClient/spec/processLightClientUpdate.js.map +1 -1
  38. package/lib/lightClient/spec/utils.d.ts +7 -2
  39. package/lib/lightClient/spec/utils.d.ts.map +1 -1
  40. package/lib/lightClient/spec/utils.js +130 -19
  41. package/lib/lightClient/spec/utils.js.map +1 -1
  42. package/lib/lightClient/spec/validateLightClientBootstrap.d.ts.map +1 -1
  43. package/lib/lightClient/spec/validateLightClientBootstrap.js +2 -7
  44. package/lib/lightClient/spec/validateLightClientBootstrap.js.map +1 -1
  45. package/lib/lightClient/spec/validateLightClientUpdate.d.ts.map +1 -1
  46. package/lib/lightClient/spec/validateLightClientUpdate.js +6 -5
  47. package/lib/lightClient/spec/validateLightClientUpdate.js.map +1 -1
  48. package/lib/lightClient/types.d.ts +3 -1
  49. package/lib/lightClient/types.d.ts.map +1 -1
  50. package/lib/metrics.js +2 -4
  51. package/lib/metrics.js.map +1 -1
  52. package/lib/slot/upgradeStateToAltair.js +1 -1
  53. package/lib/slot/upgradeStateToAltair.js.map +1 -1
  54. package/lib/slot/upgradeStateToGloas.d.ts.map +1 -1
  55. package/lib/slot/upgradeStateToGloas.js +49 -10
  56. package/lib/slot/upgradeStateToGloas.js.map +1 -1
  57. package/lib/util/clock.d.ts +55 -0
  58. package/lib/util/clock.d.ts.map +1 -0
  59. package/lib/util/clock.js +142 -0
  60. package/lib/util/clock.js.map +1 -0
  61. package/lib/util/execution.d.ts.map +1 -1
  62. package/lib/util/execution.js +7 -2
  63. package/lib/util/execution.js.map +1 -1
  64. package/lib/util/gloas.d.ts +3 -1
  65. package/lib/util/gloas.d.ts.map +1 -1
  66. package/lib/util/gloas.js +8 -11
  67. package/lib/util/gloas.js.map +1 -1
  68. package/lib/util/index.d.ts +2 -0
  69. package/lib/util/index.d.ts.map +1 -1
  70. package/lib/util/index.js +2 -0
  71. package/lib/util/index.js.map +1 -1
  72. package/lib/util/ssz.d.ts +9 -0
  73. package/lib/util/ssz.d.ts.map +1 -0
  74. package/lib/util/ssz.js +39 -0
  75. package/lib/util/ssz.js.map +1 -0
  76. package/package.json +14 -14
  77. package/src/block/processAttestationsAltair.ts +9 -6
  78. package/src/block/processBuilderDepositRequest.ts +21 -8
  79. package/src/block/processOperations.ts +28 -1
  80. package/src/block/processParentExecutionPayload.ts +26 -1
  81. package/src/block/processWithdrawals.ts +1 -1
  82. package/src/cache/epochCache.ts +19 -22
  83. package/src/cache/stateCache.ts +2 -4
  84. package/src/epoch/processParticipationFlagUpdates.ts +20 -2
  85. package/src/epoch/processRewardsAndPenalties.ts +1 -2
  86. package/src/lightClient/proofs.ts +36 -1
  87. package/src/lightClient/spec/index.ts +8 -4
  88. package/src/lightClient/spec/processLightClientUpdate.ts +13 -1
  89. package/src/lightClient/spec/utils.ts +200 -30
  90. package/src/lightClient/spec/validateLightClientBootstrap.ts +3 -10
  91. package/src/lightClient/spec/validateLightClientUpdate.ts +11 -21
  92. package/src/lightClient/types.ts +3 -1
  93. package/src/metrics.ts +2 -4
  94. package/src/slot/upgradeStateToAltair.ts +1 -1
  95. package/src/slot/upgradeStateToGloas.ts +85 -10
  96. package/src/util/clock.ts +183 -0
  97. package/src/util/execution.ts +9 -4
  98. package/src/util/gloas.ts +9 -14
  99. package/src/util/index.ts +2 -0
  100. package/src/util/ssz.ts +42 -0
@@ -1,3 +1,15 @@
1
+ import {getNodesAtDepth} from "@chainsafe/persistent-merkle-tree";
2
+ import {
3
+ BasicType,
4
+ CompositeType,
5
+ CompositeView,
6
+ CompositeViewDU,
7
+ ListBasicTreeViewDU,
8
+ ListCompositeTreeViewDU,
9
+ ProgressiveListBasicType,
10
+ ProgressiveListCompositeType,
11
+ ValueOf,
12
+ } from "@chainsafe/ssz";
1
13
  import {PAYLOAD_BUILDER_VERSION, SLOTS_PER_HISTORICAL_ROOT} from "@lodestar/params";
2
14
  import {ssz} from "@lodestar/types";
3
15
  import {toPubkeyHex} from "@lodestar/utils";
@@ -7,6 +19,7 @@ import {CachedBeaconStateFulu, CachedBeaconStateGloas} from "../types.js";
7
19
  import {addBuilderToRegistry, initializePtcWindow, isBuilderWithdrawalCredential} from "../util/gloas.js";
8
20
  import {isValidatorKnown} from "../util/index.js";
9
21
  import {PendingDepositsLookup} from "../util/pendingDepositsLookup.js";
22
+ import {progressiveListRootNode} from "../util/ssz.js";
10
23
 
11
24
  /**
12
25
  * Upgrade a state from Fulu to Gloas.
@@ -34,21 +47,30 @@ export function upgradeStateToGloas(stateFulu: CachedBeaconStateFulu): CachedBea
34
47
  stateGloasView.eth1Data = stateGloasCloned.eth1Data;
35
48
  stateGloasView.eth1DataVotes = stateGloasCloned.eth1DataVotes;
36
49
  stateGloasView.eth1DepositIndex = stateGloasCloned.eth1DepositIndex;
37
- stateGloasView.validators = stateGloasCloned.validators;
38
- stateGloasView.balances = stateGloasCloned.balances;
50
+ stateGloasView.validators = migrateCompositeListToGloas(stateGloasCloned.validators, ssz.gloas.Validators);
51
+ stateGloasView.balances = migrateBasicListToGloas(stateGloasCloned.balances, ssz.gloas.Balances);
39
52
  stateGloasView.randaoMixes = stateGloasCloned.randaoMixes;
40
53
  stateGloasView.slashings = stateGloasCloned.slashings;
41
- stateGloasView.previousEpochParticipation = stateGloasCloned.previousEpochParticipation;
42
- stateGloasView.currentEpochParticipation = stateGloasCloned.currentEpochParticipation;
54
+ stateGloasView.previousEpochParticipation = migrateBasicListToGloas(
55
+ stateGloasCloned.previousEpochParticipation,
56
+ ssz.gloas.EpochParticipation
57
+ );
58
+ stateGloasView.currentEpochParticipation = migrateBasicListToGloas(
59
+ stateGloasCloned.currentEpochParticipation,
60
+ ssz.gloas.EpochParticipation
61
+ );
43
62
  stateGloasView.justificationBits = stateGloasCloned.justificationBits;
44
63
  stateGloasView.previousJustifiedCheckpoint = stateGloasCloned.previousJustifiedCheckpoint;
45
64
  stateGloasView.currentJustifiedCheckpoint = stateGloasCloned.currentJustifiedCheckpoint;
46
65
  stateGloasView.finalizedCheckpoint = stateGloasCloned.finalizedCheckpoint;
47
- stateGloasView.inactivityScores = stateGloasCloned.inactivityScores;
66
+ stateGloasView.inactivityScores = migrateBasicListToGloas(
67
+ stateGloasCloned.inactivityScores,
68
+ ssz.gloas.InactivityScores
69
+ );
48
70
  stateGloasView.currentSyncCommittee = stateGloasCloned.currentSyncCommittee;
49
71
  stateGloasView.nextSyncCommittee = stateGloasCloned.nextSyncCommittee;
50
72
  stateGloasView.latestExecutionPayloadBid.blockHash = stateFulu.latestExecutionPayloadHeader.blockHash;
51
- stateGloasView.latestExecutionPayloadBid.gasLimit = stateFulu.latestExecutionPayloadHeader.gasLimit;
73
+ stateGloasView.latestExecutionPayloadBid.gasLimit = BigInt(stateFulu.latestExecutionPayloadHeader.gasLimit);
52
74
  stateGloasView.latestExecutionPayloadBid.executionRequestsRoot = ssz.gloas.ExecutionRequests.hashTreeRoot(
53
75
  ssz.gloas.ExecutionRequests.defaultValue()
54
76
  );
@@ -61,9 +83,18 @@ export function upgradeStateToGloas(stateFulu: CachedBeaconStateFulu): CachedBea
61
83
  stateGloasView.earliestExitEpoch = stateGloasCloned.earliestExitEpoch;
62
84
  stateGloasView.consolidationBalanceToConsume = stateGloasCloned.consolidationBalanceToConsume;
63
85
  stateGloasView.earliestConsolidationEpoch = stateGloasCloned.earliestConsolidationEpoch;
64
- stateGloasView.pendingDeposits = stateGloasCloned.pendingDeposits;
65
- stateGloasView.pendingPartialWithdrawals = stateGloasCloned.pendingPartialWithdrawals;
66
- stateGloasView.pendingConsolidations = stateGloasCloned.pendingConsolidations;
86
+ stateGloasView.pendingDeposits = migrateCompositeListToGloas(
87
+ stateGloasCloned.pendingDeposits,
88
+ ssz.gloas.PendingDeposits
89
+ );
90
+ stateGloasView.pendingPartialWithdrawals = migrateCompositeListToGloas(
91
+ stateGloasCloned.pendingPartialWithdrawals,
92
+ ssz.gloas.PendingPartialWithdrawals
93
+ );
94
+ stateGloasView.pendingConsolidations = migrateCompositeListToGloas(
95
+ stateGloasCloned.pendingConsolidations,
96
+ ssz.gloas.PendingConsolidations
97
+ );
67
98
  stateGloasView.proposerLookahead = stateGloasCloned.proposerLookahead;
68
99
  stateGloasView.ptcWindow = ssz.gloas.PtcWindow.toViewDU(initializePtcWindow(stateFulu));
69
100
 
@@ -85,6 +116,50 @@ export function upgradeStateToGloas(stateFulu: CachedBeaconStateFulu): CachedBea
85
116
  return stateGloas;
86
117
  }
87
118
 
119
+ /**
120
+ * Migrate a composite list from fulu to its gloas progressive-list equivalent by reusing the fulu
121
+ * list's element nodes.
122
+ *
123
+ * Works whenever the element type is identical across the fork (e.g. validators use ValidatorNodeStruct,
124
+ * the pending* queues use the same electra element types). Each element's cached subtree root is then
125
+ * valid under gloas, so only the progressive list superstructure is rebuilt and a subsequent
126
+ * hashTreeRoot() skips re-hashing every element — the dominant cost for large lists like validators.
127
+ * Much cheaper than `gloasType.toViewDU(fuluList.getAllReadonlyValues())`, which decodes every element
128
+ * to a value and forces a full re-hash.
129
+ *
130
+ * The chunk nodes of a composite list ARE the element root nodes, so they are extracted directly
131
+ * with getNodesAtDepth instead of allocating a temporary ViewDU wrapper per element (getAllReadonly).
132
+ * Requires the fulu view to be committed (done at the top of upgradeStateToGloas).
133
+ */
134
+ function migrateCompositeListToGloas<
135
+ ElementType extends CompositeType<ValueOf<ElementType>, CompositeView<ElementType>, CompositeViewDU<ElementType>>,
136
+ >(fuluList: ListCompositeTreeViewDU<ElementType>, gloasType: ProgressiveListCompositeType<ElementType>) {
137
+ const {length, type} = fuluList;
138
+ const elementNodes = getNodesAtDepth(fuluList.node.left, type.chunkDepth, 0, length);
139
+ return gloasType.getViewDU(progressiveListRootNode(elementNodes, length));
140
+ }
141
+
142
+ /**
143
+ * Migrate a basic list from fulu to its gloas progressive-list equivalent by reusing the fulu
144
+ * list's packed chunk leaf nodes.
145
+ *
146
+ * Packed leaf chunks are bit-identical between List[T, N] and ProgressiveList[T] (same 32-byte
147
+ * LE packing, zero-padded final chunk); only the superstructure above the leaves differs. Reusing
148
+ * the leaves avoids materializing the value array (getAll), re-serializing it, and allocating
149
+ * fresh LeafNodes — the gloas tree shares the leaf nodes with the fulu tree.
150
+ * Requires the fulu view to be committed (done at the top of upgradeStateToGloas).
151
+ */
152
+ function migrateBasicListToGloas<ElementType extends BasicType<unknown>>(
153
+ fuluList: ListBasicTreeViewDU<ElementType>,
154
+ gloasType: ProgressiveListBasicType<ElementType>
155
+ ) {
156
+ const {length, type} = fuluList;
157
+ const chunkCount = Math.ceil(length / type.itemsPerChunk);
158
+ // List root = BranchNode(chunksNode, lengthNode) → chunks tree is the left child
159
+ const chunkLeafNodes = getNodesAtDepth(fuluList.node.left, type.chunkDepth, 0, chunkCount);
160
+ return gloasType.getViewDU(progressiveListRootNode(chunkLeafNodes, length));
161
+ }
162
+
88
163
  /**
89
164
  * Applies any pending deposits for builders to onboard builders during the fork transition
90
165
  * Spec: https://github.com/ethereum/consensus-specs/blob/v1.7.0-alpha.8/specs/gloas/fork.md#new-onboard_builders_from_pending_deposits
@@ -94,7 +169,7 @@ function onboardBuildersFromPendingDeposits(state: CachedBeaconStateGloas): void
94
169
  // at the fork, so every builder pubkey here is one added in an earlier iteration.
95
170
  const builderPubkeys = new Set<string>();
96
171
 
97
- const pendingDeposits = ssz.electra.PendingDeposits.defaultViewDU();
172
+ const pendingDeposits = ssz.gloas.PendingDeposits.defaultViewDU();
98
173
  const pendingDepositsLookup = PendingDepositsLookup.buildEmpty();
99
174
 
100
175
  for (let i = 0; i < state.pendingDeposits.length; i++) {
@@ -0,0 +1,183 @@
1
+ import {ChainForkConfig} from "@lodestar/config";
2
+ import {GENESIS_SLOT, SLOTS_PER_EPOCH} from "@lodestar/params";
3
+ import {Epoch, Slot, TimeSeconds} from "@lodestar/types";
4
+ import {ErrorAborted, Logger, isErrorAborted, sleep} from "@lodestar/utils";
5
+ import {computeEpochAtSlot} from "./epoch.js";
6
+ import {computeTimeAtSlot, getCurrentSlot} from "./slot.js";
7
+
8
+ type RunEveryFn = (slot: Slot, signal: AbortSignal) => Promise<void>;
9
+
10
+ export type ClockOptions = {
11
+ skipSlots?: boolean;
12
+ };
13
+
14
+ export interface IClock {
15
+ readonly genesisTime: number;
16
+ readonly secondsPerSlot: number;
17
+
18
+ readonly currentEpoch: number;
19
+
20
+ start(signal: AbortSignal): void;
21
+ runEverySlot(fn: (slot: Slot, signal: AbortSignal) => Promise<void>): void;
22
+ runEveryEpoch(fn: (epoch: Epoch, signal: AbortSignal) => Promise<void>): void;
23
+ msToSlot(slot: Slot): number;
24
+ msFromSlot(slot: Slot): number;
25
+ secFromSlot(slot: Slot): number;
26
+ getCurrentSlot(): Slot;
27
+ getCurrentEpoch(): Epoch;
28
+ }
29
+
30
+ export enum TimeItem {
31
+ Slot,
32
+ Epoch,
33
+ }
34
+
35
+ export class Clock implements IClock {
36
+ readonly genesisTime: number;
37
+ readonly secondsPerSlot: number;
38
+ private readonly config: ChainForkConfig;
39
+ private readonly logger: Logger;
40
+ private readonly fns: {timeItem: TimeItem; fn: RunEveryFn}[] = [];
41
+
42
+ constructor(
43
+ config: ChainForkConfig,
44
+ logger: Logger,
45
+ private readonly opts: {genesisTime: number} & ClockOptions
46
+ ) {
47
+ this.genesisTime = opts.genesisTime;
48
+ this.secondsPerSlot = config.SLOT_DURATION_MS / 1000;
49
+ this.config = config;
50
+ this.logger = logger;
51
+ }
52
+
53
+ get currentEpoch(): Epoch {
54
+ return computeEpochAtSlot(getCurrentSlot(this.config, this.genesisTime));
55
+ }
56
+
57
+ start(signal: AbortSignal): void {
58
+ for (const {timeItem, fn} of this.fns) {
59
+ this.runAtMostEvery(timeItem, signal, fn).catch((e: Error) => {
60
+ if (!isErrorAborted(e)) {
61
+ this.logger.error("runAtMostEvery", {}, e);
62
+ }
63
+ });
64
+ }
65
+ }
66
+
67
+ getCurrentSlot(): Slot {
68
+ return getCurrentSlot(this.config, this.genesisTime);
69
+ }
70
+
71
+ getCurrentEpoch(): Epoch {
72
+ return computeEpochAtSlot(getCurrentSlot(this.config, this.genesisTime));
73
+ }
74
+
75
+ runEverySlot(fn: RunEveryFn): void {
76
+ this.fns.push({timeItem: TimeItem.Slot, fn});
77
+ }
78
+
79
+ runEveryEpoch(fn: RunEveryFn): void {
80
+ this.fns.push({timeItem: TimeItem.Epoch, fn});
81
+ }
82
+
83
+ /** Milliseconds from now to a specific slot */
84
+ msToSlot(slot: Slot): number {
85
+ return computeTimeAtSlot(this.config, slot, this.genesisTime) * 1000 - Date.now();
86
+ }
87
+
88
+ /** Milliseconds elapsed from a specific slot to now */
89
+ msFromSlot(slot: Slot): number {
90
+ return Date.now() - computeTimeAtSlot(this.config, slot, this.genesisTime) * 1000;
91
+ }
92
+
93
+ /** Seconds elapsed from a specific slot to now */
94
+ secFromSlot(slot: Slot): number {
95
+ return Date.now() / 1000 - computeTimeAtSlot(this.config, slot, this.genesisTime);
96
+ }
97
+
98
+ /**
99
+ * If a task happens to take more than one slot to run, we might skip a slot. This is unfortunate,
100
+ * however the alternative is to *always* process every slot, which has the chance of creating a
101
+ * theoretically unlimited backlog of tasks. It was a conscious decision to choose to drop tasks
102
+ * on an overloaded/latent system rather than overload it even more.
103
+ */
104
+ private async runAtMostEvery(timeItem: TimeItem, signal: AbortSignal, fn: RunEveryFn): Promise<void> {
105
+ // Run immediately first
106
+ let slot = getCurrentSlot(this.config, this.genesisTime);
107
+ let slotOrEpoch = timeItem === TimeItem.Slot ? slot : computeEpochAtSlot(slot);
108
+ while (!signal.aborted) {
109
+ // Must catch fn() to ensure `sleep()` is awaited both for resolve and reject
110
+ const task = fn(slotOrEpoch, signal).catch((e: Error) => {
111
+ if (!isErrorAborted(e)) this.logger.error("Error on runEvery fn", {}, e);
112
+ });
113
+
114
+ if (timeItem !== TimeItem.Slot || this.opts.skipSlots !== false) {
115
+ // await response to only continue with next task if current task finished within slot
116
+ await task;
117
+ }
118
+
119
+ try {
120
+ await sleep(this.timeUntilNext(timeItem), signal);
121
+ // calling getCurrentSlot here may not be correct when we're close to the next slot
122
+ // it's safe to call getCurrentSlotAround after we sleep
123
+ const nextSlot = getCurrentSlotAround(this.config, this.genesisTime);
124
+
125
+ if (timeItem === TimeItem.Slot) {
126
+ if (nextSlot > slot + 1) {
127
+ // It's not very likely that we skip more than one slot as HTTP timeout is set
128
+ // to SLOT_DURATION_MS so we will fail task before skipping another slot.
129
+ this.logger.warn("Skipped slot due to task taking more than one slot to run", {
130
+ skippedSlot: slot + 1,
131
+ });
132
+ }
133
+ slotOrEpoch = nextSlot;
134
+ } else {
135
+ slotOrEpoch = computeEpochAtSlot(nextSlot);
136
+ }
137
+ slot = nextSlot;
138
+ } catch (e) {
139
+ if (e instanceof ErrorAborted) {
140
+ return;
141
+ }
142
+ throw e;
143
+ }
144
+ }
145
+ }
146
+
147
+ private timeUntilNext(timeItem: TimeItem): number {
148
+ const milliSecondsPerSlot = this.config.SLOT_DURATION_MS;
149
+ const msFromGenesis = Date.now() - this.genesisTime * 1000;
150
+
151
+ if (timeItem === TimeItem.Slot) {
152
+ if (msFromGenesis >= 0) {
153
+ return milliSecondsPerSlot - (msFromGenesis % milliSecondsPerSlot);
154
+ }
155
+ return Math.abs(msFromGenesis) % milliSecondsPerSlot;
156
+ }
157
+ const milliSecondsPerEpoch = SLOTS_PER_EPOCH * milliSecondsPerSlot;
158
+ if (msFromGenesis >= 0) {
159
+ return milliSecondsPerEpoch - (msFromGenesis % milliSecondsPerEpoch);
160
+ }
161
+ return Math.abs(msFromGenesis) % milliSecondsPerEpoch;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Same to the spec but we use Math.round instead of Math.floor.
167
+ */
168
+ export function getCurrentSlotAround(config: ChainForkConfig, genesisTime: TimeSeconds): Slot {
169
+ const diffInSeconds = Date.now() / 1000 - genesisTime;
170
+ const slotsSinceGenesis = Math.round((diffInSeconds * 1000) / config.SLOT_DURATION_MS);
171
+ return GENESIS_SLOT + slotsSinceGenesis;
172
+ }
173
+
174
+ // function useEventStream() {
175
+ // this.stream = this.events.getEventStream([BeaconEventType.BLOCK, BeaconEventType.HEAD, BeaconEventType.CHAIN_REORG]);
176
+ // pipeToEmitter(this.stream, this).catch((e: Error) => {
177
+ // this.logger.error("Error on stream pipe", {}, e);
178
+ // });
179
+
180
+ // // On stop
181
+ // this.stream.stop();
182
+ // this.stream = null;
183
+ // }
@@ -9,6 +9,7 @@ import {
9
9
  bellatrix,
10
10
  capella,
11
11
  deneb,
12
+ gloas,
12
13
  isBlindedBeaconBlockBody,
13
14
  isExecutionPayload,
14
15
  ssz,
@@ -127,7 +128,10 @@ export function isCapellaPayloadHeader(
127
128
  }
128
129
 
129
130
  export function executionPayloadToPayloadHeader(fork: ForkSeq, payload: ExecutionPayload): ExecutionPayloadHeader {
130
- const transactionsRoot = ssz.bellatrix.Transactions.hashTreeRoot(payload.transactions);
131
+ const transactionsRoot =
132
+ fork >= ForkSeq.gloas
133
+ ? ssz.gloas.Transactions.hashTreeRoot((payload as gloas.ExecutionPayload).transactions)
134
+ : ssz.bellatrix.Transactions.hashTreeRoot(payload.transactions);
131
135
 
132
136
  const bellatrixPayloadFields: ExecutionPayloadHeader = {
133
137
  parentHash: payload.parentHash,
@@ -147,9 +151,10 @@ export function executionPayloadToPayloadHeader(fork: ForkSeq, payload: Executio
147
151
  };
148
152
 
149
153
  if (fork >= ForkSeq.capella) {
150
- (bellatrixPayloadFields as capella.ExecutionPayloadHeader).withdrawalsRoot = ssz.capella.Withdrawals.hashTreeRoot(
151
- (payload as capella.ExecutionPayload).withdrawals
152
- );
154
+ (bellatrixPayloadFields as capella.ExecutionPayloadHeader).withdrawalsRoot =
155
+ fork >= ForkSeq.gloas
156
+ ? ssz.gloas.Withdrawals.hashTreeRoot((payload as gloas.ExecutionPayload).withdrawals)
157
+ : ssz.capella.Withdrawals.hashTreeRoot((payload as capella.ExecutionPayload).withdrawals);
153
158
  }
154
159
 
155
160
  if (fork >= ForkSeq.deneb) {
package/src/util/gloas.ts CHANGED
@@ -18,7 +18,6 @@ import {AttestationData} from "@lodestar/types/phase0";
18
18
  import {byteArrayEquals} from "@lodestar/utils";
19
19
  import {ZERO_HASH} from "../constants/index.js";
20
20
  import {CachedBeaconStateFulu, CachedBeaconStateGloas} from "../types.js";
21
- import {getBlockRootAtSlot} from "./blockRoot.js";
22
21
  import {computeDomain} from "./domain.js";
23
22
  import {computeEpochAtSlot} from "./epoch.js";
24
23
  import {computeEpochShuffling} from "./epochShuffling.js";
@@ -32,11 +31,13 @@ export function isBuilderWithdrawalCredential(withdrawalCredentials: Uint8Array)
32
31
  }
33
32
 
34
33
  export function getBuilderPaymentQuorumThreshold(state: CachedBeaconStateGloas): number {
35
- const quorum =
36
- Math.floor((state.epochCtx.totalActiveBalanceIncrements * EFFECTIVE_BALANCE_INCREMENT) / SLOTS_PER_EPOCH) *
37
- BUILDER_PAYMENT_THRESHOLD_NUMERATOR;
34
+ // total active balance exceeds Number.MAX_SAFE_INTEGER at mainnet scale, keep the intermediate math in bigint
35
+ const perSlotBalance =
36
+ (BigInt(state.epochCtx.totalActiveBalanceIncrements) * BigInt(EFFECTIVE_BALANCE_INCREMENT)) /
37
+ BigInt(SLOTS_PER_EPOCH);
38
+ const quorum = perSlotBalance * BigInt(BUILDER_PAYMENT_THRESHOLD_NUMERATOR);
38
39
 
39
- return Math.floor(quorum / BUILDER_PAYMENT_THRESHOLD_DENOMINATOR);
40
+ return Number(quorum / BigInt(BUILDER_PAYMENT_THRESHOLD_DENOMINATOR));
40
41
  }
41
42
 
42
43
  function hasBuilderIndexFlag(index: number): boolean {
@@ -188,15 +189,9 @@ export function findBuilderIndexByPubkey(state: CachedBeaconStateGloas, pubkey:
188
189
  return null;
189
190
  }
190
191
 
191
- export function isAttestationSameSlot(state: CachedBeaconStateGloas, data: AttestationData): boolean {
192
- if (data.slot === 0) return true;
193
-
194
- const isMatchingBlockRoot = byteArrayEquals(data.beaconBlockRoot, getBlockRootAtSlot(state, data.slot));
195
- const isCurrentBlockRoot = !byteArrayEquals(data.beaconBlockRoot, getBlockRootAtSlot(state, data.slot - 1));
196
-
197
- return isMatchingBlockRoot && isCurrentBlockRoot;
198
- }
199
-
192
+ /**
193
+ * Use cached block roots to avoid repeated state root lookups while matching the spec's is_attestation_same_slot behavior.
194
+ */
200
195
  export function isAttestationSameSlotRootCache(rootCache: RootCache, data: AttestationData): boolean {
201
196
  if (data.slot === 0) return true;
202
197
 
package/src/util/index.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./balance.js";
6
6
  export * from "./blindedBlock.js";
7
7
  export * from "./blockRoot.js";
8
8
  export * from "./capella.js";
9
+ export * from "./clock.js";
9
10
  export * from "./computeAnchorCheckpoint.js";
10
11
  export * from "./deposit.js";
11
12
  export * from "./domain.js";
@@ -25,6 +26,7 @@ export * from "./shuffling.js";
25
26
  export * from "./signatureSets.js";
26
27
  export * from "./signingRoot.js";
27
28
  export * from "./slot.js";
29
+ export * from "./ssz.js";
28
30
  export * from "./syncCommittee.js";
29
31
  export * from "./validator.js";
30
32
  export * from "./weakSubjectivity.js";
@@ -0,0 +1,42 @@
1
+ import {BranchNode, LeafNode, Node, zeroNode} from "@chainsafe/persistent-merkle-tree";
2
+ import {progressiveSubtreeFillToContents} from "@chainsafe/ssz";
3
+
4
+ // TODO: move these utils to @chainsafe/ssz (progressive.ts, next to progressiveSubtreeFillToContents)
5
+
6
+ /** Root node (chunks + length mix-in) of a zero-filled ProgressiveListBasicType of `length` items */
7
+ export function zeroProgressiveListBasicRootNode(itemsPerChunk: number, length: number): Node {
8
+ const chunkCount = Math.ceil(length / itemsPerChunk);
9
+ // mirrors ssz's progressiveSubtreeCount (subtree capacities 1, 4, 16, ...)
10
+ let numSubtrees = 0;
11
+ for (let remaining = chunkCount, subtreeLength = 1; remaining > 0; subtreeLength *= 4) {
12
+ remaining -= Math.min(remaining, subtreeLength);
13
+ numSubtrees++;
14
+ }
15
+ return new BranchNode(zeroProgressiveNode(numSubtrees), LeafNode.fromUint32(length));
16
+ }
17
+
18
+ /**
19
+ * Root node of a progressive list from its chunk/element nodes + length mix-in.
20
+ * `nodes` are packed 32-byte chunk leaves for basic lists, or element root nodes for composite lists.
21
+ */
22
+ export function progressiveListRootNode(nodes: Node[], length: number): Node {
23
+ return new BranchNode(progressiveSubtreeFillToContents(nodes), LeafNode.fromUint32(length));
24
+ }
25
+
26
+ /**
27
+ * Return the chunks node of a zero-filled progressive merkle list spanning `numSubtrees`
28
+ * balanced subtrees (chunk capacities 1, 4, 16, ... = 4^i; depths 0, 2, 4, ... = 2i).
29
+ *
30
+ * Not memoized: the zero data is already fully shared via the cached zeroNode(2i) subtrees;
31
+ * only the O(numSubtrees) spine BranchNodes (~10 at 2M validators) are allocated per call.
32
+ */
33
+ function zeroProgressiveNode(numSubtrees: number): Node {
34
+ // chain(k) = B(zeroNode(0), B(zeroNode(2), ... B(zeroNode(2(k-1)), zeroNode(0))))
35
+ let node: Node = zeroNode(0); // terminator
36
+ for (let i = numSubtrees - 1; i >= 0; i--) {
37
+ // BranchNode(left: balanced subtree i, right: rest of chain) — chain grows to the right,
38
+ // same as ssz progressiveSubtreeFillToContents: `root = new BranchNode(subtreeRoots[i], root)`
39
+ node = new BranchNode(zeroNode(2 * i), node);
40
+ }
41
+ return node;
42
+ }