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

feat(state-transition): make validators epochs handling close to Eth2.0 specs #2226

Merged
merged 16 commits into from
Dec 9, 2024
46 changes: 30 additions & 16 deletions consensus-types/types/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,24 +246,18 @@ func (v Validator) IsActive(epoch math.Epoch) bool {
// https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#is_eligible_for_activation_queue
//
//nolint:lll
func (v Validator) IsEligibleForActivation(
finalizedEpoch math.Epoch,
) bool {
func (v Validator) IsEligibleForActivation(finalizedEpoch math.Epoch) bool {
return v.ActivationEligibilityEpoch <= finalizedEpoch &&
v.ActivationEpoch == math.Epoch(constants.FarFutureEpoch)
}

// IsEligibleForActivationQueue as defined in the Ethereum 2.0 Spec
// IsEligibleForActivationQueue is defined slightly differently from Ethereum 2.0 Spec
// https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#is_eligible_for_activation_queue
//
//nolint:lll
func (v Validator) IsEligibleForActivationQueue(
maxEffectiveBalance math.Gwei,
) bool {
return v.ActivationEligibilityEpoch == math.Epoch(
constants.FarFutureEpoch,
) &&
v.EffectiveBalance == maxEffectiveBalance
func (v Validator) IsEligibleForActivationQueue(threshold math.Gwei) bool {
return v.ActivationEligibilityEpoch == math.Epoch(constants.FarFutureEpoch) &&
v.EffectiveBalance >= threshold
}

// IsSlashable as defined in the Ethereum 2.0 Spec
Expand Down Expand Up @@ -296,9 +290,7 @@ func (v Validator) IsFullyWithdrawable(
// https://github.com/ethereum/consensus-specs/blob/dev/specs/capella/beacon-chain.md#is_partially_withdrawable_validator
//
//nolint:lll
func (v Validator) IsPartiallyWithdrawable(
balance, maxEffectiveBalance math.Gwei,
) bool {
func (v Validator) IsPartiallyWithdrawable(balance, maxEffectiveBalance math.Gwei) bool {
hasExcessBalance := balance > maxEffectiveBalance
return v.HasEth1WithdrawalCredentials() &&
v.HasMaxEffectiveBalance(maxEffectiveBalance) && hasExcessBalance
Expand All @@ -325,12 +317,34 @@ func (v *Validator) SetEffectiveBalance(balance math.Gwei) {
v.EffectiveBalance = balance
}

// SetWithdrawableEpoch sets the epoch when the validator can withdraw.
func (v *Validator) SetActivationEligibilityEpoch(e math.Epoch) {
v.ActivationEligibilityEpoch = e
}

func (v *Validator) GetActivationEligibilityEpoch() math.Epoch {
return v.ActivationEligibilityEpoch
}

func (v *Validator) SetActivationEpoch(e math.Epoch) {
v.ActivationEpoch = e
}

func (v *Validator) GetActivationEpoch() math.Epoch {
return v.ActivationEpoch
}

func (v *Validator) SetExitEpoch(e math.Epoch) {
v.ExitEpoch = e
}

func (v Validator) GetExitEpoch() math.Epoch {
return v.ExitEpoch
}

func (v *Validator) SetWithdrawableEpoch(e math.Epoch) {
v.WithdrawableEpoch = e
}

// GetWithdrawableEpoch returns the epoch when the validator can withdraw.
func (v Validator) GetWithdrawableEpoch() math.Epoch {
return v.WithdrawableEpoch
}
Expand Down
64 changes: 6 additions & 58 deletions state-transition/core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"github.com/berachain/beacon-kit/errors"
"github.com/berachain/beacon-kit/log"
"github.com/berachain/beacon-kit/primitives/common"
"github.com/berachain/beacon-kit/primitives/constants"
"github.com/berachain/beacon-kit/primitives/crypto"
"github.com/berachain/beacon-kit/primitives/math"
"github.com/berachain/beacon-kit/primitives/transition"
Expand Down Expand Up @@ -375,36 +374,19 @@ func (sp *StateProcessor[
]) processEpoch(
st BeaconStateT,
) (transition.ValidatorUpdates, error) {
slot, err := st.GetSlot()
if err != nil {
if err := sp.processRewardsAndPenalties(st); err != nil {
return nil, err
}

switch {
case sp.cs.DepositEth1ChainID() == spec.BartioChainID:
if err = sp.hollowProcessRewardsAndPenalties(st); err != nil {
return nil, err
}
case sp.cs.DepositEth1ChainID() == spec.BoonetEth1ChainID &&
slot < math.U64(spec.BoonetFork3Height):
// We cannot simply drop hollowProcessRewardsAndPenalties because
// appHash accounts for the list of operations carried out
// over the state even if the operations does not affect the state
// (rewards and penalties are always zero at this stage of beaconKit)
if err = sp.hollowProcessRewardsAndPenalties(st); err != nil {
return nil, err
}
default:
// no real need to perform hollowProcessRewardsAndPenalties
Comment on lines -383 to -398
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved into processRewardsAndPenalties to have fork switches less in the way of mostly read code

if err := sp.processRegistryUpdates(st); err != nil {
return nil, err
}

if err = sp.processEffectiveBalanceUpdates(st); err != nil {
if err := sp.processEffectiveBalanceUpdates(st); err != nil {
return nil, err
}
if err = sp.processSlashingsReset(st); err != nil {
if err := sp.processSlashingsReset(st); err != nil {
return nil, err
}
if err = sp.processRandaoMixesReset(st); err != nil {
if err := sp.processRandaoMixesReset(st); err != nil {
return nil, err
}
return sp.processValidatorsSetUpdates(st)
Expand Down Expand Up @@ -492,40 +474,6 @@ func (sp *StateProcessor[
return st.SetLatestBlockHeader(lbh)
}

func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) hollowProcessRewardsAndPenalties(st BeaconStateT) error {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved to its own file to be out of the way

slot, err := st.GetSlot()
if err != nil {
return err
}

if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}

// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}

for i := range valCount {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}

// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}

return nil
}

// processEffectiveBalanceUpdates as defined in the Ethereum 2.0 specification.
// https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/beacon-chain.md#effective-balances-updates
//
Expand Down
43 changes: 42 additions & 1 deletion state-transition/core/state_processor_genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
package core

import (
"fmt"

"github.com/berachain/beacon-kit/config/spec"
"github.com/berachain/beacon-kit/primitives/common"
"github.com/berachain/beacon-kit/primitives/constants"
Expand All @@ -32,7 +34,7 @@ import (

// InitializePreminedBeaconStateFromEth1 initializes the beacon state.
//
//nolint:gocognit // todo fix.
//nolint:gocognit,funlen // todo fix.
func (sp *StateProcessor[
_, BeaconBlockBodyT, BeaconBlockHeaderT, BeaconStateT, _, DepositT,
Eth1DataT, _, ExecutionPayloadHeaderT, ForkT, _, _, ValidatorT, _, _, _, _,
Expand Down Expand Up @@ -103,6 +105,11 @@ func (sp *StateProcessor[
}
}

// process activations
if err := sp.processGenesisActivation(st); err != nil {
return nil, err
}

// Handle special case bartio genesis.
validatorsRoot := common.Root(hex.MustToBytes(spec.BartioValRoot))
if sp.cs.DepositEth1ChainID() != spec.BartioChainID {
Expand Down Expand Up @@ -145,3 +152,37 @@ func (sp *StateProcessor[

return sp.processValidatorsSetUpdates(st)
}

func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, ValidatorT, _, _, _, _,
]) processGenesisActivation(
st BeaconStateT,
) error {
switch {
case sp.cs.DepositEth1ChainID() == spec.BartioChainID:
// nothing to do
return nil
case sp.cs.DepositEth1ChainID() == spec.BoonetEth1ChainID:
// nothing to do
return nil
default:
vals, err := st.GetValidators()
if err != nil {
return fmt.Errorf("genesis activation, failed listing validators: %w", err)
}

var idx math.ValidatorIndex
for _, val := range vals {
val.SetActivationEligibilityEpoch(0)
val.SetActivationEpoch(0)
idx, err = st.ValidatorIndexByPubkey(val.GetPubkey())
if err != nil {
return err
}
if err = st.UpdateValidatorAtIndex(idx, val); err != nil {
return err
}
}
return nil
}
}
42 changes: 28 additions & 14 deletions state-transition/core/state_processor_genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,19 @@ func checkValidatorNonBartio(
) {
t.Helper()

idx, err := bs.ValidatorIndexByPubkey(dep.Pubkey)
require.NoError(t, err)

val, err := bs.ValidatorByIndex(idx)
require.NoError(t, err)
require.Equal(t, dep.Pubkey, val.Pubkey)

// checks on validators common to all networks
commonChecksValidators(t, cs, bs, dep)
commonChecksValidators(t, cs, val, dep)

// checks on validators for any network but Bartio
idx, err := bs.ValidatorIndexByPubkey(dep.Pubkey)
require.NoError(t, err)
require.Equal(t, math.Epoch(0), val.GetActivationEligibilityEpoch())
require.Equal(t, math.Epoch(0), val.GetActivationEpoch())

valBal, err := bs.GetBalance(idx)
require.NoError(t, err)
Expand Down Expand Up @@ -268,15 +275,28 @@ func checkValidatorBartio(
) {
t.Helper()

// checks on validators common to all networks
commonChecksValidators(t, cs, bs, dep)

// Bartio specific checks on validators
idx, err := bs.ValidatorIndexByPubkey(dep.Pubkey)
require.NoError(t, err)

val, err := bs.ValidatorByIndex(idx)
require.NoError(t, err)
require.Equal(t, dep.Pubkey, val.Pubkey)

// checks on validators common to all networks
commonChecksValidators(t, cs, val, dep)

require.Equal(
t,
math.Epoch(constants.FarFutureEpoch),
val.GetActivationEligibilityEpoch(),
)
require.Equal(
t,
math.Epoch(constants.FarFutureEpoch),
val.GetActivationEpoch(),
)

// Bartio specific checks on validators
valBal, err := bs.GetBalance(idx)
require.NoError(t, err)
require.Equal(t, val.EffectiveBalance, valBal)
Expand All @@ -291,16 +311,10 @@ func commonChecksValidators(
math.Slot,
any,
],
bs *TestBeaconStateT,
val *types.Validator,
dep *types.Deposit,
) {
t.Helper()

idx, err := bs.ValidatorIndexByPubkey(dep.Pubkey)
require.NoError(t, err)

val, err := bs.ValidatorByIndex(idx)
require.NoError(t, err)
require.Equal(t, dep.Pubkey, val.Pubkey)

var (
Expand Down
77 changes: 77 additions & 0 deletions state-transition/core/state_processor_rewards_penalties.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: BUSL-1.1
//
// Copyright (C) 2024, Berachain Foundation. All rights reserved.
// Use of this software is governed by the Business Source License included
// in the LICENSE file of this repository and at www.mariadb.com/bsl11.
//
// ANY USE OF THE LICENSED WORK IN VIOLATION OF THIS LICENSE WILL AUTOMATICALLY
// TERMINATE YOUR RIGHTS UNDER THIS LICENSE FOR THE CURRENT AND ALL OTHER
// VERSIONS OF THE LICENSED WORK.
//
// THIS LICENSE DOES NOT GRANT YOU ANY RIGHT IN ANY TRADEMARK OR LOGO OF
// LICENSOR OR ITS AFFILIATES (PROVIDED THAT YOU MAY USE A TRADEMARK OR LOGO OF
// LICENSOR AS EXPRESSLY REQUIRED BY THIS LICENSE).
//
// TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
// AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
// EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
// TITLE.

package core

import (
"github.com/berachain/beacon-kit/config/spec"
"github.com/berachain/beacon-kit/primitives/constants"
"github.com/berachain/beacon-kit/primitives/math"
)

func (sp *StateProcessor[
_, _, _, BeaconStateT, _, _, _, _, _, _, _, _, _, _, _, _, _,
]) processRewardsAndPenalties(st BeaconStateT) error {
abi87 marked this conversation as resolved.
Show resolved Hide resolved
slot, err := st.GetSlot()
if err != nil {
return err
}

// processRewardsAndPenalties does not really do anything right now.
// However we cannot simply drop it because appHash accounts
// for the list of operations carried out over the state
// even if the operations does not affect the final state
// (rewards and penalties are always zero at this stage of beaconKit)

switch {
case sp.cs.DepositEth1ChainID() == spec.BartioChainID:
// go head doing the processing, eve
case sp.cs.DepositEth1ChainID() == spec.BoonetEth1ChainID &&
slot < math.U64(spec.BoonetFork3Height):
default:
// no real need to perform hollowProcessRewardsAndPenalties
return nil
}
abi87 marked this conversation as resolved.
Show resolved Hide resolved

if sp.cs.SlotToEpoch(slot) == math.U64(constants.GenesisEpoch) {
return nil
}

// this has been simplified to make clear that
// we are not really doing anything here
valCount, err := st.GetTotalValidators()
if err != nil {
return err
}

for i := range valCount {
// Increase the balance of the validator.
if err = st.IncreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}

// Decrease the balance of the validator.
if err = st.DecreaseBalance(math.ValidatorIndex(i), 0); err != nil {
return err
}
}
abi87 marked this conversation as resolved.
Show resolved Hide resolved

return nil
}
Loading
Loading