@lodestar/state-transition 1.39.0-dev.3bf4734ba9 → 1.39.0-dev.6ac43e390d

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 (118) 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 +3 -2
  5. package/lib/block/isValidIndexedAttestation.d.ts.map +1 -1
  6. package/lib/block/isValidIndexedAttestation.js +4 -4
  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.d.ts.map +1 -1
  12. package/lib/block/processAttestationsAltair.js +1 -1
  13. package/lib/block/processAttestationsAltair.js.map +1 -1
  14. package/lib/block/processAttesterSlashing.js +1 -1
  15. package/lib/block/processAttesterSlashing.js.map +1 -1
  16. package/lib/block/processExecutionPayload.d.ts.map +1 -1
  17. package/lib/block/processExecutionPayload.js +6 -4
  18. package/lib/block/processExecutionPayload.js.map +1 -1
  19. package/lib/block/processProposerSlashing.d.ts.map +1 -1
  20. package/lib/block/processProposerSlashing.js +1 -1
  21. package/lib/block/processProposerSlashing.js.map +1 -1
  22. package/lib/block/processRandao.js +2 -2
  23. package/lib/block/processRandao.js.map +1 -1
  24. package/lib/block/processSyncCommittee.d.ts +3 -1
  25. package/lib/block/processSyncCommittee.d.ts.map +1 -1
  26. package/lib/block/processSyncCommittee.js +6 -4
  27. package/lib/block/processSyncCommittee.js.map +1 -1
  28. package/lib/block/processVoluntaryExit.d.ts.map +1 -1
  29. package/lib/block/processVoluntaryExit.js +2 -1
  30. package/lib/block/processVoluntaryExit.js.map +1 -1
  31. package/lib/cache/epochCache.d.ts +0 -3
  32. package/lib/cache/epochCache.d.ts.map +1 -1
  33. package/lib/cache/epochCache.js +0 -3
  34. package/lib/cache/epochCache.js.map +1 -1
  35. package/lib/cache/stateCache.d.ts +1 -0
  36. package/lib/cache/stateCache.d.ts.map +1 -1
  37. package/lib/cache/stateCache.js.map +1 -1
  38. package/lib/index.d.ts +2 -1
  39. package/lib/index.d.ts.map +1 -1
  40. package/lib/index.js +2 -0
  41. package/lib/index.js.map +1 -1
  42. package/lib/rewards/attestationsRewards.d.ts +6 -0
  43. package/lib/rewards/attestationsRewards.d.ts.map +1 -0
  44. package/lib/rewards/attestationsRewards.js +113 -0
  45. package/lib/rewards/attestationsRewards.js.map +1 -0
  46. package/lib/rewards/blockRewards.d.ts +13 -0
  47. package/lib/rewards/blockRewards.d.ts.map +1 -0
  48. package/lib/rewards/blockRewards.js +95 -0
  49. package/lib/rewards/blockRewards.js.map +1 -0
  50. package/lib/rewards/index.d.ts +4 -0
  51. package/lib/rewards/index.d.ts.map +1 -0
  52. package/lib/rewards/index.js +4 -0
  53. package/lib/rewards/index.js.map +1 -0
  54. package/lib/rewards/syncCommitteeRewards.d.ts +6 -0
  55. package/lib/rewards/syncCommitteeRewards.d.ts.map +1 -0
  56. package/lib/rewards/syncCommitteeRewards.js +36 -0
  57. package/lib/rewards/syncCommitteeRewards.js.map +1 -0
  58. package/lib/signatureSets/attesterSlashings.d.ts +5 -5
  59. package/lib/signatureSets/attesterSlashings.d.ts.map +1 -1
  60. package/lib/signatureSets/attesterSlashings.js +10 -7
  61. package/lib/signatureSets/attesterSlashings.js.map +1 -1
  62. package/lib/signatureSets/index.d.ts +3 -2
  63. package/lib/signatureSets/index.d.ts.map +1 -1
  64. package/lib/signatureSets/index.js +10 -10
  65. package/lib/signatureSets/index.js.map +1 -1
  66. package/lib/signatureSets/indexedAttestation.d.ts +6 -6
  67. package/lib/signatureSets/indexedAttestation.d.ts.map +1 -1
  68. package/lib/signatureSets/indexedAttestation.js +12 -9
  69. package/lib/signatureSets/indexedAttestation.js.map +1 -1
  70. package/lib/signatureSets/proposer.d.ts +3 -2
  71. package/lib/signatureSets/proposer.d.ts.map +1 -1
  72. package/lib/signatureSets/proposer.js +7 -5
  73. package/lib/signatureSets/proposer.js.map +1 -1
  74. package/lib/signatureSets/proposerSlashings.d.ts +4 -4
  75. package/lib/signatureSets/proposerSlashings.d.ts.map +1 -1
  76. package/lib/signatureSets/proposerSlashings.js +7 -4
  77. package/lib/signatureSets/proposerSlashings.js.map +1 -1
  78. package/lib/signatureSets/randao.d.ts +3 -3
  79. package/lib/signatureSets/randao.d.ts.map +1 -1
  80. package/lib/signatureSets/randao.js +6 -4
  81. package/lib/signatureSets/randao.js.map +1 -1
  82. package/lib/signatureSets/voluntaryExits.d.ts +5 -5
  83. package/lib/signatureSets/voluntaryExits.d.ts.map +1 -1
  84. package/lib/signatureSets/voluntaryExits.js +10 -7
  85. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  86. package/lib/stateTransition.js +1 -1
  87. package/lib/stateTransition.js.map +1 -1
  88. package/lib/util/execution.d.ts +11 -1
  89. package/lib/util/execution.d.ts.map +1 -1
  90. package/lib/util/execution.js +26 -1
  91. package/lib/util/execution.js.map +1 -1
  92. package/package.json +14 -11
  93. package/src/block/index.ts +6 -2
  94. package/src/block/isValidIndexedAttestation.ts +7 -2
  95. package/src/block/processAttestationPhase0.ts +1 -0
  96. package/src/block/processAttestationsAltair.ts +7 -1
  97. package/src/block/processAttesterSlashing.ts +1 -1
  98. package/src/block/processExecutionPayload.ts +14 -8
  99. package/src/block/processProposerSlashing.ts +6 -1
  100. package/src/block/processRandao.ts +2 -2
  101. package/src/block/processSyncCommittee.ts +15 -4
  102. package/src/block/processVoluntaryExit.ts +4 -1
  103. package/src/cache/epochCache.ts +0 -3
  104. package/src/cache/stateCache.ts +1 -0
  105. package/src/index.ts +2 -2
  106. package/src/rewards/attestationsRewards.ts +200 -0
  107. package/src/rewards/blockRewards.ts +147 -0
  108. package/src/rewards/index.ts +3 -0
  109. package/src/rewards/syncCommitteeRewards.ts +59 -0
  110. package/src/signatureSets/attesterSlashings.ts +14 -9
  111. package/src/signatureSets/index.ts +14 -11
  112. package/src/signatureSets/indexedAttestation.ts +18 -11
  113. package/src/signatureSets/proposer.ts +8 -5
  114. package/src/signatureSets/proposerSlashings.ts +10 -10
  115. package/src/signatureSets/randao.ts +7 -5
  116. package/src/signatureSets/voluntaryExits.ts +14 -9
  117. package/src/stateTransition.ts +1 -1
  118. package/src/util/execution.ts +39 -0
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.3bf4734ba9",
14
+ "version": "1.39.0-dev.6ac43e390d",
15
15
  "type": "module",
16
16
  "exports": {
17
17
  ".": {
@@ -43,15 +43,15 @@
43
43
  "scripts": {
44
44
  "clean": "rm -rf lib && rm -f *.tsbuildinfo",
45
45
  "build": "tsc -p tsconfig.build.json",
46
- "build:watch": "yarn run build --watch",
47
- "build:release": "yarn clean && yarn build",
46
+ "build:watch": "pnpm run build --watch",
47
+ "build:release": "pnpm clean && pnpm build",
48
48
  "check-build": "node -e \"(async function() { await import('./lib/index.js') })()\"",
49
49
  "check-types": "tsc",
50
50
  "lint": "biome check src/ test/",
51
- "lint:fix": "yarn run lint --write",
52
- "test": "yarn test:unit",
51
+ "lint:fix": "pnpm run lint --write",
52
+ "test": "pnpm test:unit",
53
53
  "test:unit": "vitest run --project unit --project unit-minimal",
54
- "check-readme": "typescript-docs-verifier"
54
+ "check-readme": "pnpm exec ts-node ../../scripts/check_readme.ts"
55
55
  },
56
56
  "types": "lib/index.d.ts",
57
57
  "dependencies": {
@@ -62,17 +62,20 @@
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.3bf4734ba9",
66
- "@lodestar/params": "1.39.0-dev.3bf4734ba9",
67
- "@lodestar/types": "1.39.0-dev.3bf4734ba9",
68
- "@lodestar/utils": "1.39.0-dev.3bf4734ba9",
65
+ "@lodestar/config": "^1.39.0-dev.6ac43e390d",
66
+ "@lodestar/params": "^1.39.0-dev.6ac43e390d",
67
+ "@lodestar/types": "^1.39.0-dev.6ac43e390d",
68
+ "@lodestar/utils": "^1.39.0-dev.6ac43e390d",
69
69
  "bigint-buffer": "^1.1.5"
70
70
  },
71
+ "devDependencies": {
72
+ "@lodestar/api": "^1.39.0-dev.6ac43e390d"
73
+ },
71
74
  "keywords": [
72
75
  "ethereum",
73
76
  "eth-consensus",
74
77
  "beacon",
75
78
  "blockchain"
76
79
  ],
77
- "gitHead": "890675f6ac97591d1111b6f61ed0e2079f264906"
80
+ "gitHead": "4b76f3b7cd72022fc7dd121cc40d9698f3cce066"
78
81
  }
@@ -7,7 +7,7 @@ import {
7
7
  CachedBeaconStateCapella,
8
8
  CachedBeaconStateGloas,
9
9
  } from "../types.js";
10
- import {getFullOrBlindedPayload} from "../util/execution.js";
10
+ import {getFullOrBlindedPayload, isExecutionEnabled} from "../util/execution.js";
11
11
  import {BlockExternalData, DataAvailabilityStatus} from "./externalData.js";
12
12
  import {processBlobKzgCommitments} from "./processBlobKzgCommitments.js";
13
13
  import {processBlockHeader} from "./processBlockHeader.js";
@@ -67,7 +67,11 @@ export function processBlock(
67
67
  // The call to the process_execution_payload must happen before the call to the process_randao as the former depends
68
68
  // on the randao_mix computed with the reveal of the previous block.
69
69
  // TODO GLOAS: We call processExecutionPayload somewhere else post-gloas
70
- if (fork >= ForkSeq.bellatrix && fork < ForkSeq.gloas) {
70
+ if (
71
+ fork < ForkSeq.gloas &&
72
+ fork >= ForkSeq.bellatrix &&
73
+ isExecutionEnabled(state as CachedBeaconStateBellatrix, block)
74
+ ) {
71
75
  processExecutionPayload(fork, state as CachedBeaconStateBellatrix, block.body, externalData);
72
76
  }
73
77
 
@@ -1,3 +1,4 @@
1
+ import {BeaconConfig} from "@lodestar/config";
1
2
  import {ForkSeq, MAX_COMMITTEES_PER_SLOT, MAX_VALIDATORS_PER_COMMITTEE} from "@lodestar/params";
2
3
  import {IndexedAttestation, IndexedAttestationBigint} from "@lodestar/types";
3
4
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
@@ -9,6 +10,7 @@ import {verifySignatureSet} from "../util/index.js";
9
10
  * Check if `indexedAttestation` has sorted and unique indices and a valid aggregate signature.
10
11
  */
11
12
  export function isValidIndexedAttestation(
13
+ config: BeaconConfig,
12
14
  index2pubkey: Index2PubkeyCache,
13
15
  state: CachedBeaconStateAllForks,
14
16
  indexedAttestation: IndexedAttestation,
@@ -19,12 +21,13 @@ export function isValidIndexedAttestation(
19
21
  }
20
22
 
21
23
  if (verifySignature) {
22
- return verifySignatureSet(getIndexedAttestationSignatureSet(index2pubkey, state, indexedAttestation));
24
+ return verifySignatureSet(getIndexedAttestationSignatureSet(config, index2pubkey, state.slot, indexedAttestation));
23
25
  }
24
26
  return true;
25
27
  }
26
28
 
27
29
  export function isValidIndexedAttestationBigint(
30
+ config: BeaconConfig,
28
31
  index2pubkey: Index2PubkeyCache,
29
32
  state: CachedBeaconStateAllForks,
30
33
  indexedAttestation: IndexedAttestationBigint,
@@ -35,7 +38,9 @@ export function isValidIndexedAttestationBigint(
35
38
  }
36
39
 
37
40
  if (verifySignature) {
38
- return verifySignatureSet(getIndexedAttestationBigintSignatureSet(index2pubkey, state, indexedAttestation));
41
+ return verifySignatureSet(
42
+ getIndexedAttestationBigintSignatureSet(config, index2pubkey, state.slot, indexedAttestation)
43
+ );
39
44
  }
40
45
  return true;
41
46
  }
@@ -52,6 +52,7 @@ export function processAttestationPhase0(
52
52
 
53
53
  if (
54
54
  !isValidIndexedAttestation(
55
+ state.config,
55
56
  epochCtx.index2pubkey,
56
57
  state,
57
58
  epochCtx.getIndexedAttestation(ForkSeq.phase0, attestation),
@@ -64,7 +64,13 @@ export function processAttestationsAltair(
64
64
  // TODO: Why should we verify an indexed attestation that we just created? If it's just for the signature
65
65
  // we can verify only that and nothing else.
66
66
  if (verifySignature) {
67
- const sigSet = getAttestationWithIndicesSignatureSet(epochCtx.index2pubkey, state, attestation, attestingIndices);
67
+ const sigSet = getAttestationWithIndicesSignatureSet(
68
+ state.config,
69
+ epochCtx.index2pubkey,
70
+ state.slot,
71
+ attestation,
72
+ attestingIndices
73
+ );
68
74
  if (!verifySignatureSet(sigSet)) {
69
75
  throw new Error("Attestation signature is not valid");
70
76
  }
@@ -55,7 +55,7 @@ export function assertValidAttesterSlashing(
55
55
  // be higher than the clock and the slashing would still be valid. Same applies to attestation data index, which
56
56
  // can be any arbitrary value. Must use bigint variants to hash correctly to all possible values
57
57
  for (const [i, attestation] of [attestation1, attestation2].entries()) {
58
- if (!isValidIndexedAttestationBigint(index2pubkey, state, attestation, verifySignatures)) {
58
+ if (!isValidIndexedAttestationBigint(state.config, index2pubkey, state, attestation, verifySignatures)) {
59
59
  throw new Error(`AttesterSlashing attestation${i} is invalid`);
60
60
  }
61
61
  }
@@ -3,7 +3,11 @@ import {ForkName, ForkSeq, isForkPostDeneb} from "@lodestar/params";
3
3
  import {BeaconBlockBody, BlindedBeaconBlockBody, deneb, isExecutionPayload} from "@lodestar/types";
4
4
  import {toHex, toRootHex} from "@lodestar/utils";
5
5
  import {CachedBeaconStateBellatrix, CachedBeaconStateCapella} from "../types.js";
6
- import {executionPayloadToPayloadHeader, getFullOrBlindedPayloadFromBody} from "../util/execution.js";
6
+ import {
7
+ executionPayloadToPayloadHeader,
8
+ getFullOrBlindedPayloadFromBody,
9
+ isMergeTransitionComplete,
10
+ } from "../util/execution.js";
7
11
  import {computeEpochAtSlot, computeTimeAtSlot, getRandaoMix} from "../util/index.js";
8
12
  import {BlockExternalData, ExecutionPayloadStatus} from "./externalData.js";
9
13
 
@@ -17,13 +21,15 @@ export function processExecutionPayload(
17
21
  const forkName = ForkName[ForkSeq[fork] as ForkName];
18
22
  // Verify consistency of the parent hash, block number, base fee per gas and gas limit
19
23
  // with respect to the previous execution payload header
20
- const {latestExecutionPayloadHeader} = state;
21
- if (!byteArrayEquals(payload.parentHash, latestExecutionPayloadHeader.blockHash)) {
22
- throw Error(
23
- `Invalid execution payload parentHash ${toRootHex(payload.parentHash)} latest blockHash ${toRootHex(
24
- latestExecutionPayloadHeader.blockHash
25
- )}`
26
- );
24
+ if (isMergeTransitionComplete(state)) {
25
+ const {latestExecutionPayloadHeader} = state;
26
+ if (!byteArrayEquals(payload.parentHash, latestExecutionPayloadHeader.blockHash)) {
27
+ throw Error(
28
+ `Invalid execution payload parentHash ${toRootHex(payload.parentHash)} latest blockHash ${toRootHex(
29
+ latestExecutionPayloadHeader.blockHash
30
+ )}`
31
+ );
32
+ }
27
33
  }
28
34
 
29
35
  // Verify random
@@ -77,7 +77,12 @@ export function assertValidProposerSlashing(
77
77
 
78
78
  // verify signatures
79
79
  if (verifySignatures) {
80
- const signatureSets = getProposerSlashingSignatureSets(state.epochCtx.index2pubkey, state, proposerSlashing);
80
+ const signatureSets = getProposerSlashingSignatureSets(
81
+ state.config,
82
+ state.epochCtx.index2pubkey,
83
+ state.slot,
84
+ proposerSlashing
85
+ );
81
86
  for (let i = 0; i < signatureSets.length; i++) {
82
87
  if (!verifySignatureSet(signatureSets[i])) {
83
88
  throw new Error(`ProposerSlashing header${i + 1} signature invalid`);
@@ -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(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
 
@@ -1,7 +1,9 @@
1
1
  import {byteArrayEquals} from "@chainsafe/ssz";
2
+ import {BeaconConfig} from "@lodestar/config";
2
3
  import {DOMAIN_SYNC_COMMITTEE, SYNC_COMMITTEE_SIZE} from "@lodestar/params";
3
4
  import {altair, ssz} from "@lodestar/types";
4
5
  import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
6
+ import {SyncCommitteeCache} from "../cache/syncCommitteeCache.js";
5
7
  import {G2_POINT_AT_INFINITY} from "../constants/index.js";
6
8
  import {CachedBeaconStateAllForks} from "../types.js";
7
9
  import {
@@ -24,7 +26,13 @@ export function processSyncAggregate(
24
26
  if (verifySignatures) {
25
27
  // This is to conform to the spec - we want the signature to be verified
26
28
  const participantIndices = block.body.syncAggregate.syncCommitteeBits.intersectValues(committeeIndices);
27
- const signatureSet = getSyncCommitteeSignatureSet(state.epochCtx.index2pubkey, state, block, participantIndices);
29
+ const signatureSet = getSyncCommitteeSignatureSet(
30
+ state.config,
31
+ state.epochCtx.index2pubkey,
32
+ state.epochCtx.currentSyncCommitteeIndexed,
33
+ block,
34
+ participantIndices
35
+ );
28
36
  // When there's no participation we consider the signature valid and just ignore i
29
37
  if (signatureSet !== null && !verifySignatureSet(signatureSet)) {
30
38
  throw Error("Sync committee signature invalid");
@@ -64,8 +72,9 @@ export function processSyncAggregate(
64
72
  }
65
73
 
66
74
  export function getSyncCommitteeSignatureSet(
75
+ config: BeaconConfig,
67
76
  index2pubkey: Index2PubkeyCache,
68
- state: CachedBeaconStateAllForks,
77
+ currentSyncCommitteeIndexed: SyncCommitteeCache,
69
78
  block: altair.BeaconBlock,
70
79
  /** Optional parameter to prevent computing it twice */
71
80
  participantIndices?: number[]
@@ -93,7 +102,7 @@ export function getSyncCommitteeSignatureSet(
93
102
  const rootSigned = block.parentRoot;
94
103
 
95
104
  if (!participantIndices) {
96
- const committeeIndices = state.epochCtx.currentSyncCommitteeIndexed.validatorIndices;
105
+ const committeeIndices = currentSyncCommitteeIndexed.validatorIndices;
97
106
  participantIndices = syncAggregate.syncCommitteeBits.intersectValues(committeeIndices);
98
107
  }
99
108
 
@@ -107,7 +116,9 @@ export function getSyncCommitteeSignatureSet(
107
116
  throw Error("Empty sync committee signature is not infinity");
108
117
  }
109
118
 
110
- const domain = state.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);
111
122
 
112
123
  return {
113
124
  type: SignatureSetType.aggregate,
@@ -74,7 +74,10 @@ export function getVoluntaryExitValidity(
74
74
  return VoluntaryExitValidity.pendingWithdrawals;
75
75
  }
76
76
 
77
- if (verifySignature && !verifyVoluntaryExitSignature(epochCtx.index2pubkey, state, signedVoluntaryExit)) {
77
+ if (
78
+ verifySignature &&
79
+ !verifyVoluntaryExitSignature(state.config, epochCtx.index2pubkey, state.slot, signedVoluntaryExit)
80
+ ) {
78
81
  return VoluntaryExitValidity.invalidSignature;
79
82
  }
80
83
 
@@ -108,9 +108,6 @@ export class EpochCache {
108
108
  /**
109
109
  * Unique globally shared pubkey registry. There should only exist one for the entire application.
110
110
  *
111
- * TODO: this is a hack, we need a safety mechanism in case a bad eth1 majority vote is in,
112
- * or handle non finalized data differently, or use an immutable.js structure for cheap copies
113
- *
114
111
  * $VALIDATOR_COUNT x 192 char String -> Number Map
115
112
  */
116
113
  pubkey2index: PubkeyIndexMap;
@@ -17,6 +17,7 @@ import {
17
17
  } from "./types.js";
18
18
 
19
19
  export type BeaconStateCache = {
20
+ /** @deprecated should not access config outside of state-transition package */
20
21
  config: BeaconConfig;
21
22
  epochCtx: EpochCache;
22
23
  /** Count of clones created from this BeaconStateCache instance. readonly to prevent accidental usage downstream */
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
+ }