github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/core/helpers/rewards_penalties.go (about)

     1  package helpers
     2  
     3  import (
     4  	types "github.com/prysmaticlabs/eth2-types"
     5  	iface "github.com/prysmaticlabs/prysm/beacon-chain/state/interface"
     6  	"github.com/prysmaticlabs/prysm/shared/params"
     7  )
     8  
     9  // TotalBalance returns the total amount at stake in Gwei
    10  // of input validators.
    11  //
    12  // Spec pseudocode definition:
    13  //   def get_total_balance(state: BeaconState, indices: Set[ValidatorIndex]) -> Gwei:
    14  //    """
    15  //    Return the combined effective balance of the ``indices``.
    16  //    ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
    17  //    Math safe up to ~10B ETH, afterwhich this overflows uint64.
    18  //    """
    19  //    return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices])))
    20  func TotalBalance(state iface.ReadOnlyValidators, indices []types.ValidatorIndex) uint64 {
    21  	total := uint64(0)
    22  
    23  	for _, idx := range indices {
    24  		val, err := state.ValidatorAtIndexReadOnly(idx)
    25  		if err != nil {
    26  			continue
    27  		}
    28  		total += val.EffectiveBalance()
    29  	}
    30  
    31  	// EFFECTIVE_BALANCE_INCREMENT is the lower bound for total balance.
    32  	if total < params.BeaconConfig().EffectiveBalanceIncrement {
    33  		return params.BeaconConfig().EffectiveBalanceIncrement
    34  	}
    35  
    36  	return total
    37  }
    38  
    39  // TotalActiveBalance returns the total amount at stake in Gwei
    40  // of active validators.
    41  //
    42  // Spec pseudocode definition:
    43  //   def get_total_active_balance(state: BeaconState) -> Gwei:
    44  //    """
    45  //    Return the combined effective balance of the active validators.
    46  //    Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
    47  //    """
    48  //    return get_total_balance(state, set(get_active_validator_indices(state, get_current_epoch(state))))
    49  func TotalActiveBalance(state iface.ReadOnlyBeaconState) (uint64, error) {
    50  	total := uint64(0)
    51  	if err := state.ReadFromEveryValidator(func(idx int, val iface.ReadOnlyValidator) error {
    52  		if IsActiveValidatorUsingTrie(val, SlotToEpoch(state.Slot())) {
    53  			total += val.EffectiveBalance()
    54  		}
    55  		return nil
    56  	}); err != nil {
    57  		return 0, err
    58  	}
    59  	return total, nil
    60  }
    61  
    62  // IncreaseBalance increases validator with the given 'index' balance by 'delta' in Gwei.
    63  //
    64  // Spec pseudocode definition:
    65  //  def increase_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
    66  //    """
    67  //    Increase the validator balance at index ``index`` by ``delta``.
    68  //    """
    69  //    state.balances[index] += delta
    70  func IncreaseBalance(state iface.BeaconState, idx types.ValidatorIndex, delta uint64) error {
    71  	balAtIdx, err := state.BalanceAtIndex(idx)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	return state.UpdateBalancesAtIndex(idx, IncreaseBalanceWithVal(balAtIdx, delta))
    76  }
    77  
    78  // IncreaseBalanceWithVal increases validator with the given 'index' balance by 'delta' in Gwei.
    79  // This method is flattened version of the spec method, taking in the raw balance and returning
    80  // the post balance.
    81  //
    82  // Spec pseudocode definition:
    83  //  def increase_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
    84  //    """
    85  //    Increase the validator balance at index ``index`` by ``delta``.
    86  //    """
    87  //    state.balances[index] += delta
    88  func IncreaseBalanceWithVal(currBalance, delta uint64) uint64 {
    89  	return currBalance + delta
    90  }
    91  
    92  // DecreaseBalance decreases validator with the given 'index' balance by 'delta' in Gwei.
    93  //
    94  // Spec pseudocode definition:
    95  //  def decrease_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
    96  //    """
    97  //    Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
    98  //    """
    99  //    state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta
   100  func DecreaseBalance(state iface.BeaconState, idx types.ValidatorIndex, delta uint64) error {
   101  	balAtIdx, err := state.BalanceAtIndex(idx)
   102  	if err != nil {
   103  		return err
   104  	}
   105  	return state.UpdateBalancesAtIndex(idx, DecreaseBalanceWithVal(balAtIdx, delta))
   106  }
   107  
   108  // DecreaseBalanceWithVal decreases validator with the given 'index' balance by 'delta' in Gwei.
   109  // This method is flattened version of the spec method, taking in the raw balance and returning
   110  // the post balance.
   111  //
   112  // Spec pseudocode definition:
   113  //  def decrease_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
   114  //    """
   115  //    Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
   116  //    """
   117  //    state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta
   118  func DecreaseBalanceWithVal(currBalance, delta uint64) uint64 {
   119  	if delta > currBalance {
   120  		return 0
   121  	}
   122  	return currBalance - delta
   123  }
   124  
   125  // IsInInactivityLeak returns true if the state is experiencing inactivity leak.
   126  //
   127  // Spec code:
   128  // def is_in_inactivity_leak(state: BeaconState) -> bool:
   129  //    return get_finality_delay(state) > MIN_EPOCHS_TO_INACTIVITY_PENALTY
   130  func IsInInactivityLeak(prevEpoch, finalizedEpoch types.Epoch) bool {
   131  	return FinalityDelay(prevEpoch, finalizedEpoch) > params.BeaconConfig().MinEpochsToInactivityPenalty
   132  }
   133  
   134  // FinalityDelay returns the finality delay using the beacon state.
   135  //
   136  // Spec code:
   137  // def get_finality_delay(state: BeaconState) -> uint64:
   138  //    return get_previous_epoch(state) - state.finalized_checkpoint.epoch
   139  func FinalityDelay(prevEpoch, finalizedEpoch types.Epoch) types.Epoch {
   140  	return prevEpoch - finalizedEpoch
   141  }