helpers

package
v5.1.3-rc.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 4, 2024 License: GPL-3.0 Imports: 35 Imported by: 0

Documentation

Overview

Package helpers contains helper functions outlined in the Ethereum Beacon Chain spec, such as computing committees, randao, rewards/penalties, and more.

Package helpers contains helper functions outlined in the Ethereum Beacon Chain spec, such as computing committees, randao, rewards/penalties, and more.

Index

Constants

This section is empty.

Variables

View Source
var (
	CommitteeCacheInProgressHit = promauto.NewCounter(prometheus.CounterOpts{
		Name: "committee_cache_in_progress_hit",
		Help: "The number of committee requests that are present in the cache.",
	})
)
View Source
var (
	ErrTooLate = errors.New("attestation is too late")
)

Functions

func ActivationExitChurnLimit added in v5.1.0

func ActivationExitChurnLimit(activeBalance primitives.Gwei) primitives.Gwei

ActivationExitChurnLimit for the current active balance, in gwei. New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251

Spec definition:

def get_activation_exit_churn_limit(state: BeaconState) -> Gwei:
    """
    Return the churn limit for the current epoch dedicated to activations and exits.
    """
    return min(MAX_PER_EPOCH_ACTIVATION_EXIT_CHURN_LIMIT, get_balance_churn_limit(state))

func ActivationExitEpoch

func ActivationExitEpoch(epoch primitives.Epoch) primitives.Epoch

ActivationExitEpoch takes in epoch number and returns when the validator is eligible for activation and exit.

Spec pseudocode definition:

def compute_activation_exit_epoch(epoch: Epoch) -> Epoch:
  """
  Return the epoch during which validator activations and exits initiated in ``epoch`` take effect.
  """
  return Epoch(epoch + 1 + MAX_SEED_LOOKAHEAD)

func ActiveValidatorCount

func ActiveValidatorCount(ctx context.Context, s state.ReadOnlyBeaconState, epoch primitives.Epoch) (uint64, error)

ActiveValidatorCount returns the number of active validators in the state at the given epoch.

func ActiveValidatorIndices

func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]primitives.ValidatorIndex, error)

ActiveValidatorIndices filters out active validators based on validator status and returns their indices in a list.

WARNING: This method allocates a new copy of the validator index set and is considered to be very memory expensive. Avoid using this unless you really need the active validator indices for some specific reason.

Spec pseudocode definition:

def get_active_validator_indices(state: BeaconState, epoch: Epoch) -> Sequence[ValidatorIndex]:
  """
  Return the sequence of active validator indices at ``epoch``.
  """
  return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)]

func AttestationCommittees added in v5.1.0

func AttestationCommittees(ctx context.Context, st state.ReadOnlyBeaconState, att ethpb.Att) ([][]primitives.ValidatorIndex, error)

AttestationCommittees returns beacon state committees that reflect attestation's committee indices.

func BalanceChurnLimit added in v5.1.0

func BalanceChurnLimit(activeBalance primitives.Gwei) primitives.Gwei

BalanceChurnLimit for the current active balance, in gwei. New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251

Spec definition:

def get_balance_churn_limit(state: BeaconState) -> Gwei:
    """
    Return the churn limit for the current epoch.
    """
    churn = max(
        MIN_PER_EPOCH_CHURN_LIMIT_ELECTRA,
        get_total_active_balance(state) // CHURN_LIMIT_QUOTIENT
    )
    return churn - churn % EFFECTIVE_BALANCE_INCREMENT

func BeaconCommittee

func BeaconCommittee(
	ctx context.Context,
	validatorIndices []primitives.ValidatorIndex,
	seed [32]byte,
	slot primitives.Slot,
	committeeIndex primitives.CommitteeIndex,
) ([]primitives.ValidatorIndex, error)

BeaconCommittee returns the beacon committee of a given slot and committee index. The validator indices and seed are provided as an argument rather than an imported implementation from the spec definition. Having them as an argument allows for cheaper computation run time.

Spec pseudocode definition:

def get_beacon_committee(state: BeaconState, slot: Slot, index: CommitteeIndex) -> Sequence[ValidatorIndex]:
 """
 Return the beacon committee at ``slot`` for ``index``.
 """
 epoch = compute_epoch_at_slot(slot)
 committees_per_slot = get_committee_count_per_slot(state, epoch)
 return compute_committee(
     indices=get_active_validator_indices(state, epoch),
     seed=get_seed(state, epoch, DOMAIN_BEACON_ATTESTER),
     index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index,
     count=committees_per_slot * SLOTS_PER_EPOCH,
 )

func BeaconCommitteeFromState

func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconState, slot primitives.Slot, committeeIndex primitives.CommitteeIndex) ([]primitives.ValidatorIndex, error)

BeaconCommitteeFromState returns the crosslink committee of a given slot and committee index. This is a spec implementation where state is used as an argument. In case of state retrieval becomes expensive, consider using BeaconCommittee below.

Spec pseudocode definition:

def get_beacon_committee(state: BeaconState, slot: Slot, index: CommitteeIndex) -> Sequence[ValidatorIndex]:
 """
 Return the beacon committee at ``slot`` for ``index``.
 """
 epoch = compute_epoch_at_slot(slot)
 committees_per_slot = get_committee_count_per_slot(state, epoch)
 return compute_committee(
     indices=get_active_validator_indices(state, epoch),
     seed=get_seed(state, epoch, DOMAIN_BEACON_ATTESTER),
     index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index,
     count=committees_per_slot * SLOTS_PER_EPOCH,
 )

func BeaconCommittees added in v5.1.0

func BeaconCommittees(ctx context.Context, state state.ReadOnlyBeaconState, slot primitives.Slot) ([][]primitives.ValidatorIndex, error)

BeaconCommittees returns the list of all beacon committees for a given state at a given slot.

func BeaconProposerIndex

func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) (primitives.ValidatorIndex, error)

BeaconProposerIndex returns proposer index of a current slot.

Spec pseudocode definition:

def get_beacon_proposer_index(state: BeaconState) -> ValidatorIndex:
  """
  Return the beacon proposer index at the current slot.
  """
  epoch = get_current_epoch(state)
  seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + uint_to_bytes(state.slot))
  indices = get_active_validator_indices(state, epoch)
  return compute_proposer_index(state, indices, seed)

func BeaconProposerIndexAtSlot

func BeaconProposerIndexAtSlot(ctx context.Context, state state.ReadOnlyBeaconState, slot primitives.Slot) (primitives.ValidatorIndex, error)

BeaconProposerIndexAtSlot returns proposer index at the given slot from the point of view of the given state as head state

func BlockRoot

func BlockRoot(state state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]byte, error)

BlockRoot returns the block root stored in the BeaconState for epoch start slot.

Spec pseudocode definition:

def get_block_root(state: BeaconState, epoch: Epoch) -> Root:
  """
  Return the block root at the start of a recent ``epoch``.
  """
  return get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch))

func BlockRootAtSlot

func BlockRootAtSlot(state state.ReadOnlyBeaconState, slot primitives.Slot) ([]byte, error)

BlockRootAtSlot returns the block root stored in the BeaconState for a recent slot. It returns an error if the requested block root is not within the slot range.

Spec pseudocode definition:

def get_block_root_at_slot(state: BeaconState, slot: Slot) -> Root:
  """
  Return the block root at a recent ``slot``.
  """
  assert slot < state.slot <= slot + SLOTS_PER_HISTORICAL_ROOT
  return state.block_roots[slot % SLOTS_PER_HISTORICAL_ROOT]

func ClearCache

func ClearCache()

ClearCache clears the beacon committee cache and sync committee cache.

func CommitteeAssignments

func CommitteeAssignments(ctx context.Context, state state.BeaconState, epoch primitives.Epoch, validators []primitives.ValidatorIndex) (map[primitives.ValidatorIndex]*CommitteeAssignment, error)

CommitteeAssignments calculates committee assignments for each validator during the specified epoch. It retrieves active validator indices, determines the number of committees per slot, and computes assignments for each validator based on their presence in the provided validators slice.

func CommitteeIndices added in v5.1.0

func CommitteeIndices(committeeBits bitfield.Bitfield) []primitives.CommitteeIndex

CommitteeIndices return beacon committee indices corresponding to bits that are set on the argument bitfield.

Spec pseudocode definition:

def get_committee_indices(committee_bits: Bitvector) -> Sequence[CommitteeIndex]:
   return [CommitteeIndex(index) for index, bit in enumerate(committee_bits) if bit]

func CompressCommitteeCache added in v5.0.2

func CompressCommitteeCache()

CompressCommitteeCache resizes the cache to a lower limit.

func ComputeCommittee added in v5.0.4

func ComputeCommittee(
	indices []primitives.ValidatorIndex,
	seed [32]byte,
	index, count uint64,
) ([]primitives.ValidatorIndex, error)

ComputeCommittee returns the requested shuffled committee out of the total committees using validator indices and seed.

Spec pseudocode definition:

def compute_committee(indices: Sequence[ValidatorIndex],
                    seed: Bytes32,
                    index: uint64,
                    count: uint64) -> Sequence[ValidatorIndex]:
  """
  Return the committee corresponding to ``indices``, ``seed``, ``index``, and committee ``count``.
  """
  start = (len(indices) * index) // count
  end = (len(indices) * uint64(index + 1)) // count
  return [indices[compute_shuffled_index(uint64(i), uint64(len(indices)), seed)] for i in range(start, end)]

func ComputeProposerIndex

func ComputeProposerIndex(bState state.ReadOnlyBeaconState, activeIndices []primitives.ValidatorIndex, seed [32]byte) (primitives.ValidatorIndex, error)

ComputeProposerIndex returns the index sampled by effective balance, which is used to calculate proposer.

nolint:dupword Spec pseudocode definition:

def compute_proposer_index(state: BeaconState, indices: Sequence[ValidatorIndex], seed: Bytes32) -> ValidatorIndex:
  """
  Return from ``indices`` a random index sampled by effective balance.
  """
  assert len(indices) > 0
  MAX_RANDOM_BYTE = 2**8 - 1
  i = uint64(0)
  total = uint64(len(indices))
  while True:
      candidate_index = indices[compute_shuffled_index(i % total, total, seed)]
      random_byte = hash(seed + uint_to_bytes(uint64(i // 32)))[i % 32]
      effective_balance = state.validators[candidate_index].effective_balance
      if effective_balance * MAX_RANDOM_BYTE >= MAX_EFFECTIVE_BALANCE_ELECTRA * random_byte: #[Modified in Electra:EIP7251]
          return candidate_index
      i += 1

func ComputeShuffledIndex

func ComputeShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte, shuffle bool) (primitives.ValidatorIndex, error)

ComputeShuffledIndex returns the shuffled validator index corresponding to seed and index count. Spec pseudocode definition:

def compute_shuffled_index(index: uint64, index_count: uint64, seed: Bytes32) -> uint64:
 """
 Return the shuffled index corresponding to ``seed`` (and ``index_count``).
 """
 assert index < index_count

 # Swap or not (https://link.springer.com/content/pdf/10.1007%2F978-3-642-32009-5_1.pdf)
 # See the 'generalized domain' algorithm on page 3
 for current_round in range(SHUFFLE_ROUND_COUNT):
     pivot = bytes_to_uint64(hash(seed + uint_to_bytes(uint8(current_round)))[0:8]) % index_count
     flip = (pivot + index_count - index) % index_count
     position = max(index, flip)
     source = hash(
         seed
         + uint_to_bytes(uint8(current_round))
         + uint_to_bytes(uint32(position // 256))
     )
     byte = uint8(source[(position % 256) // 8])
     bit = (byte >> (position % 8)) % 2
     index = flip if bit else index

 return index

func ComputeSubnetForAttestation

func ComputeSubnetForAttestation(activeValCount uint64, att ethpb.Att) uint64

ComputeSubnetForAttestation returns the subnet for which the provided attestation will be broadcasted to. This differs from the spec definition by instead passing in the active validators indices in the attestation's given epoch.

Spec pseudocode definition: def compute_subnet_for_attestation(committees_per_slot: uint64, slot: Slot, committee_index: CommitteeIndex) -> uint64:

"""
Compute the correct subnet for an attestation for Phase 0.
Note, this mimics expected future behavior where attestations will be mapped to their shard subnet.
"""
slots_since_epoch_start = uint64(slot % SLOTS_PER_EPOCH)
committees_since_epoch_start = committees_per_slot * slots_since_epoch_start

return uint64((committees_since_epoch_start + committee_index) % ATTESTATION_SUBNET_COUNT)

func ComputeSubnetFromCommitteeAndSlot

func ComputeSubnetFromCommitteeAndSlot(activeValCount uint64, comIdx primitives.CommitteeIndex, attSlot primitives.Slot) uint64

ComputeSubnetFromCommitteeAndSlot is a flattened version of ComputeSubnetForAttestation where we only pass in the relevant fields from the attestation as function arguments.

Spec pseudocode definition: def compute_subnet_for_attestation(committees_per_slot: uint64, slot: Slot, committee_index: CommitteeIndex) -> uint64:

"""
Compute the correct subnet for an attestation for Phase 0.
Note, this mimics expected future behavior where attestations will be mapped to their shard subnet.
"""
slots_since_epoch_start = uint64(slot % SLOTS_PER_EPOCH)
committees_since_epoch_start = committees_per_slot * slots_since_epoch_start

return uint64((committees_since_epoch_start + committee_index) % ATTESTATION_SUBNET_COUNT)

func ComputeWeakSubjectivityPeriod

func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (primitives.Epoch, error)

ComputeWeakSubjectivityPeriod returns weak subjectivity period for the active validator count and finalized epoch.

Reference spec implementation: https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/weak-subjectivity.md#calculating-the-weak-subjectivity-period

def compute_weak_subjectivity_period(state: BeaconState) -> uint64:

"""
Returns the weak subjectivity period for the current ``state``.
This computation takes into account the effect of:
    - validator set churn (bounded by ``get_validator_churn_limit()`` per epoch), and
    - validator balance top-ups (bounded by ``MAX_DEPOSITS * SLOTS_PER_EPOCH`` per epoch).
A detailed calculation can be found at:
https://github.com/runtimeverification/beacon-chain-verification/blob/master/weak-subjectivity/weak-subjectivity-analysis.pdf
"""
ws_period = MIN_VALIDATOR_WITHDRAWABILITY_DELAY
N = len(get_active_validator_indices(state, get_current_epoch(state)))
t = get_total_active_balance(state) // N // ETH_TO_GWEI
T = MAX_EFFECTIVE_BALANCE // ETH_TO_GWEI
delta = get_validator_churn_limit(state)
Delta = MAX_DEPOSITS * SLOTS_PER_EPOCH
D = SAFETY_DECAY

if T * (200 + 3 * D) < t * (200 + 12 * D):
    epochs_for_validator_set_churn = (
        N * (t * (200 + 12 * D) - T * (200 + 3 * D)) // (600 * delta * (2 * t + T))
    )
    epochs_for_balance_top_ups = (
        N * (200 + 3 * D) // (600 * Delta)
    )
    ws_period += max(epochs_for_validator_set_churn, epochs_for_balance_top_ups)
else:
    ws_period += (
        3 * N * D * t // (200 * Delta * (T - t))
    )

return ws_period

func ConsolidationChurnLimit added in v5.1.0

func ConsolidationChurnLimit(activeBalance primitives.Gwei) primitives.Gwei

ConsolidationChurnLimit for the current active balance, in gwei. New in EIP-7251: https://eips.ethereum.org/EIPS/eip-7251

Spec definition:

def get_consolidation_churn_limit(state: BeaconState) -> Gwei:
    return get_balance_churn_limit(state) - get_activation_exit_churn_limit(state)

func CurrentPeriodSyncSubcommitteeIndices

func CurrentPeriodSyncSubcommitteeIndices(
	st state.BeaconState, valIdx primitives.ValidatorIndex,
) ([]primitives.CommitteeIndex, error)

CurrentPeriodSyncSubcommitteeIndices returns the subcommittee indices of the current period sync committee for input validator.

func DecreaseBalance

func DecreaseBalance(state state.BeaconState, idx primitives.ValidatorIndex, delta uint64) error

DecreaseBalance decreases validator with the given 'index' balance by 'delta' in Gwei.

Spec pseudocode definition:

def decrease_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
  """
  Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
  """
  state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta

func DecreaseBalanceWithVal

func DecreaseBalanceWithVal(currBalance, delta uint64) uint64

DecreaseBalanceWithVal decreases validator with the given 'index' balance by 'delta' in Gwei. This method is flattened version of the spec method, taking in the raw balance and returning the post balance.

Spec pseudocode definition:

def decrease_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
  """
  Decrease the validator balance at index ``index`` by ``delta``, with underflow protection.
  """
  state.balances[index] = 0 if delta > state.balances[index] else state.balances[index] - delta

func ExpandCommitteeCache added in v5.0.2

func ExpandCommitteeCache()

ExpandCommitteeCache resizes the cache to a higher limit.

func FinalityDelay

func FinalityDelay(prevEpoch, finalizedEpoch primitives.Epoch) primitives.Epoch

FinalityDelay returns the finality delay using the beacon state.

Spec code: def get_finality_delay(state: BeaconState) -> uint64:

return get_previous_epoch(state) - state.finalized_checkpoint.epoch

func HasCompoundingWithdrawalCredential added in v5.1.0

func HasCompoundingWithdrawalCredential(v interfaces.WithWithdrawalCredentials) bool

HasCompoundingWithdrawalCredential checks if the validator has a compounding withdrawal credential. New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251

Spec definition:

def has_compounding_withdrawal_credential(validator: Validator) -> bool:
    """
    Check if ``validator`` has an 0x02 prefixed "compounding" withdrawal credential.
    """
    return is_compounding_withdrawal_credential(validator.withdrawal_credentials)

func HasETH1WithdrawalCredential added in v5.1.0

func HasETH1WithdrawalCredential(val interfaces.WithWithdrawalCredentials) bool

hasETH1WithdrawalCredential returns whether the validator has an ETH1 Withdrawal prefix. It assumes that the caller has a lock on the state

func HasExecutionWithdrawalCredentials added in v5.1.0

func HasExecutionWithdrawalCredentials(v interfaces.WithWithdrawalCredentials) bool

HasExecutionWithdrawalCredentials checks if the validator has an execution withdrawal credential or compounding credential. New in Electra EIP-7251: https://eips.ethereum.org/EIPS/eip-7251

Spec definition:

def has_execution_withdrawal_credential(validator: Validator) -> bool:
    """
    Check if ``validator`` has a 0x01 or 0x02 prefixed withdrawal credential.
    """
    return has_compounding_withdrawal_credential(validator) or has_eth1_withdrawal_credential(validator)

func IncreaseBalance

func IncreaseBalance(state state.BeaconState, idx primitives.ValidatorIndex, delta uint64) error

IncreaseBalance increases validator with the given 'index' balance by 'delta' in Gwei.

Spec pseudocode definition:

def increase_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
  """
  Increase the validator balance at index ``index`` by ``delta``.
  """
  state.balances[index] += delta

func IncreaseBalanceWithVal

func IncreaseBalanceWithVal(currBalance, delta uint64) (uint64, error)

IncreaseBalanceWithVal increases validator with the given 'index' balance by 'delta' in Gwei. This method is flattened version of the spec method, taking in the raw balance and returning the post balance.

Spec pseudocode definition:

def increase_balance(state: BeaconState, index: ValidatorIndex, delta: Gwei) -> None:
  """
  Increase the validator balance at index ``index`` by ``delta``.
  """
  state.balances[index] += delta

func IsActiveNonSlashedValidatorUsingTrie

func IsActiveNonSlashedValidatorUsingTrie(validator state.ReadOnlyValidator, epoch primitives.Epoch) bool

IsActiveNonSlashedValidatorUsingTrie checks if a read only validator is active and not slashed

func IsActiveValidator

func IsActiveValidator(validator *ethpb.Validator, epoch primitives.Epoch) bool

IsActiveValidator returns the boolean value on whether the validator is active or not.

Spec pseudocode definition:

def is_active_validator(validator: Validator, epoch: Epoch) -> bool:
  """
  Check if ``validator`` is active.
  """
  return validator.activation_epoch <= epoch < validator.exit_epoch

func IsActiveValidatorUsingTrie

func IsActiveValidatorUsingTrie(validator state.ReadOnlyValidator, epoch primitives.Epoch) bool

IsActiveValidatorUsingTrie checks if a read only validator is active.

func IsAggregated

func IsAggregated(attestation ethpb.Att) bool

IsAggregated returns true if the attestation is an aggregated attestation, false otherwise.

func IsAggregator

func IsAggregator(committeeCount uint64, slotSig []byte) (bool, error)

IsAggregator returns true if the signature is from the input validator. The committee count is provided as an argument rather than imported implementation from spec. Having committee count as an argument allows cheaper computation at run time.

Spec pseudocode definition:

def is_aggregator(state: BeaconState, slot: Slot, index: CommitteeIndex, slot_signature: BLSSignature) -> bool:
 committee = get_beacon_committee(state, slot, index)
 modulo = max(1, len(committee) // TARGET_AGGREGATORS_PER_COMMITTEE)
 return bytes_to_uint64(hash(slot_signature)[0:8]) % modulo == 0

func IsCompoundingWithdrawalCredential added in v5.1.0

func IsCompoundingWithdrawalCredential(creds []byte) bool

IsCompoundingWithdrawalCredential checks if the credentials are a compounding withdrawal credential.

Spec definition:

def is_compounding_withdrawal_credential(withdrawal_credentials: Bytes32) -> bool:
    return withdrawal_credentials[:1] == COMPOUNDING_WITHDRAWAL_PREFIX

func IsCurrentPeriodSyncCommittee

func IsCurrentPeriodSyncCommittee(st state.BeaconState, valIdx primitives.ValidatorIndex) (bool, error)

IsCurrentPeriodSyncCommittee returns true if the input validator index belongs in the current period sync committee along with the sync committee root. 1. Checks if the public key exists in the sync committee cache 2. If 1 fails, checks if the public key exists in the input current sync committee object

func IsEligibleForActivation

func IsEligibleForActivation(state state.ReadOnlyCheckpoint, validator *ethpb.Validator) bool

IsEligibleForActivation checks if the validator is eligible for activation.

Spec pseudocode definition:

def is_eligible_for_activation(state: BeaconState, validator: Validator) -> bool:
  """
  Check if ``validator`` is eligible for activation.
  """
  return (
      # Placement in queue is finalized
      validator.activation_eligibility_epoch <= state.finalized_checkpoint.epoch
      # Has not yet been activated
      and validator.activation_epoch == FAR_FUTURE_EPOCH
  )

func IsEligibleForActivationQueue

func IsEligibleForActivationQueue(validator state.ReadOnlyValidator, currentEpoch primitives.Epoch) bool

IsEligibleForActivationQueue checks if the validator is eligible to be placed into the activation queue.

Spec definition:

def is_eligible_for_activation_queue(validator: Validator) -> bool:
    """
    Check if ``validator`` is eligible to be placed into the activation queue.
    """
    return (
        validator.activation_eligibility_epoch == FAR_FUTURE_EPOCH
        and validator.effective_balance >= MIN_ACTIVATION_BALANCE  # [Modified in Electra:EIP7251]
    )

func IsEligibleForActivationUsingROVal added in v5.1.0

func IsEligibleForActivationUsingROVal(state state.ReadOnlyCheckpoint, validator state.ReadOnlyValidator) bool

IsEligibleForActivationUsingROVal checks if the validator is eligible for activation using the provided read only validator.

func IsFullyWithdrawableValidator added in v5.1.0

func IsFullyWithdrawableValidator(val state.ReadOnlyValidator, balance uint64, epoch primitives.Epoch, fork int) bool

IsFullyWithdrawableValidator returns whether the validator is able to perform a full withdrawal. This function assumes that the caller holds a lock on the state.

Spec definition:

def is_fully_withdrawable_validator(validator: Validator, balance: Gwei, epoch: Epoch) -> bool:
    """
    Check if ``validator`` is fully withdrawable.
    """
    return (
        has_execution_withdrawal_credential(validator)  # [Modified in Electra:EIP7251]
        and validator.withdrawable_epoch <= epoch
        and balance > 0
    )

func IsInInactivityLeak

func IsInInactivityLeak(prevEpoch, finalizedEpoch primitives.Epoch) bool

IsInInactivityLeak returns true if the state is experiencing inactivity leak.

Spec code: def is_in_inactivity_leak(state: BeaconState) -> bool:

return get_finality_delay(state) > MIN_EPOCHS_TO_INACTIVITY_PENALTY

func IsNextPeriodSyncCommittee

func IsNextPeriodSyncCommittee(
	st state.BeaconState, valIdx primitives.ValidatorIndex,
) (bool, error)

IsNextPeriodSyncCommittee returns true if the input validator index belongs in the next period sync committee along with the sync period boundary root. 1. Checks if the public key exists in the sync committee cache 2. If 1 fails, checks if the public key exists in the input next sync committee object

func IsPartiallyWithdrawableValidator added in v5.1.0

func IsPartiallyWithdrawableValidator(val state.ReadOnlyValidator, balance uint64, epoch primitives.Epoch, fork int) bool

IsPartiallyWithdrawableValidator returns whether the validator is able to perform a partial withdrawal. This function assumes that the caller has a lock on the state. This method conditionally calls the fork appropriate implementation based on the epoch argument.

func IsSameWithdrawalCredentials added in v5.1.0

func IsSameWithdrawalCredentials(a, b *ethpb.Validator) bool

IsSameWithdrawalCredentials returns true if both validators have the same withdrawal credentials.

return a.withdrawal_credentials[12:] == b.withdrawal_credentials[12:]

func IsSlashableValidator

func IsSlashableValidator(activationEpoch, withdrawableEpoch primitives.Epoch, slashed bool, epoch primitives.Epoch) bool

IsSlashableValidator returns the boolean value on whether the validator is slashable or not.

Spec pseudocode definition:

def is_slashable_validator(validator: Validator, epoch: Epoch) -> bool:
"""
Check if ``validator`` is slashable.
"""
return (not validator.slashed) and (validator.activation_epoch <= epoch < validator.withdrawable_epoch)

func IsSlashableValidatorUsingTrie

func IsSlashableValidatorUsingTrie(val state.ReadOnlyValidator, epoch primitives.Epoch) bool

IsSlashableValidatorUsingTrie checks if a read only validator is slashable.

func IsWithinWeakSubjectivityPeriod

func IsWithinWeakSubjectivityPeriod(
	ctx context.Context, currentEpoch primitives.Epoch, wsState state.ReadOnlyBeaconState, wsStateRoot [fieldparams.RootLength]byte, wsEpoch primitives.Epoch, cfg *params.BeaconChainConfig) (bool, error)

IsWithinWeakSubjectivityPeriod verifies if a given weak subjectivity checkpoint is not stale i.e. the current node is so far beyond, that a given state and checkpoint are not for the latest weak subjectivity point. Provided checkpoint still can be used to double-check that node's block root at a given epoch matches that of the checkpoint.

Reference implementation: https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/weak-subjectivity.md#checking-for-stale-weak-subjectivity-checkpoint

def is_within_weak_subjectivity_period(store: Store, ws_state: BeaconState, ws_checkpoint: Checkpoint) -> bool:

# Clients may choose to validate the input state against the input Weak Subjectivity Checkpoint
assert ws_state.latest_block_header.state_root == ws_checkpoint.root
assert compute_epoch_at_slot(ws_state.slot) == ws_checkpoint.epoch

ws_period = compute_weak_subjectivity_period(ws_state)
ws_state_epoch = compute_epoch_at_slot(ws_state.slot)
current_epoch = compute_epoch_at_slot(get_current_slot(store))
return current_epoch <= ws_state_epoch + ws_period

func LastActivatedValidatorIndex

func LastActivatedValidatorIndex(ctx context.Context, st state.ReadOnlyBeaconState) (primitives.ValidatorIndex, error)

LastActivatedValidatorIndex provides the last activated validator given a state

func LatestWeakSubjectivityEpoch

func LatestWeakSubjectivityEpoch(ctx context.Context, st state.ReadOnlyBeaconState, cfg *params.BeaconChainConfig) (primitives.Epoch, error)

LatestWeakSubjectivityEpoch returns epoch of the most recent weak subjectivity checkpoint known to a node.

Within the weak subjectivity period, if two conflicting blocks are finalized, 1/3 - D (D := safety decay) of validators will get slashed. Therefore, it is safe to assume that any finalized checkpoint within that period is protected by this safety margin.

func MinEpochsForBlockRequests

func MinEpochsForBlockRequests() primitives.Epoch

MinEpochsForBlockRequests computes the number of epochs of block history that we need to maintain, relative to the current epoch, per the p2p specs. This is used to compute the slot where backfill is complete. value defined: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#configuration MIN_VALIDATOR_WITHDRAWABILITY_DELAY + CHURN_LIMIT_QUOTIENT // 2 (= 33024, ~5 months) detailed rationale: https://github.com/ethereum/consensus-specs/blob/dev/specs/phase0/p2p-interface.md#why-are-blocksbyrange-requests-only-required-to-be-served-for-the-latest-min_epochs_for_block_requests-epochs

func NextPeriodSyncSubcommitteeIndices

func NextPeriodSyncSubcommitteeIndices(
	st state.BeaconState, valIdx primitives.ValidatorIndex,
) ([]primitives.CommitteeIndex, error)

NextPeriodSyncSubcommitteeIndices returns the subcommittee indices of the next period sync committee for input validator.

func ParseWeakSubjectivityInputString

func ParseWeakSubjectivityInputString(wsCheckpointString string) (*v1alpha1.Checkpoint, error)

ParseWeakSubjectivityInputString parses "blocks_root:epoch_number" string into a checkpoint.

func PrecomputeProposerIndices added in v5.0.4

func PrecomputeProposerIndices(state state.ReadOnlyBeaconState, activeIndices []primitives.ValidatorIndex, e primitives.Epoch) ([]primitives.ValidatorIndex, error)

PrecomputeProposerIndices computes proposer indices of the current epoch and returns a list of proposer indices, the index of the list represents the slot number.

func ProposerAssignments added in v5.0.4

func ProposerAssignments(ctx context.Context, state state.BeaconState, epoch primitives.Epoch) (map[primitives.ValidatorIndex][]primitives.Slot, error)

ProposerAssignments calculates proposer assignments for each validator during the specified epoch. It verifies the validity of the epoch, then iterates through each slot in the epoch to determine the proposer for that slot and assigns them accordingly.

func ProposerIndexAtSlotFromCheckpoint

func ProposerIndexAtSlotFromCheckpoint(c *forkchoicetypes.Checkpoint, slot primitives.Slot) (primitives.ValidatorIndex, error)

ProposerIndexAtSlotFromCheckpoint returns the proposer index at the given slot from the cache at the given checkpoint

func RandaoMix

func RandaoMix(state state.ReadOnlyBeaconState, epoch primitives.Epoch) ([]byte, error)

RandaoMix returns the randao mix (xor'ed seed) of a given slot. It is used to shuffle validators.

Spec pseudocode definition:

def get_randao_mix(state: BeaconState, epoch: Epoch) -> Bytes32:
 """
 Return the randao mix at a recent ``epoch``.
 """
 return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR]

func Seed

func Seed(state state.ReadOnlyBeaconState, epoch primitives.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error)

Seed returns the randao seed used for shuffling of a given epoch.

Spec pseudocode definition:

def get_seed(state: BeaconState, epoch: Epoch, domain_type: DomainType) -> Bytes32:
  """
  Return the seed at ``epoch``.
  """
  mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1))  # Avoid underflow
  return hash(domain_type + uint_to_bytes(epoch) + mix)

func ShuffleList

func ShuffleList(input []primitives.ValidatorIndex, seed [32]byte) ([]primitives.ValidatorIndex, error)

ShuffleList returns list of shuffled indexes in a pseudorandom permutation `p` of `0...list_size - 1` with “seed“ as entropy. We utilize 'swap or not' shuffling in this implementation; we are allocating the memory with the seed that stays constant between iterations instead of reallocating it each iteration as in the spec. This implementation is based on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle

improvements:
 - seed is always the first 32 bytes of the hash input, we just copy it into the buffer one time.
 - add round byte to seed and hash that part of the buffer.
 - split up the for-loop in two:
  1. Handle the part from 0 (incl) to pivot (incl). This is mirrored around (pivot / 2).
  2. Handle the part from pivot (excl) to N (excl). This is mirrored around ((pivot / 2) + (size/2)).
 - hash source every 256 iterations.
 - change byteV every 8 iterations.
 - we start at the edges, and work back to the mirror point.
   this makes us process each pear exactly once (instead of unnecessarily twice, like in the spec).

func ShuffledIndex

func ShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte) (primitives.ValidatorIndex, error)

ShuffledIndex returns `p(index)` in a pseudorandom permutation `p` of `0...list_size - 1` with “seed“ as entropy. We utilize 'swap or not' shuffling in this implementation; we are allocating the memory with the seed that stays constant between iterations instead of reallocating it each iteration as in the spec. This implementation is based on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle

func ShuffledIndices

ShuffledIndices uses input beacon state and returns the shuffled indices of the input epoch, the shuffled indices then can be used to break up into committees.

func SlotCommitteeCount

func SlotCommitteeCount(activeValidatorCount uint64) uint64

SlotCommitteeCount returns the number of beacon committees of a slot. The active validator count is provided as an argument rather than an imported implementation from the spec definition. Having the active validator count as an argument allows for cheaper computation, instead of retrieving head state, one can retrieve the validator count.

Spec pseudocode definition:

def get_committee_count_per_slot(state: BeaconState, epoch: Epoch) -> uint64:
 """
 Return the number of committees in each slot for the given ``epoch``.
 """
 return max(uint64(1), min(
     MAX_COMMITTEES_PER_SLOT,
     uint64(len(get_active_validator_indices(state, epoch))) // SLOTS_PER_EPOCH // TARGET_COMMITTEE_SIZE,
 ))

func SplitIndices

func SplitIndices(l []uint64, n uint64) [][]uint64

SplitIndices splits a list into n pieces.

func StateRootAtSlot

func StateRootAtSlot(state state.ReadOnlyBeaconState, slot primitives.Slot) ([]byte, error)

StateRootAtSlot returns the cached state root at that particular slot. If no state root has been cached it will return a zero-hash.

func SyncPeriodBoundaryRoot added in v5.0.4

func SyncPeriodBoundaryRoot(st state.ReadOnlyBeaconState) ([32]byte, error)

SyncPeriodBoundaryRoot computes the current sync period boundary root by calculating sync period start epoch and calling `BlockRoot`. It uses the boundary slot - 1 for block root. (Ex: SlotsPerEpoch * EpochsPerSyncCommitteePeriod - 1)

func TotalActiveBalance

func TotalActiveBalance(s state.ReadOnlyBeaconState) (uint64, error)

TotalActiveBalance returns the total amount at stake in Gwei of active validators.

Spec pseudocode definition:

def get_total_active_balance(state: BeaconState) -> Gwei:
 """
 Return the combined effective balance of the active validators.
 Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
 """
 return get_total_balance(state, set(get_active_validator_indices(state, get_current_epoch(state))))

func TotalBalance

func TotalBalance(state state.ReadOnlyValidators, indices []primitives.ValidatorIndex) uint64

TotalBalance returns the total amount at stake in Gwei of input validators.

Spec pseudocode definition:

def get_total_balance(state: BeaconState, indices: Set[ValidatorIndex]) -> Gwei:
 """
 Return the combined effective balance of the ``indices``.
 ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
 Math safe up to ~10B ETH, after which this overflows uint64.
 """
 return Gwei(max(EFFECTIVE_BALANCE_INCREMENT, sum([state.validators[index].effective_balance for index in indices])))

func UnShuffledIndex

func UnShuffledIndex(index primitives.ValidatorIndex, indexCount uint64, seed [32]byte) (primitives.ValidatorIndex, error)

UnShuffledIndex returns the inverse of ShuffledIndex. This implementation is based on the original implementation from protolambda, https://github.com/protolambda/eth2-shuffle

func UnshuffleList

func UnshuffleList(input []primitives.ValidatorIndex, seed [32]byte) ([]primitives.ValidatorIndex, error)

UnshuffleList un-shuffles the list by running backwards through the round count.

func UpdateCachedCheckpointToStateRoot

func UpdateCachedCheckpointToStateRoot(state state.ReadOnlyBeaconState, cp *forkchoicetypes.Checkpoint) error

UpdateCachedCheckpointToStateRoot updates the map from checkpoints to state root in the proposer indices cache

func UpdateCommitteeCache

func UpdateCommitteeCache(ctx context.Context, state state.ReadOnlyBeaconState, e primitives.Epoch) error

UpdateCommitteeCache gets called at the beginning of every epoch to cache the committee shuffled indices list with committee index and epoch number. It caches the shuffled indices for the input epoch.

func UpdateGenesisEth1Data

func UpdateGenesisEth1Data(state state.BeaconState, deposits []*ethpb.Deposit, eth1Data *ethpb.Eth1Data) (state.BeaconState, error)

UpdateGenesisEth1Data updates eth1 data for genesis state.

func UpdateProposerIndicesInCache

func UpdateProposerIndicesInCache(ctx context.Context, state state.ReadOnlyBeaconState, epoch primitives.Epoch) error

UpdateProposerIndicesInCache updates proposer indices entry of the committee cache. Input state is used to retrieve active validator indices. Input root is to use as key in the cache. Input epoch is the epoch to retrieve proposer indices for.

func UpdateSyncCommitteeCache

func UpdateSyncCommitteeCache(st state.BeaconState) error

UpdateSyncCommitteeCache updates sync committee cache. It uses `state`'s latest block header root as key. To avoid misuse, it disallows block header with state root zeroed out.

func ValidateAttestationTime

func ValidateAttestationTime(attSlot primitives.Slot, genesisTime time.Time, clockDisparity time.Duration) error

ValidateAttestationTime Validates that the incoming attestation is in the desired time range. An attestation is valid only if received within the last ATTESTATION_PROPAGATION_SLOT_RANGE slots.

Example:

ATTESTATION_PROPAGATION_SLOT_RANGE = 5
clockDisparity = 24 seconds
current_slot = 100
invalid_attestation_slot = 92
invalid_attestation_slot = 103
valid_attestation_slot = 98
valid_attestation_slot = 101

In the attestation must be within the range of 95 to 102 in the example above.

func ValidateNilAttestation

func ValidateNilAttestation(attestation ethpb.Att) error

ValidateNilAttestation checks if any composite field of input attestation is nil. Access to these nil fields will result in run time panic, it is recommended to run these checks as first line of defense.

func ValidateSlotTargetEpoch

func ValidateSlotTargetEpoch(data *ethpb.AttestationData) error

ValidateSlotTargetEpoch checks if attestation data's epoch matches target checkpoint's epoch. It is recommended to run `ValidateNilAttestation` first to ensure `data.Target` can't be nil.

func ValidatorActivationChurnLimit

func ValidatorActivationChurnLimit(activeValidatorCount uint64) uint64

ValidatorActivationChurnLimit returns the maximum number of validators that can be activated in a slot.

func ValidatorActivationChurnLimitDeneb

func ValidatorActivationChurnLimitDeneb(activeValidatorCount uint64) uint64

ValidatorActivationChurnLimitDeneb returns the maximum number of validators that can be activated in a slot post Deneb.

func ValidatorExitChurnLimit

func ValidatorExitChurnLimit(activeValidatorCount uint64) uint64

ValidatorExitChurnLimit returns the maximum number of validators that can be exited in a slot.

func ValidatorMaxEffectiveBalance added in v5.1.0

func ValidatorMaxEffectiveBalance(val state.ReadOnlyValidator) uint64

ValidatorMaxEffectiveBalance returns the maximum effective balance for a validator.

Spec definition:

def get_validator_max_effective_balance(validator: Validator) -> Gwei:
    """
    Get max effective balance for ``validator``.
    """
    if has_compounding_withdrawal_credential(validator):
        return MAX_EFFECTIVE_BALANCE_ELECTRA
    else:
        return MIN_ACTIVATION_BALANCE

func VerifyBitfieldLength

func VerifyBitfieldLength(bf bitfield.Bitfield, committeeSize uint64) error

VerifyBitfieldLength verifies that a bitfield length matches the given committee size.

func VerifyCheckpointEpoch

func VerifyCheckpointEpoch(c *ethpb.Checkpoint, genesis time.Time) bool

VerifyCheckpointEpoch is within current epoch and previous epoch with respect to current time. Returns true if it's within, false if it's not.

Types

type CommitteeAssignment added in v5.0.4

type CommitteeAssignment struct {
	Committee      []primitives.ValidatorIndex
	AttesterSlot   primitives.Slot
	CommitteeIndex primitives.CommitteeIndex
}

CommitteeAssignment represents committee list, committee index, and to be attested slot for a given epoch.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL