@lodestar/state-transition 1.39.0-dev.882891d89c → 1.39.0-dev.90334173dc

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 (172) hide show
  1. package/lib/block/index.d.ts.map +1 -1
  2. package/lib/block/index.js +4 -2
  3. package/lib/block/index.js.map +1 -1
  4. package/lib/block/isValidIndexedAttestation.d.ts +4 -5
  5. package/lib/block/isValidIndexedAttestation.d.ts.map +1 -1
  6. package/lib/block/isValidIndexedAttestation.js +9 -10
  7. package/lib/block/isValidIndexedAttestation.js.map +1 -1
  8. package/lib/block/processAttestationPhase0.d.ts.map +1 -1
  9. package/lib/block/processAttestationPhase0.js +1 -1
  10. package/lib/block/processAttestationPhase0.js.map +1 -1
  11. package/lib/block/processAttestationsAltair.js +1 -1
  12. package/lib/block/processAttestationsAltair.js.map +1 -1
  13. package/lib/block/processAttesterSlashing.d.ts +3 -2
  14. package/lib/block/processAttesterSlashing.d.ts.map +1 -1
  15. package/lib/block/processAttesterSlashing.js +3 -3
  16. package/lib/block/processAttesterSlashing.js.map +1 -1
  17. package/lib/block/processBlsToExecutionChange.d.ts +3 -1
  18. package/lib/block/processBlsToExecutionChange.d.ts.map +1 -1
  19. package/lib/block/processBlsToExecutionChange.js +7 -11
  20. package/lib/block/processBlsToExecutionChange.js.map +1 -1
  21. package/lib/block/processExecutionPayload.d.ts.map +1 -1
  22. package/lib/block/processExecutionPayload.js +6 -4
  23. package/lib/block/processExecutionPayload.js.map +1 -1
  24. package/lib/block/processProposerSlashing.d.ts +5 -2
  25. package/lib/block/processProposerSlashing.d.ts.map +1 -1
  26. package/lib/block/processProposerSlashing.js +7 -5
  27. package/lib/block/processProposerSlashing.js.map +1 -1
  28. package/lib/block/processRandao.js +2 -2
  29. package/lib/block/processRandao.js.map +1 -1
  30. package/lib/block/processSyncCommittee.d.ts +2 -1
  31. package/lib/block/processSyncCommittee.d.ts.map +1 -1
  32. package/lib/block/processSyncCommittee.js +6 -4
  33. package/lib/block/processSyncCommittee.js.map +1 -1
  34. package/lib/block/processVoluntaryExit.js +1 -1
  35. package/lib/block/processVoluntaryExit.js.map +1 -1
  36. package/lib/block/processWithdrawals.d.ts +3 -3
  37. package/lib/block/processWithdrawals.d.ts.map +1 -1
  38. package/lib/block/processWithdrawals.js +152 -105
  39. package/lib/block/processWithdrawals.js.map +1 -1
  40. package/lib/cache/epochCache.d.ts +8 -28
  41. package/lib/cache/epochCache.d.ts.map +1 -1
  42. package/lib/cache/epochCache.js +40 -180
  43. package/lib/cache/epochCache.js.map +1 -1
  44. package/lib/cache/epochTransitionCache.d.ts +5 -12
  45. package/lib/cache/epochTransitionCache.d.ts.map +1 -1
  46. package/lib/cache/epochTransitionCache.js +4 -14
  47. package/lib/cache/epochTransitionCache.js.map +1 -1
  48. package/lib/cache/stateCache.d.ts.map +1 -1
  49. package/lib/cache/stateCache.js +1 -2
  50. package/lib/cache/stateCache.js.map +1 -1
  51. package/lib/epoch/processProposerLookahead.d.ts.map +1 -1
  52. package/lib/epoch/processProposerLookahead.js +3 -6
  53. package/lib/epoch/processProposerLookahead.js.map +1 -1
  54. package/lib/index.d.ts +3 -2
  55. package/lib/index.d.ts.map +1 -1
  56. package/lib/index.js +3 -1
  57. package/lib/index.js.map +1 -1
  58. package/lib/rewards/attestationsRewards.d.ts +6 -0
  59. package/lib/rewards/attestationsRewards.d.ts.map +1 -0
  60. package/lib/rewards/attestationsRewards.js +113 -0
  61. package/lib/rewards/attestationsRewards.js.map +1 -0
  62. package/lib/rewards/blockRewards.d.ts +14 -0
  63. package/lib/rewards/blockRewards.d.ts.map +1 -0
  64. package/lib/rewards/blockRewards.js +96 -0
  65. package/lib/rewards/blockRewards.js.map +1 -0
  66. package/lib/rewards/index.d.ts +4 -0
  67. package/lib/rewards/index.d.ts.map +1 -0
  68. package/lib/rewards/index.js +4 -0
  69. package/lib/rewards/index.js.map +1 -0
  70. package/lib/rewards/syncCommitteeRewards.d.ts +6 -0
  71. package/lib/rewards/syncCommitteeRewards.d.ts.map +1 -0
  72. package/lib/rewards/syncCommitteeRewards.js +35 -0
  73. package/lib/rewards/syncCommitteeRewards.js.map +1 -0
  74. package/lib/signatureSets/attesterSlashings.d.ts +4 -5
  75. package/lib/signatureSets/attesterSlashings.d.ts.map +1 -1
  76. package/lib/signatureSets/attesterSlashings.js +10 -7
  77. package/lib/signatureSets/attesterSlashings.js.map +1 -1
  78. package/lib/signatureSets/blsToExecutionChange.d.ts +1 -2
  79. package/lib/signatureSets/blsToExecutionChange.d.ts.map +1 -1
  80. package/lib/signatureSets/blsToExecutionChange.js +2 -2
  81. package/lib/signatureSets/blsToExecutionChange.js.map +1 -1
  82. package/lib/signatureSets/index.d.ts +2 -2
  83. package/lib/signatureSets/index.d.ts.map +1 -1
  84. package/lib/signatureSets/index.js +10 -10
  85. package/lib/signatureSets/index.js.map +1 -1
  86. package/lib/signatureSets/indexedAttestation.d.ts +5 -6
  87. package/lib/signatureSets/indexedAttestation.d.ts.map +1 -1
  88. package/lib/signatureSets/indexedAttestation.js +12 -9
  89. package/lib/signatureSets/indexedAttestation.js.map +1 -1
  90. package/lib/signatureSets/proposer.d.ts +5 -6
  91. package/lib/signatureSets/proposer.d.ts.map +1 -1
  92. package/lib/signatureSets/proposer.js +12 -10
  93. package/lib/signatureSets/proposer.js.map +1 -1
  94. package/lib/signatureSets/proposerSlashings.d.ts +3 -4
  95. package/lib/signatureSets/proposerSlashings.d.ts.map +1 -1
  96. package/lib/signatureSets/proposerSlashings.js +7 -4
  97. package/lib/signatureSets/proposerSlashings.js.map +1 -1
  98. package/lib/signatureSets/randao.d.ts +2 -3
  99. package/lib/signatureSets/randao.d.ts.map +1 -1
  100. package/lib/signatureSets/randao.js +6 -4
  101. package/lib/signatureSets/randao.js.map +1 -1
  102. package/lib/signatureSets/voluntaryExits.d.ts +4 -5
  103. package/lib/signatureSets/voluntaryExits.d.ts.map +1 -1
  104. package/lib/signatureSets/voluntaryExits.js +10 -7
  105. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  106. package/lib/stateTransition.d.ts.map +1 -1
  107. package/lib/stateTransition.js +1 -2
  108. package/lib/stateTransition.js.map +1 -1
  109. package/lib/types.d.ts +1 -1
  110. package/lib/types.d.ts.map +1 -1
  111. package/lib/util/epochShuffling.d.ts +1 -34
  112. package/lib/util/epochShuffling.d.ts.map +1 -1
  113. package/lib/util/epochShuffling.js +1 -1
  114. package/lib/util/epochShuffling.js.map +1 -1
  115. package/lib/util/execution.d.ts +11 -1
  116. package/lib/util/execution.d.ts.map +1 -1
  117. package/lib/util/execution.js +26 -1
  118. package/lib/util/execution.js.map +1 -1
  119. package/lib/util/index.d.ts +1 -2
  120. package/lib/util/index.d.ts.map +1 -1
  121. package/lib/util/index.js +1 -2
  122. package/lib/util/index.js.map +1 -1
  123. package/lib/util/shuffling.d.ts +58 -0
  124. package/lib/util/shuffling.d.ts.map +1 -0
  125. package/lib/util/shuffling.js +175 -0
  126. package/lib/util/shuffling.js.map +1 -0
  127. package/package.json +14 -11
  128. package/src/block/index.ts +6 -2
  129. package/src/block/isValidIndexedAttestation.ts +19 -12
  130. package/src/block/processAttestationPhase0.ts +2 -1
  131. package/src/block/processAttestationsAltair.ts +1 -1
  132. package/src/block/processAttesterSlashing.ts +16 -4
  133. package/src/block/processBlsToExecutionChange.ts +13 -14
  134. package/src/block/processExecutionPayload.ts +14 -8
  135. package/src/block/processProposerSlashing.ts +21 -11
  136. package/src/block/processRandao.ts +2 -2
  137. package/src/block/processSyncCommittee.ts +7 -4
  138. package/src/block/processVoluntaryExit.ts +1 -1
  139. package/src/block/processWithdrawals.ts +230 -135
  140. package/src/cache/epochCache.ts +52 -214
  141. package/src/cache/epochTransitionCache.ts +9 -34
  142. package/src/cache/stateCache.ts +1 -2
  143. package/src/epoch/processProposerLookahead.ts +3 -7
  144. package/src/index.ts +2 -4
  145. package/src/rewards/attestationsRewards.ts +200 -0
  146. package/src/rewards/blockRewards.ts +150 -0
  147. package/src/rewards/index.ts +3 -0
  148. package/src/rewards/syncCommitteeRewards.ts +56 -0
  149. package/src/signatureSets/attesterSlashings.ts +10 -9
  150. package/src/signatureSets/blsToExecutionChange.ts +2 -3
  151. package/src/signatureSets/index.ts +11 -11
  152. package/src/signatureSets/indexedAttestation.ts +12 -11
  153. package/src/signatureSets/proposer.ts +11 -11
  154. package/src/signatureSets/proposerSlashings.ts +7 -6
  155. package/src/signatureSets/randao.ts +4 -5
  156. package/src/signatureSets/voluntaryExits.ts +10 -9
  157. package/src/stateTransition.ts +1 -4
  158. package/src/types.ts +1 -0
  159. package/src/util/epochShuffling.ts +2 -43
  160. package/src/util/execution.ts +39 -0
  161. package/src/util/index.ts +1 -2
  162. package/src/util/shuffling.ts +234 -0
  163. package/lib/util/calculateCommitteeAssignments.d.ts +0 -12
  164. package/lib/util/calculateCommitteeAssignments.d.ts.map +0 -1
  165. package/lib/util/calculateCommitteeAssignments.js +0 -26
  166. package/lib/util/calculateCommitteeAssignments.js.map +0 -1
  167. package/lib/util/shufflingDecisionRoot.d.ts +0 -20
  168. package/lib/util/shufflingDecisionRoot.d.ts.map +0 -1
  169. package/lib/util/shufflingDecisionRoot.js +0 -76
  170. package/lib/util/shufflingDecisionRoot.js.map +0 -1
  171. package/src/util/calculateCommitteeAssignments.ts +0 -43
  172. package/src/util/shufflingDecisionRoot.ts +0 -81
@@ -0,0 +1,200 @@
1
+ import {PubkeyIndexMap} from "@chainsafe/pubkey-index-map";
2
+ import {BeaconConfig} from "@lodestar/config";
3
+ import {
4
+ EFFECTIVE_BALANCE_INCREMENT,
5
+ ForkName,
6
+ INACTIVITY_PENALTY_QUOTIENT_ALTAIR,
7
+ MAX_EFFECTIVE_BALANCE,
8
+ MAX_EFFECTIVE_BALANCE_ELECTRA,
9
+ PARTICIPATION_FLAG_WEIGHTS,
10
+ TIMELY_HEAD_FLAG_INDEX,
11
+ TIMELY_SOURCE_FLAG_INDEX,
12
+ TIMELY_TARGET_FLAG_INDEX,
13
+ WEIGHT_DENOMINATOR,
14
+ isForkPostElectra,
15
+ } from "@lodestar/params";
16
+ import {ValidatorIndex, rewards} from "@lodestar/types";
17
+ import {fromHex} from "@lodestar/utils";
18
+ import {EpochTransitionCache, beforeProcessEpoch} from "../cache/epochTransitionCache.js";
19
+ import {CachedBeaconStateAllForks, CachedBeaconStateAltair} from "../types.js";
20
+ import {
21
+ FLAG_ELIGIBLE_ATTESTER,
22
+ FLAG_PREV_HEAD_ATTESTER_UNSLASHED,
23
+ FLAG_PREV_SOURCE_ATTESTER_UNSLASHED,
24
+ FLAG_PREV_TARGET_ATTESTER_UNSLASHED,
25
+ hasMarkers,
26
+ isInInactivityLeak,
27
+ } from "../util/index.js";
28
+
29
+ /** Attestations penalty with respect to effective balance in Gwei */
30
+ type AttestationsPenalty = {target: number; source: number; effectiveBalance: number};
31
+
32
+ const defaultAttestationsReward = {head: 0, target: 0, source: 0, inclusionDelay: 0, inactivity: 0};
33
+ const defaultAttestationsPenalty = {target: 0, source: 0};
34
+
35
+ export async function computeAttestationsRewards(
36
+ config: BeaconConfig,
37
+ pubkey2index: PubkeyIndexMap,
38
+ state: CachedBeaconStateAllForks,
39
+ validatorIds?: (ValidatorIndex | string)[]
40
+ ): Promise<rewards.AttestationsRewards> {
41
+ const fork = config.getForkName(state.slot);
42
+ if (fork === ForkName.phase0) {
43
+ throw Error("Unsupported fork. Attestations rewards calculation is not available in phase0");
44
+ }
45
+
46
+ const stateAltair = state as CachedBeaconStateAltair;
47
+ const transitionCache = beforeProcessEpoch(stateAltair);
48
+
49
+ const [idealRewards, penalties] = computeIdealAttestationsRewardsAndPenaltiesAltair(
50
+ config,
51
+ stateAltair,
52
+ transitionCache
53
+ );
54
+ const totalRewards = computeTotalAttestationsRewardsAltair(
55
+ config,
56
+ pubkey2index,
57
+ stateAltair,
58
+ transitionCache,
59
+ idealRewards,
60
+ penalties,
61
+ validatorIds
62
+ );
63
+
64
+ return {idealRewards, totalRewards};
65
+ }
66
+
67
+ function computeIdealAttestationsRewardsAndPenaltiesAltair(
68
+ config: BeaconConfig,
69
+ state: CachedBeaconStateAllForks,
70
+ transitionCache: EpochTransitionCache
71
+ ): [rewards.IdealAttestationsReward[], AttestationsPenalty[]] {
72
+ const baseRewardPerIncrement = transitionCache.baseRewardPerIncrement;
73
+ const activeBalanceByIncrement = transitionCache.totalActiveStakeByIncrement;
74
+ const fork = config.getForkName(state.slot);
75
+ const maxEffectiveBalance = isForkPostElectra(fork) ? MAX_EFFECTIVE_BALANCE_ELECTRA : MAX_EFFECTIVE_BALANCE;
76
+ const maxEffectiveBalanceByIncrement = Math.floor(maxEffectiveBalance / EFFECTIVE_BALANCE_INCREMENT);
77
+
78
+ const idealRewards = Array.from({length: maxEffectiveBalanceByIncrement + 1}, (_, effectiveBalanceByIncrement) => ({
79
+ ...defaultAttestationsReward,
80
+ effectiveBalance: effectiveBalanceByIncrement * EFFECTIVE_BALANCE_INCREMENT,
81
+ }));
82
+
83
+ const attestationsPenalties: AttestationsPenalty[] = Array.from(
84
+ {length: maxEffectiveBalanceByIncrement + 1},
85
+ (_, effectiveBalanceByIncrement) => ({
86
+ ...defaultAttestationsPenalty,
87
+ effectiveBalance: effectiveBalanceByIncrement * EFFECTIVE_BALANCE_INCREMENT,
88
+ })
89
+ );
90
+
91
+ for (let i = 0; i < PARTICIPATION_FLAG_WEIGHTS.length; i++) {
92
+ const weight = PARTICIPATION_FLAG_WEIGHTS[i];
93
+
94
+ let unslashedStakeByIncrement: number;
95
+ let flagName: keyof rewards.IdealAttestationsReward;
96
+
97
+ switch (i) {
98
+ case TIMELY_SOURCE_FLAG_INDEX: {
99
+ unslashedStakeByIncrement = transitionCache.prevEpochUnslashedStake.sourceStakeByIncrement;
100
+ flagName = "source";
101
+ break;
102
+ }
103
+ case TIMELY_TARGET_FLAG_INDEX: {
104
+ unslashedStakeByIncrement = transitionCache.prevEpochUnslashedStake.targetStakeByIncrement;
105
+ flagName = "target";
106
+ break;
107
+ }
108
+ case TIMELY_HEAD_FLAG_INDEX: {
109
+ unslashedStakeByIncrement = transitionCache.prevEpochUnslashedStake.headStakeByIncrement;
110
+ flagName = "head";
111
+ break;
112
+ }
113
+ default: {
114
+ throw Error(`Unable to retrieve unslashed stake. Unknown participation flag index: ${i}`);
115
+ }
116
+ }
117
+
118
+ for (
119
+ let effectiveBalanceByIncrement = 0;
120
+ effectiveBalanceByIncrement <= maxEffectiveBalanceByIncrement;
121
+ effectiveBalanceByIncrement++
122
+ ) {
123
+ const baseReward = effectiveBalanceByIncrement * baseRewardPerIncrement;
124
+ const rewardNumerator = baseReward * weight * unslashedStakeByIncrement;
125
+ // Both idealReward and penalty are rounded to nearest integer. Loss of precision is minimal as unit is gwei
126
+ const idealReward = Math.round(rewardNumerator / activeBalanceByIncrement / WEIGHT_DENOMINATOR);
127
+ const penalty = Math.round((baseReward * weight) / WEIGHT_DENOMINATOR); // Positive number indicates penalty
128
+
129
+ const idealAttestationsReward = idealRewards[effectiveBalanceByIncrement];
130
+ idealAttestationsReward[flagName] = isInInactivityLeak(state) ? 0 : idealReward; // No attestations rewards during inactivity leak
131
+
132
+ if (flagName !== "head") {
133
+ const attestationPenalty = attestationsPenalties[effectiveBalanceByIncrement];
134
+ attestationPenalty[flagName] = penalty;
135
+ }
136
+ }
137
+ }
138
+
139
+ return [idealRewards, attestationsPenalties];
140
+ }
141
+
142
+ // Same calculation as `getRewardsAndPenaltiesAltair` but returns the breakdown of rewards instead of aggregated
143
+ function computeTotalAttestationsRewardsAltair(
144
+ config: BeaconConfig,
145
+ pubkey2index: PubkeyIndexMap,
146
+ state: CachedBeaconStateAltair,
147
+ transitionCache: EpochTransitionCache,
148
+ idealRewards: rewards.IdealAttestationsReward[],
149
+ penalties: AttestationsPenalty[],
150
+ validatorIds: (ValidatorIndex | string)[] = []
151
+ ): rewards.TotalAttestationsReward[] {
152
+ const rewards = [];
153
+ const {flags} = transitionCache;
154
+ const {epochCtx} = state;
155
+ const validatorIndices = validatorIds
156
+ .map((id) => (typeof id === "number" ? id : pubkey2index.get(fromHex(id))))
157
+ .filter((index) => index !== undefined); // Validator indices to include in the result
158
+
159
+ const inactivityPenaltyDenominator = config.INACTIVITY_SCORE_BIAS * INACTIVITY_PENALTY_QUOTIENT_ALTAIR;
160
+
161
+ for (let i = 0; i < flags.length; i++) {
162
+ if (validatorIndices.length && !validatorIndices.includes(i)) {
163
+ continue;
164
+ }
165
+
166
+ const flag = flags[i];
167
+ if (!hasMarkers(flag, FLAG_ELIGIBLE_ATTESTER)) {
168
+ continue;
169
+ }
170
+
171
+ const effectiveBalanceIncrement = epochCtx.effectiveBalanceIncrements[i];
172
+
173
+ const currentRewards = {...defaultAttestationsReward, validatorIndex: i};
174
+
175
+ if (hasMarkers(flag, FLAG_PREV_SOURCE_ATTESTER_UNSLASHED)) {
176
+ currentRewards.source = idealRewards[effectiveBalanceIncrement].source;
177
+ } else {
178
+ currentRewards.source = penalties[effectiveBalanceIncrement].source * -1; // Negative reward to indicate penalty
179
+ }
180
+
181
+ if (hasMarkers(flag, FLAG_PREV_TARGET_ATTESTER_UNSLASHED)) {
182
+ currentRewards.target = idealRewards[effectiveBalanceIncrement].target;
183
+ } else {
184
+ currentRewards.target = penalties[effectiveBalanceIncrement].target * -1;
185
+
186
+ // Also incur inactivity penalty if not voting target correctly
187
+ const inactivityPenaltyNumerator =
188
+ effectiveBalanceIncrement * EFFECTIVE_BALANCE_INCREMENT * state.inactivityScores.get(i);
189
+ currentRewards.inactivity = Math.floor(inactivityPenaltyNumerator / inactivityPenaltyDenominator) * -1;
190
+ }
191
+
192
+ if (hasMarkers(flag, FLAG_PREV_HEAD_ATTESTER_UNSLASHED)) {
193
+ currentRewards.head = idealRewards[effectiveBalanceIncrement].head;
194
+ }
195
+
196
+ rewards.push(currentRewards);
197
+ }
198
+
199
+ return rewards;
200
+ }
@@ -0,0 +1,150 @@
1
+ import {BeaconConfig} from "@lodestar/config";
2
+ import {
3
+ ForkName,
4
+ WHISTLEBLOWER_REWARD_QUOTIENT,
5
+ WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA,
6
+ isForkPostElectra,
7
+ } from "@lodestar/params";
8
+ import {BeaconBlock, altair, phase0, rewards} from "@lodestar/types";
9
+ import {processAttestationsAltair} from "../block/processAttestationsAltair.js";
10
+ import {RewardCache} from "../cache/rewardCache.js";
11
+ import {CachedBeaconStateAllForks, CachedBeaconStateAltair, CachedBeaconStatePhase0} from "../cache/stateCache.js";
12
+ import {getAttesterSlashableIndices} from "../util/attestation.js";
13
+
14
+ type SubRewardValue = number; // All reward values should be integer
15
+
16
+ /**
17
+ * Calculate total proposer block rewards given block and the beacon state of the same slot before the block is applied (preState)
18
+ * postState can be passed in to read reward cache if available
19
+ * Standard (Non MEV) rewards for proposing a block consists of:
20
+ * 1) Including attestations from (beacon) committee
21
+ * 2) Including attestations from sync committee
22
+ * 3) Reporting slashable behaviours from proposer and attester
23
+ */
24
+ export async function computeBlockRewards(
25
+ config: BeaconConfig,
26
+ block: BeaconBlock,
27
+ preStateIn: CachedBeaconStateAllForks,
28
+ proposerRewards?: RewardCache
29
+ ): Promise<rewards.BlockRewards> {
30
+ const preState = preStateIn.clone();
31
+
32
+ const fork = config.getForkName(block.slot);
33
+ const {attestations: cachedAttestationsReward = 0, syncAggregate: cachedSyncAggregateReward = 0} =
34
+ proposerRewards ?? {};
35
+ let blockAttestationReward = cachedAttestationsReward;
36
+ let syncAggregateReward = cachedSyncAggregateReward;
37
+
38
+ if (blockAttestationReward === 0) {
39
+ blockAttestationReward =
40
+ fork === ForkName.phase0
41
+ ? computeBlockAttestationRewardPhase0(block as phase0.BeaconBlock, preState as CachedBeaconStatePhase0)
42
+ : computeBlockAttestationRewardAltair(config, block as altair.BeaconBlock, preState as CachedBeaconStateAltair);
43
+ }
44
+
45
+ if (syncAggregateReward === 0) {
46
+ syncAggregateReward = computeSyncAggregateReward(block as altair.BeaconBlock, preState as CachedBeaconStateAltair);
47
+ }
48
+
49
+ const blockProposerSlashingReward = computeBlockProposerSlashingReward(fork, block, preState);
50
+ const blockAttesterSlashingReward = computeBlockAttesterSlashingReward(fork, block, preState);
51
+
52
+ const total =
53
+ blockAttestationReward + syncAggregateReward + blockProposerSlashingReward + blockAttesterSlashingReward;
54
+
55
+ return {
56
+ proposerIndex: block.proposerIndex,
57
+ total,
58
+ attestations: blockAttestationReward,
59
+ syncAggregate: syncAggregateReward,
60
+ proposerSlashings: blockProposerSlashingReward,
61
+ attesterSlashings: blockAttesterSlashingReward,
62
+ };
63
+ }
64
+
65
+ /**
66
+ * TODO: Calculate rewards received by block proposer for including attestations.
67
+ */
68
+ function computeBlockAttestationRewardPhase0(
69
+ _block: phase0.BeaconBlock,
70
+ _preState: CachedBeaconStatePhase0
71
+ ): SubRewardValue {
72
+ throw new Error("Unsupported fork! Block attestation reward calculation is not available in phase0");
73
+ }
74
+
75
+ /**
76
+ * Calculate rewards received by block proposer for including attestations since Altair.
77
+ * Reuses `processAttestationsAltair()`. Has dependency on RewardCache
78
+ */
79
+ function computeBlockAttestationRewardAltair(
80
+ config: BeaconConfig,
81
+ block: altair.BeaconBlock,
82
+ preState: CachedBeaconStateAltair
83
+ ): SubRewardValue {
84
+ const fork = config.getForkSeq(block.slot);
85
+ const {attestations} = block.body;
86
+
87
+ processAttestationsAltair(fork, preState, attestations, false);
88
+
89
+ return preState.proposerRewards.attestations;
90
+ }
91
+
92
+ function computeSyncAggregateReward(block: altair.BeaconBlock, preState: CachedBeaconStateAltair): SubRewardValue {
93
+ if (block.body.syncAggregate !== undefined) {
94
+ const {syncCommitteeBits} = block.body.syncAggregate;
95
+ const {syncProposerReward} = preState.epochCtx;
96
+
97
+ return syncCommitteeBits.getTrueBitIndexes().length * Math.floor(syncProposerReward); // syncProposerReward should already be integer
98
+ }
99
+
100
+ return 0; // phase0 block does not have syncAggregate
101
+ }
102
+
103
+ /**
104
+ * Calculate rewards received by block proposer for including proposer slashings.
105
+ * All proposer slashing rewards go to block proposer and none to whistleblower as of Deneb
106
+ */
107
+ function computeBlockProposerSlashingReward(
108
+ fork: ForkName,
109
+ block: BeaconBlock,
110
+ state: CachedBeaconStateAllForks
111
+ ): SubRewardValue {
112
+ let proposerSlashingReward = 0;
113
+
114
+ for (const proposerSlashing of block.body.proposerSlashings) {
115
+ const offendingProposerIndex = proposerSlashing.signedHeader1.message.proposerIndex;
116
+ const offendingProposerBalance = state.validators.getReadonly(offendingProposerIndex).effectiveBalance;
117
+ const whistleblowerRewardQuotient = isForkPostElectra(fork)
118
+ ? WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA
119
+ : WHISTLEBLOWER_REWARD_QUOTIENT;
120
+
121
+ proposerSlashingReward += Math.floor(offendingProposerBalance / whistleblowerRewardQuotient);
122
+ }
123
+
124
+ return proposerSlashingReward;
125
+ }
126
+
127
+ /**
128
+ * Calculate rewards received by block proposer for including attester slashings.
129
+ * All attester slashing rewards go to block proposer and none to whistleblower as of Deneb
130
+ */
131
+ function computeBlockAttesterSlashingReward(
132
+ fork: ForkName,
133
+ block: BeaconBlock,
134
+ preState: CachedBeaconStateAllForks
135
+ ): SubRewardValue {
136
+ let attesterSlashingReward = 0;
137
+
138
+ for (const attesterSlashing of block.body.attesterSlashings) {
139
+ for (const offendingAttesterIndex of getAttesterSlashableIndices(attesterSlashing)) {
140
+ const offendingAttesterBalance = preState.validators.getReadonly(offendingAttesterIndex).effectiveBalance;
141
+ const whistleblowerRewardQuotient = isForkPostElectra(fork)
142
+ ? WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA
143
+ : WHISTLEBLOWER_REWARD_QUOTIENT;
144
+
145
+ attesterSlashingReward += Math.floor(offendingAttesterBalance / whistleblowerRewardQuotient);
146
+ }
147
+ }
148
+
149
+ return attesterSlashingReward;
150
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./attestationsRewards.js";
2
+ export * from "./blockRewards.js";
3
+ export * from "./syncCommitteeRewards.js";
@@ -0,0 +1,56 @@
1
+ import {BeaconConfig} from "@lodestar/config";
2
+ import {ForkName, SYNC_COMMITTEE_SIZE} from "@lodestar/params";
3
+ import {BeaconBlock, ValidatorIndex, altair, rewards} from "@lodestar/types";
4
+ import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
5
+ import {CachedBeaconStateAllForks, CachedBeaconStateAltair} from "../cache/stateCache.js";
6
+
7
+ export async function computeSyncCommitteeRewards(
8
+ config: BeaconConfig,
9
+ index2pubkey: Index2PubkeyCache,
10
+ block: BeaconBlock,
11
+ preState: CachedBeaconStateAllForks,
12
+ validatorIds: (ValidatorIndex | string)[] = []
13
+ ): Promise<rewards.SyncCommitteeRewards> {
14
+ const fork = config.getForkName(block.slot);
15
+ if (fork === ForkName.phase0) {
16
+ throw Error("Cannot get sync rewards as phase0 block does not have sync committee");
17
+ }
18
+
19
+ const altairBlock = block as altair.BeaconBlock;
20
+ const preStateAltair = preState.clone() as CachedBeaconStateAltair;
21
+
22
+ // Bound syncCommitteeValidatorIndices in case it goes beyond SYNC_COMMITTEE_SIZE just to be safe
23
+ const syncCommitteeValidatorIndices = preStateAltair.epochCtx.currentSyncCommitteeIndexed.validatorIndices.slice(
24
+ 0,
25
+ SYNC_COMMITTEE_SIZE
26
+ );
27
+ const {syncParticipantReward} = preStateAltair.epochCtx;
28
+ const {syncCommitteeBits} = altairBlock.body.syncAggregate;
29
+
30
+ // Track reward deltas per validator (can appear multiple times in sync committee)
31
+ const rewardDeltas: Map<ValidatorIndex, number> = new Map();
32
+
33
+ // Iterate by position index to correctly access syncCommitteeBits
34
+ for (let i = 0; i < syncCommitteeValidatorIndices.length; i++) {
35
+ const validatorIndex = syncCommitteeValidatorIndices[i];
36
+ const currentDelta = rewardDeltas.get(validatorIndex) ?? 0;
37
+ if (syncCommitteeBits.get(i)) {
38
+ // Positive rewards for participants
39
+ rewardDeltas.set(validatorIndex, currentDelta + syncParticipantReward);
40
+ } else {
41
+ // Negative rewards for non participants
42
+ rewardDeltas.set(validatorIndex, currentDelta - syncParticipantReward);
43
+ }
44
+ }
45
+
46
+ const rewards = Array.from(rewardDeltas, ([validatorIndex, reward]) => ({validatorIndex, reward}));
47
+
48
+ if (validatorIds.length) {
49
+ const filtersSet = new Set(validatorIds);
50
+ return rewards.filter(
51
+ (reward) => filtersSet.has(reward.validatorIndex) || filtersSet.has(index2pubkey[reward.validatorIndex].toHex())
52
+ );
53
+ }
54
+
55
+ return rewards;
56
+ }
@@ -1,19 +1,20 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {DOMAIN_BEACON_ATTESTER} from "@lodestar/params";
3
- import {AttesterSlashing, IndexedAttestationBigint, SignedBeaconBlock, ssz} from "@lodestar/types";
3
+ import {AttesterSlashing, IndexedAttestationBigint, SignedBeaconBlock, Slot, ssz} from "@lodestar/types";
4
4
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
5
- import {CachedBeaconStateAllForks} from "../types.js";
6
5
  import {ISignatureSet, SignatureSetType, computeSigningRoot, computeStartSlotAtEpoch} from "../util/index.js";
7
6
 
8
7
  /** Get signature sets from all AttesterSlashing objects in a block */
9
8
  export function getAttesterSlashingsSignatureSets(
10
9
  config: BeaconConfig,
11
10
  index2pubkey: Index2PubkeyCache,
12
- state: CachedBeaconStateAllForks,
13
11
  signedBlock: SignedBeaconBlock
14
12
  ): ISignatureSet[] {
13
+ // the getDomain() api requires the state slot as 1st param, however it's the same to block.slot in state-transition
14
+ // and the same epoch when we verify blocks in batch in beacon-node. So we can safely use block.slot here.
15
+ const blockSlot = signedBlock.message.slot;
15
16
  return signedBlock.message.body.attesterSlashings.flatMap((attesterSlashing) =>
16
- getAttesterSlashingSignatureSets(config, index2pubkey, state, attesterSlashing)
17
+ getAttesterSlashingSignatureSets(config, index2pubkey, blockSlot, attesterSlashing)
17
18
  );
18
19
  }
19
20
 
@@ -21,22 +22,22 @@ export function getAttesterSlashingsSignatureSets(
21
22
  export function getAttesterSlashingSignatureSets(
22
23
  config: BeaconConfig,
23
24
  index2pubkey: Index2PubkeyCache,
24
- state: CachedBeaconStateAllForks,
25
+ stateSlot: Slot,
25
26
  attesterSlashing: AttesterSlashing
26
27
  ): ISignatureSet[] {
27
28
  return [attesterSlashing.attestation1, attesterSlashing.attestation2].map((attestation) =>
28
- getIndexedAttestationBigintSignatureSet(config, index2pubkey, state, attestation)
29
+ getIndexedAttestationBigintSignatureSet(config, index2pubkey, stateSlot, attestation)
29
30
  );
30
31
  }
31
32
 
32
33
  export function getIndexedAttestationBigintSignatureSet(
33
34
  config: BeaconConfig,
34
35
  index2pubkey: Index2PubkeyCache,
35
- state: CachedBeaconStateAllForks,
36
+ stateSlot: Slot,
36
37
  indexedAttestation: IndexedAttestationBigint
37
38
  ): ISignatureSet {
38
- const slot = computeStartSlotAtEpoch(Number(indexedAttestation.data.target.epoch as bigint));
39
- const domain = config.getDomain(state.slot, DOMAIN_BEACON_ATTESTER, slot);
39
+ const messageSlot = computeStartSlotAtEpoch(Number(indexedAttestation.data.target.epoch as bigint));
40
+ const domain = config.getDomain(stateSlot, DOMAIN_BEACON_ATTESTER, messageSlot);
40
41
 
41
42
  return {
42
43
  type: SignatureSetType.aggregate,
@@ -2,14 +2,13 @@ import {PublicKey} from "@chainsafe/blst";
2
2
  import {BeaconConfig} from "@lodestar/config";
3
3
  import {DOMAIN_BLS_TO_EXECUTION_CHANGE, ForkName} from "@lodestar/params";
4
4
  import {capella, ssz} from "@lodestar/types";
5
- import {CachedBeaconStateAllForks} from "../types.js";
6
5
  import {ISignatureSet, SignatureSetType, computeSigningRoot, verifySignatureSet} from "../util/index.js";
7
6
 
8
7
  export function verifyBlsToExecutionChangeSignature(
9
- state: CachedBeaconStateAllForks,
8
+ config: BeaconConfig,
10
9
  signedBLSToExecutionChange: capella.SignedBLSToExecutionChange
11
10
  ): boolean {
12
- return verifySignatureSet(getBlsToExecutionChangeSignatureSet(state.config, signedBLSToExecutionChange));
11
+ return verifySignatureSet(getBlsToExecutionChangeSignatureSet(config, signedBLSToExecutionChange));
13
12
  }
14
13
 
15
14
  /**
@@ -3,7 +3,7 @@ import {ForkSeq} from "@lodestar/params";
3
3
  import {IndexedAttestation, SignedBeaconBlock, altair, capella} from "@lodestar/types";
4
4
  import {getSyncCommitteeSignatureSet} from "../block/processSyncCommittee.js";
5
5
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
6
- import {CachedBeaconStateAllForks, CachedBeaconStateAltair} from "../types.js";
6
+ import {SyncCommitteeCache} from "../cache/syncCommitteeCache.js";
7
7
  import {ISignatureSet} from "../util/index.js";
8
8
  import {getAttesterSlashingsSignatureSets} from "./attesterSlashings.js";
9
9
  import {getBlsToExecutionChangeSignatureSets} from "./blsToExecutionChange.js";
@@ -29,7 +29,7 @@ export * from "./voluntaryExits.js";
29
29
  export function getBlockSignatureSets(
30
30
  config: BeaconConfig,
31
31
  index2pubkey: Index2PubkeyCache,
32
- state: CachedBeaconStateAllForks,
32
+ currentSyncCommitteeIndexed: SyncCommitteeCache,
33
33
  signedBlock: SignedBeaconBlock,
34
34
  indexedAttestations: IndexedAttestation[],
35
35
  opts?: {
@@ -38,18 +38,18 @@ export function getBlockSignatureSets(
38
38
  }
39
39
  ): ISignatureSet[] {
40
40
  // fork based validations
41
- const fork = state.config.getForkSeq(signedBlock.message.slot);
41
+ const fork = config.getForkSeq(signedBlock.message.slot);
42
42
 
43
43
  const signatureSets = [
44
- getRandaoRevealSignatureSet(config, index2pubkey, state, signedBlock.message),
45
- ...getProposerSlashingsSignatureSets(config, index2pubkey, state, signedBlock),
46
- ...getAttesterSlashingsSignatureSets(config, index2pubkey, state, signedBlock),
47
- ...getAttestationsSignatureSets(config, index2pubkey, state, signedBlock, indexedAttestations),
48
- ...getVoluntaryExitsSignatureSets(config, index2pubkey, state, signedBlock),
44
+ getRandaoRevealSignatureSet(config, index2pubkey, signedBlock.message),
45
+ ...getProposerSlashingsSignatureSets(config, index2pubkey, signedBlock),
46
+ ...getAttesterSlashingsSignatureSets(config, index2pubkey, signedBlock),
47
+ ...getAttestationsSignatureSets(config, index2pubkey, signedBlock, indexedAttestations),
48
+ ...getVoluntaryExitsSignatureSets(config, index2pubkey, signedBlock),
49
49
  ];
50
50
 
51
51
  if (!opts?.skipProposerSignature) {
52
- signatureSets.push(getBlockProposerSignatureSet(config, index2pubkey, state, signedBlock));
52
+ signatureSets.push(getBlockProposerSignatureSet(config, index2pubkey, signedBlock));
53
53
  }
54
54
 
55
55
  // Only after altair fork, validate tSyncCommitteeSignature
@@ -57,7 +57,7 @@ export function getBlockSignatureSets(
57
57
  const syncCommitteeSignatureSet = getSyncCommitteeSignatureSet(
58
58
  config,
59
59
  index2pubkey,
60
- state as CachedBeaconStateAltair,
60
+ currentSyncCommitteeIndexed,
61
61
  (signedBlock as altair.SignedBeaconBlock).message
62
62
  );
63
63
  // There may be no participants in this syncCommitteeSignature, so it must not be validated
@@ -69,7 +69,7 @@ export function getBlockSignatureSets(
69
69
  // only after capella fork
70
70
  if (fork >= ForkSeq.capella) {
71
71
  const blsToExecutionChangeSignatureSets = getBlsToExecutionChangeSignatureSets(
72
- state.config,
72
+ config,
73
73
  signedBlock as capella.SignedBeaconBlock
74
74
  );
75
75
  if (blsToExecutionChangeSignatureSets.length > 0) {
@@ -1,8 +1,7 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {DOMAIN_BEACON_ATTESTER} from "@lodestar/params";
3
- import {IndexedAttestation, SignedBeaconBlock, phase0, ssz} from "@lodestar/types";
3
+ import {IndexedAttestation, SignedBeaconBlock, Slot, phase0, ssz} from "@lodestar/types";
4
4
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
5
- import {CachedBeaconStateAllForks} from "../types.js";
6
5
  import {
7
6
  ISignatureSet,
8
7
  computeSigningRoot,
@@ -12,11 +11,11 @@ import {
12
11
 
13
12
  export function getAttestationDataSigningRoot(
14
13
  config: BeaconConfig,
15
- state: CachedBeaconStateAllForks,
14
+ stateSlot: Slot,
16
15
  data: phase0.AttestationData
17
16
  ): Uint8Array {
18
- const slot = computeStartSlotAtEpoch(data.target.epoch);
19
- const domain = config.getDomain(state.slot, DOMAIN_BEACON_ATTESTER, slot);
17
+ const messageSlot = computeStartSlotAtEpoch(data.target.epoch);
18
+ const domain = config.getDomain(stateSlot, DOMAIN_BEACON_ATTESTER, messageSlot);
20
19
 
21
20
  return computeSigningRoot(ssz.phase0.AttestationData, data, domain);
22
21
  }
@@ -24,13 +23,13 @@ export function getAttestationDataSigningRoot(
24
23
  export function getAttestationWithIndicesSignatureSet(
25
24
  config: BeaconConfig,
26
25
  index2pubkey: Index2PubkeyCache,
27
- state: CachedBeaconStateAllForks,
26
+ stateSlot: Slot,
28
27
  attestation: Pick<phase0.Attestation, "data" | "signature">,
29
28
  attestingIndices: number[]
30
29
  ): ISignatureSet {
31
30
  return createAggregateSignatureSetFromComponents(
32
31
  attestingIndices.map((i) => index2pubkey[i]),
33
- getAttestationDataSigningRoot(config, state, attestation.data),
32
+ getAttestationDataSigningRoot(config, stateSlot, attestation.data),
34
33
  attestation.signature
35
34
  );
36
35
  }
@@ -38,13 +37,13 @@ export function getAttestationWithIndicesSignatureSet(
38
37
  export function getIndexedAttestationSignatureSet(
39
38
  config: BeaconConfig,
40
39
  index2pubkey: Index2PubkeyCache,
41
- state: CachedBeaconStateAllForks,
40
+ stateSlot: Slot,
42
41
  indexedAttestation: IndexedAttestation
43
42
  ): ISignatureSet {
44
43
  return getAttestationWithIndicesSignatureSet(
45
44
  config,
46
45
  index2pubkey,
47
- state,
46
+ stateSlot,
48
47
  indexedAttestation,
49
48
  indexedAttestation.attestingIndices
50
49
  );
@@ -53,7 +52,6 @@ export function getIndexedAttestationSignatureSet(
53
52
  export function getAttestationsSignatureSets(
54
53
  config: BeaconConfig,
55
54
  index2pubkey: Index2PubkeyCache,
56
- state: CachedBeaconStateAllForks,
57
55
  signedBlock: SignedBeaconBlock,
58
56
  indexedAttestations: IndexedAttestation[]
59
57
  ): ISignatureSet[] {
@@ -62,7 +60,10 @@ export function getAttestationsSignatureSets(
62
60
  `Indexed attestations length mismatch: got ${indexedAttestations.length}, expected ${signedBlock.message.body.attestations.length}`
63
61
  );
64
62
  }
63
+ // the getDomain() api requires the state slot as 1st param, however it's the same to block.slot in state-transition
64
+ // and the same epoch when we verify blocks in batch in beacon-node. So we can safely use block.slot here.
65
+ const blockSlot = signedBlock.message.slot;
65
66
  return indexedAttestations.map((indexedAttestation) =>
66
- getIndexedAttestationSignatureSet(config, index2pubkey, state, indexedAttestation)
67
+ getIndexedAttestationSignatureSet(config, index2pubkey, blockSlot, indexedAttestation)
67
68
  );
68
69
  }