@lodestar/state-transition 1.39.0-dev.7e9e7caf38 → 1.39.0-dev.86298a43e6

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 (86) hide show
  1. package/lib/block/isValidIndexedAttestation.d.ts.map +1 -1
  2. package/lib/block/isValidIndexedAttestation.js +2 -2
  3. package/lib/block/isValidIndexedAttestation.js.map +1 -1
  4. package/lib/block/processAttestationsAltair.js +1 -1
  5. package/lib/block/processAttestationsAltair.js.map +1 -1
  6. package/lib/block/processProposerSlashing.js +1 -1
  7. package/lib/block/processProposerSlashing.js.map +1 -1
  8. package/lib/block/processRandao.js +2 -2
  9. package/lib/block/processRandao.js.map +1 -1
  10. package/lib/block/processSyncCommittee.d.ts +2 -1
  11. package/lib/block/processSyncCommittee.d.ts.map +1 -1
  12. package/lib/block/processSyncCommittee.js +6 -4
  13. package/lib/block/processSyncCommittee.js.map +1 -1
  14. package/lib/block/processVoluntaryExit.js +1 -1
  15. package/lib/block/processVoluntaryExit.js.map +1 -1
  16. package/lib/index.d.ts +2 -1
  17. package/lib/index.d.ts.map +1 -1
  18. package/lib/index.js +2 -0
  19. package/lib/index.js.map +1 -1
  20. package/lib/rewards/attestationsRewards.d.ts +6 -0
  21. package/lib/rewards/attestationsRewards.d.ts.map +1 -0
  22. package/lib/rewards/attestationsRewards.js +113 -0
  23. package/lib/rewards/attestationsRewards.js.map +1 -0
  24. package/lib/rewards/blockRewards.d.ts +13 -0
  25. package/lib/rewards/blockRewards.d.ts.map +1 -0
  26. package/lib/rewards/blockRewards.js +95 -0
  27. package/lib/rewards/blockRewards.js.map +1 -0
  28. package/lib/rewards/index.d.ts +4 -0
  29. package/lib/rewards/index.d.ts.map +1 -0
  30. package/lib/rewards/index.js +4 -0
  31. package/lib/rewards/index.js.map +1 -0
  32. package/lib/rewards/syncCommitteeRewards.d.ts +6 -0
  33. package/lib/rewards/syncCommitteeRewards.d.ts.map +1 -0
  34. package/lib/rewards/syncCommitteeRewards.js +36 -0
  35. package/lib/rewards/syncCommitteeRewards.js.map +1 -0
  36. package/lib/signatureSets/attesterSlashings.d.ts +4 -5
  37. package/lib/signatureSets/attesterSlashings.d.ts.map +1 -1
  38. package/lib/signatureSets/attesterSlashings.js +10 -7
  39. package/lib/signatureSets/attesterSlashings.js.map +1 -1
  40. package/lib/signatureSets/index.d.ts +2 -2
  41. package/lib/signatureSets/index.d.ts.map +1 -1
  42. package/lib/signatureSets/index.js +10 -10
  43. package/lib/signatureSets/index.js.map +1 -1
  44. package/lib/signatureSets/indexedAttestation.d.ts +5 -6
  45. package/lib/signatureSets/indexedAttestation.d.ts.map +1 -1
  46. package/lib/signatureSets/indexedAttestation.js +12 -9
  47. package/lib/signatureSets/indexedAttestation.js.map +1 -1
  48. package/lib/signatureSets/proposer.d.ts +2 -2
  49. package/lib/signatureSets/proposer.d.ts.map +1 -1
  50. package/lib/signatureSets/proposer.js +7 -4
  51. package/lib/signatureSets/proposer.js.map +1 -1
  52. package/lib/signatureSets/proposerSlashings.d.ts +3 -4
  53. package/lib/signatureSets/proposerSlashings.d.ts.map +1 -1
  54. package/lib/signatureSets/proposerSlashings.js +7 -4
  55. package/lib/signatureSets/proposerSlashings.js.map +1 -1
  56. package/lib/signatureSets/randao.d.ts +2 -3
  57. package/lib/signatureSets/randao.d.ts.map +1 -1
  58. package/lib/signatureSets/randao.js +6 -4
  59. package/lib/signatureSets/randao.js.map +1 -1
  60. package/lib/signatureSets/voluntaryExits.d.ts +4 -5
  61. package/lib/signatureSets/voluntaryExits.d.ts.map +1 -1
  62. package/lib/signatureSets/voluntaryExits.js +10 -7
  63. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  64. package/lib/stateTransition.d.ts.map +1 -1
  65. package/lib/stateTransition.js +1 -2
  66. package/lib/stateTransition.js.map +1 -1
  67. package/package.json +6 -6
  68. package/src/block/isValidIndexedAttestation.ts +4 -2
  69. package/src/block/processAttestationsAltair.ts +1 -1
  70. package/src/block/processProposerSlashing.ts +1 -1
  71. package/src/block/processRandao.ts +2 -2
  72. package/src/block/processSyncCommittee.ts +7 -4
  73. package/src/block/processVoluntaryExit.ts +1 -1
  74. package/src/index.ts +2 -2
  75. package/src/rewards/attestationsRewards.ts +200 -0
  76. package/src/rewards/blockRewards.ts +147 -0
  77. package/src/rewards/index.ts +3 -0
  78. package/src/rewards/syncCommitteeRewards.ts +59 -0
  79. package/src/signatureSets/attesterSlashings.ts +10 -9
  80. package/src/signatureSets/index.ts +11 -11
  81. package/src/signatureSets/indexedAttestation.ts +12 -11
  82. package/src/signatureSets/proposer.ts +5 -4
  83. package/src/signatureSets/proposerSlashings.ts +7 -6
  84. package/src/signatureSets/randao.ts +4 -5
  85. package/src/signatureSets/voluntaryExits.ts +10 -9
  86. package/src/stateTransition.ts +1 -4
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.39.0-dev.7e9e7caf38",
14
+ "version": "1.39.0-dev.86298a43e6",
15
15
  "type": "module",
16
16
  "exports": {
17
17
  ".": {
@@ -62,10 +62,10 @@
62
62
  "@chainsafe/pubkey-index-map": "^3.0.0",
63
63
  "@chainsafe/ssz": "^1.2.2",
64
64
  "@chainsafe/swap-or-not-shuffle": "^1.2.1",
65
- "@lodestar/config": "1.39.0-dev.7e9e7caf38",
66
- "@lodestar/params": "1.39.0-dev.7e9e7caf38",
67
- "@lodestar/types": "1.39.0-dev.7e9e7caf38",
68
- "@lodestar/utils": "1.39.0-dev.7e9e7caf38",
65
+ "@lodestar/config": "1.39.0-dev.86298a43e6",
66
+ "@lodestar/params": "1.39.0-dev.86298a43e6",
67
+ "@lodestar/types": "1.39.0-dev.86298a43e6",
68
+ "@lodestar/utils": "1.39.0-dev.86298a43e6",
69
69
  "bigint-buffer": "^1.1.5"
70
70
  },
71
71
  "keywords": [
@@ -74,5 +74,5 @@
74
74
  "beacon",
75
75
  "blockchain"
76
76
  ],
77
- "gitHead": "93dd5cb6c00cbb7945b0d35e689d94e7c5d814b1"
77
+ "gitHead": "55dd258fb9d9a8eaad756c34d331ebe0ab71995f"
78
78
  }
@@ -21,7 +21,7 @@ export function isValidIndexedAttestation(
21
21
  }
22
22
 
23
23
  if (verifySignature) {
24
- return verifySignatureSet(getIndexedAttestationSignatureSet(config, index2pubkey, state, indexedAttestation));
24
+ return verifySignatureSet(getIndexedAttestationSignatureSet(config, index2pubkey, state.slot, indexedAttestation));
25
25
  }
26
26
  return true;
27
27
  }
@@ -38,7 +38,9 @@ export function isValidIndexedAttestationBigint(
38
38
  }
39
39
 
40
40
  if (verifySignature) {
41
- return verifySignatureSet(getIndexedAttestationBigintSignatureSet(config, index2pubkey, state, indexedAttestation));
41
+ return verifySignatureSet(
42
+ getIndexedAttestationBigintSignatureSet(config, index2pubkey, state.slot, indexedAttestation)
43
+ );
42
44
  }
43
45
  return true;
44
46
  }
@@ -67,7 +67,7 @@ export function processAttestationsAltair(
67
67
  const sigSet = getAttestationWithIndicesSignatureSet(
68
68
  state.config,
69
69
  epochCtx.index2pubkey,
70
- state,
70
+ state.slot,
71
71
  attestation,
72
72
  attestingIndices
73
73
  );
@@ -80,7 +80,7 @@ export function assertValidProposerSlashing(
80
80
  const signatureSets = getProposerSlashingSignatureSets(
81
81
  state.config,
82
82
  state.epochCtx.index2pubkey,
83
- state,
83
+ state.slot,
84
84
  proposerSlashing
85
85
  );
86
86
  for (let i = 0; i < signatureSets.length; i++) {
@@ -12,12 +12,12 @@ import {getRandaoMix} from "../util/index.js";
12
12
  * PERF: Fixed work independent of block contents.
13
13
  */
14
14
  export function processRandao(state: CachedBeaconStateAllForks, block: BeaconBlock, verifySignature = true): void {
15
- const {epochCtx} = state;
15
+ const {epochCtx, config} = state;
16
16
  const epoch = epochCtx.epoch;
17
17
  const randaoReveal = block.body.randaoReveal;
18
18
 
19
19
  // verify RANDAO reveal
20
- if (verifySignature && !verifyRandaoSignature(state.config, epochCtx.index2pubkey, state, block)) {
20
+ if (verifySignature && !verifyRandaoSignature(config, epochCtx.index2pubkey, block)) {
21
21
  throw new Error("RANDAO reveal is an invalid signature");
22
22
  }
23
23
 
@@ -3,6 +3,7 @@ import {BeaconConfig} from "@lodestar/config";
3
3
  import {DOMAIN_SYNC_COMMITTEE, SYNC_COMMITTEE_SIZE} from "@lodestar/params";
4
4
  import {altair, ssz} from "@lodestar/types";
5
5
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
6
+ import {SyncCommitteeCache} from "../cache/syncCommitteeCache.js";
6
7
  import {G2_POINT_AT_INFINITY} from "../constants/index.js";
7
8
  import {CachedBeaconStateAllForks} from "../types.js";
8
9
  import {
@@ -28,7 +29,7 @@ export function processSyncAggregate(
28
29
  const signatureSet = getSyncCommitteeSignatureSet(
29
30
  state.config,
30
31
  state.epochCtx.index2pubkey,
31
- state,
32
+ state.epochCtx.currentSyncCommitteeIndexed,
32
33
  block,
33
34
  participantIndices
34
35
  );
@@ -73,7 +74,7 @@ export function processSyncAggregate(
73
74
  export function getSyncCommitteeSignatureSet(
74
75
  config: BeaconConfig,
75
76
  index2pubkey: Index2PubkeyCache,
76
- state: CachedBeaconStateAllForks,
77
+ currentSyncCommitteeIndexed: SyncCommitteeCache,
77
78
  block: altair.BeaconBlock,
78
79
  /** Optional parameter to prevent computing it twice */
79
80
  participantIndices?: number[]
@@ -101,7 +102,7 @@ export function getSyncCommitteeSignatureSet(
101
102
  const rootSigned = block.parentRoot;
102
103
 
103
104
  if (!participantIndices) {
104
- const committeeIndices = state.epochCtx.currentSyncCommitteeIndexed.validatorIndices;
105
+ const committeeIndices = currentSyncCommitteeIndexed.validatorIndices;
105
106
  participantIndices = syncAggregate.syncCommitteeBits.intersectValues(committeeIndices);
106
107
  }
107
108
 
@@ -115,7 +116,9 @@ export function getSyncCommitteeSignatureSet(
115
116
  throw Error("Empty sync committee signature is not infinity");
116
117
  }
117
118
 
118
- const domain = config.getDomain(state.slot, DOMAIN_SYNC_COMMITTEE, previousSlot);
119
+ // the getDomain() api requires the state slot as 1st param, however it's the same to block.slot in state-transition
120
+ // and the same epoch when we verify blocks in batch in beacon-node. So we can safely use block.slot here.
121
+ const domain = config.getDomain(block.slot, DOMAIN_SYNC_COMMITTEE, previousSlot);
119
122
 
120
123
  return {
121
124
  type: SignatureSetType.aggregate,
@@ -76,7 +76,7 @@ export function getVoluntaryExitValidity(
76
76
 
77
77
  if (
78
78
  verifySignature &&
79
- !verifyVoluntaryExitSignature(state.config, epochCtx.index2pubkey, state, signedVoluntaryExit)
79
+ !verifyVoluntaryExitSignature(state.config, epochCtx.index2pubkey, state.slot, signedVoluntaryExit)
80
80
  ) {
81
81
  return VoluntaryExitValidity.invalidSignature;
82
82
  }
package/src/index.ts CHANGED
@@ -27,8 +27,7 @@ export {
27
27
  createEmptyEpochCacheImmutableData,
28
28
  } from "./cache/epochCache.js";
29
29
  export {type EpochTransitionCache, beforeProcessEpoch} from "./cache/epochTransitionCache.js";
30
- // Aux data-structures
31
- export {type Index2PubkeyCache} from "./cache/pubkeyCache.js";
30
+ export {type Index2PubkeyCache, syncPubkeys} from "./cache/pubkeyCache.js";
32
31
  // Main state caches
33
32
  export {
34
33
  type BeaconStateCache,
@@ -41,6 +40,7 @@ export {
41
40
  export * from "./constants/index.js";
42
41
  export type {EpochTransitionStep} from "./epoch/index.js";
43
42
  export {type BeaconStateTransitionMetrics, getMetrics} from "./metrics.js";
43
+ export * from "./rewards/index.js";
44
44
  export * from "./signatureSets/index.js";
45
45
  export * from "./stateTransition.js";
46
46
  export type {
@@ -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,147 @@
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 {CachedBeaconStateAllForks, CachedBeaconStateAltair, CachedBeaconStatePhase0} from "../cache/stateCache.js";
11
+ import {getAttesterSlashableIndices} from "../util/attestation.js";
12
+
13
+ type SubRewardValue = number; // All reward values should be integer
14
+
15
+ /**
16
+ * Calculate total proposer block rewards given block and the beacon state of the same slot before the block is applied (preState)
17
+ * postState can be passed in to read reward cache if available
18
+ * Standard (Non MEV) rewards for proposing a block consists of:
19
+ * 1) Including attestations from (beacon) committee
20
+ * 2) Including attestations from sync committee
21
+ * 3) Reporting slashable behaviours from proposer and attester
22
+ */
23
+ export async function computeBlockRewards(
24
+ config: BeaconConfig,
25
+ block: BeaconBlock,
26
+ preState: CachedBeaconStateAllForks,
27
+ postState?: CachedBeaconStateAllForks
28
+ ): Promise<rewards.BlockRewards> {
29
+ const fork = config.getForkName(block.slot);
30
+ const {attestations: cachedAttestationsReward = 0, syncAggregate: cachedSyncAggregateReward = 0} =
31
+ postState?.proposerRewards ?? {};
32
+ let blockAttestationReward = cachedAttestationsReward;
33
+ let syncAggregateReward = cachedSyncAggregateReward;
34
+
35
+ if (blockAttestationReward === 0) {
36
+ blockAttestationReward =
37
+ fork === ForkName.phase0
38
+ ? computeBlockAttestationRewardPhase0(block as phase0.BeaconBlock, preState as CachedBeaconStatePhase0)
39
+ : computeBlockAttestationRewardAltair(config, block as altair.BeaconBlock, preState as CachedBeaconStateAltair);
40
+ }
41
+
42
+ if (syncAggregateReward === 0) {
43
+ syncAggregateReward = computeSyncAggregateReward(block as altair.BeaconBlock, preState as CachedBeaconStateAltair);
44
+ }
45
+
46
+ const blockProposerSlashingReward = computeBlockProposerSlashingReward(fork, block, preState);
47
+ const blockAttesterSlashingReward = computeBlockAttesterSlashingReward(fork, block, preState);
48
+
49
+ const total =
50
+ blockAttestationReward + syncAggregateReward + blockProposerSlashingReward + blockAttesterSlashingReward;
51
+
52
+ return {
53
+ proposerIndex: block.proposerIndex,
54
+ total,
55
+ attestations: blockAttestationReward,
56
+ syncAggregate: syncAggregateReward,
57
+ proposerSlashings: blockProposerSlashingReward,
58
+ attesterSlashings: blockAttesterSlashingReward,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * TODO: Calculate rewards received by block proposer for including attestations.
64
+ */
65
+ function computeBlockAttestationRewardPhase0(
66
+ _block: phase0.BeaconBlock,
67
+ _preState: CachedBeaconStatePhase0
68
+ ): SubRewardValue {
69
+ throw new Error("Unsupported fork! Block attestation reward calculation is not available in phase0");
70
+ }
71
+
72
+ /**
73
+ * Calculate rewards received by block proposer for including attestations since Altair.
74
+ * Reuses `processAttestationsAltair()`. Has dependency on RewardCache
75
+ */
76
+ function computeBlockAttestationRewardAltair(
77
+ config: BeaconConfig,
78
+ block: altair.BeaconBlock,
79
+ preState: CachedBeaconStateAltair
80
+ ): SubRewardValue {
81
+ const fork = config.getForkSeq(block.slot);
82
+ const {attestations} = block.body;
83
+
84
+ processAttestationsAltair(fork, preState, attestations, false);
85
+
86
+ return preState.proposerRewards.attestations;
87
+ }
88
+
89
+ function computeSyncAggregateReward(block: altair.BeaconBlock, preState: CachedBeaconStateAltair): SubRewardValue {
90
+ if (block.body.syncAggregate !== undefined) {
91
+ const {syncCommitteeBits} = block.body.syncAggregate;
92
+ const {syncProposerReward} = preState.epochCtx;
93
+
94
+ return syncCommitteeBits.getTrueBitIndexes().length * Math.floor(syncProposerReward); // syncProposerReward should already be integer
95
+ }
96
+
97
+ return 0; // phase0 block does not have syncAggregate
98
+ }
99
+
100
+ /**
101
+ * Calculate rewards received by block proposer for including proposer slashings.
102
+ * All proposer slashing rewards go to block proposer and none to whistleblower as of Deneb
103
+ */
104
+ function computeBlockProposerSlashingReward(
105
+ fork: ForkName,
106
+ block: BeaconBlock,
107
+ state: CachedBeaconStateAllForks
108
+ ): SubRewardValue {
109
+ let proposerSlashingReward = 0;
110
+
111
+ for (const proposerSlashing of block.body.proposerSlashings) {
112
+ const offendingProposerIndex = proposerSlashing.signedHeader1.message.proposerIndex;
113
+ const offendingProposerBalance = state.validators.getReadonly(offendingProposerIndex).effectiveBalance;
114
+ const whistleblowerRewardQuotient = isForkPostElectra(fork)
115
+ ? WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA
116
+ : WHISTLEBLOWER_REWARD_QUOTIENT;
117
+
118
+ proposerSlashingReward += Math.floor(offendingProposerBalance / whistleblowerRewardQuotient);
119
+ }
120
+
121
+ return proposerSlashingReward;
122
+ }
123
+
124
+ /**
125
+ * Calculate rewards received by block proposer for including attester slashings.
126
+ * All attester slashing rewards go to block proposer and none to whistleblower as of Deneb
127
+ */
128
+ function computeBlockAttesterSlashingReward(
129
+ fork: ForkName,
130
+ block: BeaconBlock,
131
+ preState: CachedBeaconStateAllForks
132
+ ): SubRewardValue {
133
+ let attesterSlashingReward = 0;
134
+
135
+ for (const attesterSlashing of block.body.attesterSlashings) {
136
+ for (const offendingAttesterIndex of getAttesterSlashableIndices(attesterSlashing)) {
137
+ const offendingAttesterBalance = preState.validators.getReadonly(offendingAttesterIndex).effectiveBalance;
138
+ const whistleblowerRewardQuotient = isForkPostElectra(fork)
139
+ ? WHISTLEBLOWER_REWARD_QUOTIENT_ELECTRA
140
+ : WHISTLEBLOWER_REWARD_QUOTIENT;
141
+
142
+ attesterSlashingReward += Math.floor(offendingAttesterBalance / whistleblowerRewardQuotient);
143
+ }
144
+ }
145
+
146
+ return attesterSlashingReward;
147
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./attestationsRewards.js";
2
+ export * from "./blockRewards.js";
3
+ export * from "./syncCommitteeRewards.js";
@@ -0,0 +1,59 @@
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
+ type BalanceRecord = {val: number}; // Use val for convenient way to increment/decrement balance
8
+
9
+ export async function computeSyncCommitteeRewards(
10
+ config: BeaconConfig,
11
+ index2pubkey: Index2PubkeyCache,
12
+ block: BeaconBlock,
13
+ preState: CachedBeaconStateAllForks,
14
+ validatorIds: (ValidatorIndex | string)[] = []
15
+ ): Promise<rewards.SyncCommitteeRewards> {
16
+ const fork = config.getForkName(block.slot);
17
+ if (fork === ForkName.phase0) {
18
+ throw Error("Cannot get sync rewards as phase0 block does not have sync committee");
19
+ }
20
+
21
+ const altairBlock = block as altair.BeaconBlock;
22
+ const preStateAltair = preState as CachedBeaconStateAltair;
23
+
24
+ // Bound syncCommitteeValidatorIndices in case it goes beyond SYNC_COMMITTEE_SIZE just to be safe
25
+ const syncCommitteeValidatorIndices = preStateAltair.epochCtx.currentSyncCommitteeIndexed.validatorIndices.slice(
26
+ 0,
27
+ SYNC_COMMITTEE_SIZE
28
+ );
29
+ const {syncParticipantReward} = preStateAltair.epochCtx;
30
+ const {syncCommitteeBits} = altairBlock.body.syncAggregate;
31
+
32
+ // Use balance of each committee as starting point such that we cap the penalty to avoid balance dropping below 0
33
+ const balances: Map<ValidatorIndex, BalanceRecord> = new Map();
34
+ for (const i of syncCommitteeValidatorIndices) {
35
+ balances.set(i, {val: preStateAltair.balances.get(i)});
36
+ }
37
+
38
+ for (const i of syncCommitteeValidatorIndices) {
39
+ const balanceRecord = balances.get(i) as BalanceRecord;
40
+ if (syncCommitteeBits.get(i)) {
41
+ // Positive rewards for participants
42
+ balanceRecord.val += syncParticipantReward;
43
+ } else {
44
+ // Negative rewards for non participants
45
+ balanceRecord.val = Math.max(0, balanceRecord.val - syncParticipantReward);
46
+ }
47
+ }
48
+
49
+ const rewards = Array.from(balances, ([validatorIndex, v]) => ({validatorIndex, reward: v.val}));
50
+
51
+ if (validatorIds.length) {
52
+ const filtersSet = new Set(validatorIds);
53
+ return rewards.filter(
54
+ (reward) => filtersSet.has(reward.validatorIndex) || filtersSet.has(index2pubkey[reward.validatorIndex].toHex())
55
+ );
56
+ }
57
+
58
+ return rewards;
59
+ }
@@ -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,