Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid getTotalBalance() #3096

Merged
merged 2 commits into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ export function processEffectiveBalanceUpdates(
const UPWARD_THRESHOLD = HYSTERESIS_INCREMENT * HYSTERESIS_UPWARD_MULTIPLIER;
const {validators, epochCtx} = state;
const {effectiveBalances} = epochCtx;
const nextEpoch = epochCtx.currentShuffling.epoch + 1;
const isNextEpochAfterAltairFork = nextEpoch >= epochCtx.config.ALTAIR_FORK_EPOCH;
let nextEpochTotalActiveBalanceByIncrement = 0;

// update effective balances with hysteresis
Expand Down Expand Up @@ -56,7 +54,7 @@ export function processEffectiveBalanceUpdates(
// TODO: Update all in batch after this loop
epochCtx.effectiveBalances.set(i, effectiveBalance);
}
if (isNextEpochAfterAltairFork && epochProcess.isActiveNextEpoch[i]) {
if (epochProcess.isActiveNextEpoch[i]) {
// We track nextEpochTotalActiveBalanceByIncrement as ETH to fit total network balance in a JS number (53 bits)
nextEpochTotalActiveBalanceByIncrement += Math.floor(effectiveBalance / EFFECTIVE_BALANCE_INCREMENT);
}
Expand Down
12 changes: 10 additions & 2 deletions packages/beacon-state-transition/src/allForks/util/epochContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ export function createEpochContext(
syncParticipantReward,
syncProposerReward,
baseRewardPerIncrement,
totalActiveBalanceByIncrement,
churnLimit,
exitQueueEpoch,
exitQueueChurn,
Expand Down Expand Up @@ -328,9 +329,9 @@ export function afterProcessEpoch(state: CachedBeaconState<allForks.BeaconState>
epochCtx.exitQueueEpoch = exitQueueEpoch;
epochCtx.exitQueueChurn = 0;
}

const totalActiveBalanceByIncrement = epochProcess.nextEpochTotalActiveBalanceByIncrement;
epochCtx.totalActiveBalanceByIncrement = totalActiveBalanceByIncrement;
if (currEpoch >= epochCtx.config.ALTAIR_FORK_EPOCH) {
const totalActiveBalanceByIncrement = epochProcess.nextEpochTotalActiveBalanceByIncrement;
const totalActiveBalance = BigInt(totalActiveBalanceByIncrement) * BigInt(EFFECTIVE_BALANCE_INCREMENT);
epochCtx.syncParticipantReward = computeSyncParticipantReward(epochCtx.config, totalActiveBalance);
epochCtx.syncProposerReward = Math.floor(
Expand All @@ -353,6 +354,7 @@ interface IEpochContextData {
syncParticipantReward: number;
syncProposerReward: number;
baseRewardPerIncrement: number;
totalActiveBalanceByIncrement: number;
churnLimit: number;
exitQueueEpoch: Epoch;
exitQueueChurn: number;
Expand Down Expand Up @@ -413,6 +415,10 @@ export class EpochContext {
* Update freq: once per epoch after `process_effective_balance_updates()`
*/
baseRewardPerIncrement: number;
/**
* Total active balance for current epoch, to be used instead of getTotalBalance()
*/
totalActiveBalanceByIncrement: number;

/**
* Rate at which validators can enter or leave the set per epoch. Depends only on activeIndexes, so it does not
Expand Down Expand Up @@ -446,6 +452,7 @@ export class EpochContext {
this.syncParticipantReward = data.syncParticipantReward;
this.syncProposerReward = data.syncProposerReward;
this.baseRewardPerIncrement = data.baseRewardPerIncrement;
this.totalActiveBalanceByIncrement = data.totalActiveBalanceByIncrement;
this.churnLimit = data.churnLimit;
this.exitQueueEpoch = data.exitQueueEpoch;
this.exitQueueChurn = data.exitQueueChurn;
Expand Down Expand Up @@ -474,6 +481,7 @@ export class EpochContext {
syncParticipantReward: this.syncParticipantReward,
syncProposerReward: this.syncProposerReward,
baseRewardPerIncrement: this.baseRewardPerIncrement,
totalActiveBalanceByIncrement: this.totalActiveBalanceByIncrement,
churnLimit: this.churnLimit,
exitQueueEpoch: this.exitQueueEpoch,
exitQueueChurn: this.exitQueueChurn,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import {IBeaconConfig, IChainForkConfig} from "@chainsafe/lodestar-config";
import {MAX_DEPOSITS, MAX_EFFECTIVE_BALANCE, SLOTS_PER_EPOCH} from "@chainsafe/lodestar-params";
import {
EFFECTIVE_BALANCE_INCREMENT,
MAX_DEPOSITS,
MAX_EFFECTIVE_BALANCE,
SLOTS_PER_EPOCH,
} from "@chainsafe/lodestar-params";
import {allForks, Epoch, Root} from "@chainsafe/lodestar-types";
import {ssz} from "@chainsafe/lodestar-types";
import {Checkpoint} from "@chainsafe/lodestar-types/phase0";
import {toHexString} from "@chainsafe/ssz";
import {CachedBeaconState} from ".";
import {
getActiveValidatorIndices,
getCurrentEpoch,
computeEpochAtSlot,
ZERO_HASH,
getTotalBalance,
getChurnLimit,
} from "../..";
import {getActiveValidatorIndices, getCurrentEpoch, computeEpochAtSlot, ZERO_HASH, getChurnLimit} from "../..";

export const ETH_TO_GWEI = 10 ** 9;
const SAFETY_DECAY = BigInt(10);
Expand All @@ -25,7 +23,7 @@ export function getLatestWeakSubjectivityCheckpointEpoch(
config: IChainForkConfig,
state: CachedBeaconState<allForks.BeaconState>
): Epoch {
return state.epochCtx.currentShuffling.epoch - computeWeakSubjectivityPeriod(config, state);
return state.epochCtx.currentShuffling.epoch - computeWeakSubjectivityPeriodCachedState(config, state);
}

/**
Expand All @@ -36,24 +34,51 @@ export function getLatestWeakSubjectivityCheckpointEpoch(
A detailed calculation can be found at:
https://github.com/runtimeverification/beacon-chain-verification/blob/master/weak-subjectivity/weak-subjectivity-analysis.pdf
*/
export function computeWeakSubjectivityPeriodCachedState(
config: IChainForkConfig,
state: CachedBeaconState<allForks.BeaconState>
): number {
const activeValidatorCount = state.currentShuffling.activeIndices.length;
return computeWeakSubjectivityPeriodFromConstituents(
activeValidatorCount,
state.totalActiveBalanceByIncrement,
getChurnLimit(config, activeValidatorCount),
config.MIN_VALIDATOR_WITHDRAWABILITY_DELAY
);
}

/**
* Same to computeWeakSubjectivityPeriodCachedState but for normal state
* This is called only 1 time at app startup so it's ok to calculate totalActiveBalanceByIncrement manually
*/
export function computeWeakSubjectivityPeriod(config: IChainForkConfig, state: allForks.BeaconState): number {
const indices = getActiveValidatorIndices(state, getCurrentEpoch(state));
const activeIndices = getActiveValidatorIndices(state, getCurrentEpoch(state));
let totalActiveBalanceByIncrement = 0;
for (const index of activeIndices) {
totalActiveBalanceByIncrement += Math.floor(state.validators[index].effectiveBalance / EFFECTIVE_BALANCE_INCREMENT);
}
if (totalActiveBalanceByIncrement <= 1) {
totalActiveBalanceByIncrement = 1;
}
return computeWeakSubjectivityPeriodFromConstituents(
indices.length,
getTotalBalance(state, indices),
getChurnLimit(config, indices.length),
activeIndices.length,
totalActiveBalanceByIncrement,
getChurnLimit(config, activeIndices.length),
config.MIN_VALIDATOR_WITHDRAWABILITY_DELAY
);
}

export function computeWeakSubjectivityPeriodFromConstituents(
activeValidatorCount: number,
totalBalance: bigint,
totalBalanceByIncrement: number,
churnLimit: number,
minWithdrawabilityDelay: number
): number {
const N = activeValidatorCount;
const t = Number(totalBalance / BigInt(N) / BigInt(ETH_TO_GWEI));
// originally const t = Number(totalBalance / BigInt(N) / BigInt(ETH_TO_GWEI));
// totalBalanceByIncrement = totalBalance / MAX_EFFECTIVE_BALANCE and MAX_EFFECTIVE_BALANCE = ETH_TO_GWEI atm
// we need to change this calculation just in case MAX_EFFECTIVE_BALANCE != ETH_TO_GWEI
const t = Math.floor(totalBalanceByIncrement / N);
const T = Number(MAX_EFFECTIVE_BALANCE / ETH_TO_GWEI);
const delta = churnLimit;
// eslint-disable-next-line @typescript-eslint/naming-convention
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {config} from "@chainsafe/lodestar-config/default";
import {expect} from "chai";
import {computeWeakSubjectivityPeriodFromConstituents, ETH_TO_GWEI} from "../../../src/allForks/util/weakSubjectivity";
import {computeWeakSubjectivityPeriodFromConstituents} from "../../../src/allForks/util/weakSubjectivity";
import {getChurnLimit} from "../../../src/util/validator";

describe("weak subjectivity tests", () => {
describe("computeWeakSubjectivityPeriodFromConstituents", function () {
const balance28 = BigInt(28) * BigInt(ETH_TO_GWEI);
const balance32 = BigInt(32) * BigInt(ETH_TO_GWEI);
const balance28 = 28;
const balance32 = 32;

const testValues = [
{avgValBalance: balance28, valCount: 32768, wsPeriod: 504},
Expand All @@ -27,7 +27,7 @@ describe("weak subjectivity tests", () => {
it(`should have wsPeriod: ${wsPeriod} with avgValBalance: ${avgValBalance} and valCount: ${valCount}`, () => {
const wsPeriod = computeWeakSubjectivityPeriodFromConstituents(
valCount,
avgValBalance * BigInt(valCount),
avgValBalance * valCount,
getChurnLimit(config, valCount),
config.MIN_VALIDATOR_WITHDRAWABILITY_DELAY
);
Expand Down