github.com/prysmaticlabs/prysm@v1.4.4/shared/p2putils/fork.go (about)

     1  // Package p2putils contains useful helpers for Ethereum consensus fork-related functionality.
     2  package p2putils
     3  
     4  import (
     5  	"time"
     6  
     7  	"github.com/pkg/errors"
     8  	types "github.com/prysmaticlabs/eth2-types"
     9  	"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
    10  	pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
    11  	"github.com/prysmaticlabs/prysm/shared/params"
    12  )
    13  
    14  // CreateForkDigest creates a fork digest from a genesis time and genesis
    15  // validators root, utilizing the current slot to determine
    16  // the active fork version in the node.
    17  func CreateForkDigest(
    18  	genesisTime time.Time,
    19  	genesisValidatorsRoot []byte,
    20  ) ([4]byte, error) {
    21  	if genesisTime.IsZero() {
    22  		return [4]byte{}, errors.New("genesis time is not set")
    23  	}
    24  	if len(genesisValidatorsRoot) == 0 {
    25  		return [4]byte{}, errors.New("genesis validators root is not set")
    26  	}
    27  	currentSlot := helpers.SlotsSince(genesisTime)
    28  	currentEpoch := helpers.SlotToEpoch(currentSlot)
    29  
    30  	forkData, err := Fork(currentEpoch)
    31  	if err != nil {
    32  		return [4]byte{}, err
    33  	}
    34  
    35  	digest, err := helpers.ComputeForkDigest(forkData.CurrentVersion, genesisValidatorsRoot)
    36  	if err != nil {
    37  		return [4]byte{}, err
    38  	}
    39  	return digest, nil
    40  }
    41  
    42  // Fork given a target epoch,
    43  // returns the active fork version during this epoch.
    44  func Fork(
    45  	targetEpoch types.Epoch,
    46  ) (*pb.Fork, error) {
    47  	// We retrieve a list of scheduled forks by epoch.
    48  	// We loop through the keys in this map to determine the current
    49  	// fork version based on the requested epoch.
    50  	retrievedForkVersion := params.BeaconConfig().GenesisForkVersion
    51  	previousForkVersion := params.BeaconConfig().GenesisForkVersion
    52  	scheduledForks := params.BeaconConfig().ForkVersionSchedule
    53  	forkEpoch := types.Epoch(0)
    54  	for epoch, forkVersion := range scheduledForks {
    55  		if epoch <= targetEpoch {
    56  			previousForkVersion = retrievedForkVersion
    57  			retrievedForkVersion = forkVersion
    58  			forkEpoch = epoch
    59  		}
    60  	}
    61  	return &pb.Fork{
    62  		PreviousVersion: previousForkVersion,
    63  		CurrentVersion:  retrievedForkVersion,
    64  		Epoch:           forkEpoch,
    65  	}, nil
    66  }