github.com/prysmaticlabs/prysm@v1.4.4/beacon-chain/core/helpers/randao.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/bls"
     7  	"github.com/prysmaticlabs/prysm/shared/bytesutil"
     8  	"github.com/prysmaticlabs/prysm/shared/hashutil"
     9  	"github.com/prysmaticlabs/prysm/shared/params"
    10  )
    11  
    12  // Seed returns the randao seed used for shuffling of a given epoch.
    13  //
    14  // Spec pseudocode definition:
    15  //  def get_seed(state: BeaconState, epoch: Epoch, domain_type: DomainType) -> Bytes32:
    16  //    """
    17  //    Return the seed at ``epoch``.
    18  //    """
    19  //    mix = get_randao_mix(state, Epoch(epoch + EPOCHS_PER_HISTORICAL_VECTOR - MIN_SEED_LOOKAHEAD - 1))  # Avoid underflow
    20  //    return hash(domain_type + uint_to_bytes(epoch) + mix)
    21  func Seed(state iface.ReadOnlyBeaconState, epoch types.Epoch, domain [bls.DomainByteLength]byte) ([32]byte, error) {
    22  	// See https://github.com/ethereum/eth2.0-specs/pull/1296 for
    23  	// rationale on why offset has to look down by 1.
    24  	lookAheadEpoch := epoch + params.BeaconConfig().EpochsPerHistoricalVector -
    25  		params.BeaconConfig().MinSeedLookahead - 1
    26  
    27  	randaoMix, err := RandaoMix(state, lookAheadEpoch)
    28  	if err != nil {
    29  		return [32]byte{}, err
    30  	}
    31  	seed := append(domain[:], bytesutil.Bytes8(uint64(epoch))...)
    32  	seed = append(seed, randaoMix...)
    33  
    34  	seed32 := hashutil.Hash(seed)
    35  
    36  	return seed32, nil
    37  }
    38  
    39  // RandaoMix returns the randao mix (xor'ed seed)
    40  // of a given slot. It is used to shuffle validators.
    41  //
    42  // Spec pseudocode definition:
    43  //   def get_randao_mix(state: BeaconState, epoch: Epoch) -> Bytes32:
    44  //    """
    45  //    Return the randao mix at a recent ``epoch``.
    46  //    """
    47  //    return state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR]
    48  func RandaoMix(state iface.ReadOnlyBeaconState, epoch types.Epoch) ([]byte, error) {
    49  	return state.RandaoMixAtIndex(uint64(epoch % params.BeaconConfig().EpochsPerHistoricalVector))
    50  }