2018-11-07 19:07:41 +00:00
|
|
|
// Package backend contains utilities for simulating an entire
|
|
|
|
// ETH 2.0 beacon chain for e2e tests and benchmarking
|
|
|
|
// purposes.
|
|
|
|
package backend
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2018-11-19 06:54:04 +00:00
|
|
|
"reflect"
|
2019-01-06 15:25:43 +00:00
|
|
|
"time"
|
2018-11-19 06:54:04 +00:00
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
2019-01-06 15:25:43 +00:00
|
|
|
"github.com/gogo/protobuf/proto"
|
2018-11-07 19:07:41 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
|
2019-01-06 15:25:43 +00:00
|
|
|
b "github.com/prysmaticlabs/prysm/beacon-chain/core/blocks"
|
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/core/state"
|
2019-01-25 16:20:02 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/core/validators"
|
2018-11-07 19:07:41 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/db"
|
2018-11-19 06:54:04 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/beacon-chain/utils"
|
2018-11-07 19:07:41 +00:00
|
|
|
pb "github.com/prysmaticlabs/prysm/proto/beacon/p2p/v1"
|
|
|
|
"github.com/prysmaticlabs/prysm/shared/hashutil"
|
2018-11-18 16:39:35 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/params"
|
2019-01-11 10:55:01 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/slices"
|
2019-01-21 05:35:34 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/trie"
|
2019-01-06 15:25:43 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
2018-11-07 19:07:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// SimulatedBackend allowing for a programmatic advancement
|
|
|
|
// of an in-memory beacon chain for client test runs
|
|
|
|
// and other e2e use cases.
|
|
|
|
type SimulatedBackend struct {
|
|
|
|
chainService *blockchain.ChainService
|
2019-01-11 10:55:01 +00:00
|
|
|
beaconDB *db.BeaconDB
|
2018-11-07 19:07:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewSimulatedBackend creates an instance by initializing a chain service
|
|
|
|
// utilizing a mockDB which will act according to test run parameters specified
|
|
|
|
// in the common ETH 2.0 client test YAML format.
|
|
|
|
func NewSimulatedBackend() (*SimulatedBackend, error) {
|
|
|
|
db, err := setupDB()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not setup simulated backend db: %v", err)
|
|
|
|
}
|
|
|
|
cs, err := blockchain.NewChainService(context.Background(), &blockchain.Config{
|
|
|
|
BeaconDB: db,
|
|
|
|
IncomingBlockBuf: 0,
|
|
|
|
EnablePOWChain: false,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &SimulatedBackend{
|
|
|
|
chainService: cs,
|
2019-01-11 10:55:01 +00:00
|
|
|
beaconDB: db,
|
2018-11-07 19:07:41 +00:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2019-01-11 10:55:01 +00:00
|
|
|
// RunForkChoiceTest uses a parsed set of chaintests from a YAML file
|
2018-11-07 19:07:41 +00:00
|
|
|
// according to the ETH 2.0 client chain test specification and runs them
|
|
|
|
// against the simulated backend.
|
2019-01-11 10:55:01 +00:00
|
|
|
func (sb *SimulatedBackend) RunForkChoiceTest(testCase *ForkChoiceTestCase) error {
|
|
|
|
defer teardownDB(sb.beaconDB)
|
2018-11-07 19:07:41 +00:00
|
|
|
// Utilize the config parameters in the test case to setup
|
|
|
|
// the DB and set global config parameters accordingly.
|
|
|
|
// Config parameters include: ValidatorCount, ShardCount,
|
|
|
|
// CycleLength, MinCommitteeSize, and more based on the YAML
|
|
|
|
// test language specification.
|
2018-11-18 16:39:35 +00:00
|
|
|
c := params.BeaconConfig()
|
|
|
|
c.ShardCount = testCase.Config.ShardCount
|
2019-01-06 04:36:05 +00:00
|
|
|
c.EpochLength = testCase.Config.CycleLength
|
2018-11-21 01:41:20 +00:00
|
|
|
c.TargetCommitteeSize = testCase.Config.MinCommitteeSize
|
2018-11-18 16:39:35 +00:00
|
|
|
params.OverrideBeaconConfig(c)
|
2018-11-07 19:07:41 +00:00
|
|
|
|
|
|
|
// Then, we create the validators based on the custom test config.
|
|
|
|
randaoPreCommit := [32]byte{}
|
|
|
|
randaoReveal := hashutil.Hash(randaoPreCommit[:])
|
|
|
|
validators := make([]*pb.ValidatorRecord, testCase.Config.ValidatorCount)
|
|
|
|
for i := uint64(0); i < testCase.Config.ValidatorCount; i++ {
|
|
|
|
validators[i] = &pb.ValidatorRecord{
|
2019-01-05 06:39:07 +00:00
|
|
|
ExitSlot: params.BeaconConfig().EntryExitDelay,
|
2018-12-03 02:17:48 +00:00
|
|
|
Pubkey: []byte{},
|
|
|
|
RandaoCommitmentHash32: randaoReveal[:],
|
2018-11-07 19:07:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// TODO(#718): Next step is to update and save the blocks specified
|
|
|
|
// in the case case into the DB.
|
|
|
|
//
|
|
|
|
// Then, we call the updateHead routine and confirm the
|
|
|
|
// chain's head is the expected result from the test case.
|
|
|
|
return nil
|
|
|
|
}
|
2018-11-19 06:54:04 +00:00
|
|
|
|
|
|
|
// RunShuffleTest uses validator set specified from a YAML file, runs the validator shuffle
|
|
|
|
// algorithm, then compare the output with the expected output from the YAML file.
|
|
|
|
func (sb *SimulatedBackend) RunShuffleTest(testCase *ShuffleTestCase) error {
|
2019-01-11 10:55:01 +00:00
|
|
|
defer teardownDB(sb.beaconDB)
|
2018-11-19 06:54:04 +00:00
|
|
|
seed := common.BytesToHash([]byte(testCase.Seed))
|
|
|
|
output, err := utils.ShuffleIndices(seed, testCase.Input)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if !reflect.DeepEqual(output, testCase.Output) {
|
|
|
|
return fmt.Errorf("shuffle result error: expected %v, actual %v", testCase.Output, output)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2019-01-06 15:25:43 +00:00
|
|
|
|
|
|
|
// RunStateTransitionTest advances a beacon chain state transition an N amount of
|
|
|
|
// slots from a genesis state, with a block being processed at every iteration
|
|
|
|
// of the state transition function.
|
|
|
|
func (sb *SimulatedBackend) RunStateTransitionTest(testCase *StateTestCase) error {
|
2019-01-11 10:55:01 +00:00
|
|
|
defer teardownDB(sb.beaconDB)
|
2019-01-06 15:25:43 +00:00
|
|
|
// We setup the initial configuration for running state
|
|
|
|
// transition tests below.
|
|
|
|
c := params.BeaconConfig()
|
|
|
|
c.EpochLength = testCase.Config.EpochLength
|
|
|
|
c.DepositsForChainStart = testCase.Config.DepositsForChainStart
|
|
|
|
params.OverrideBeaconConfig(c)
|
|
|
|
|
2019-01-11 10:55:01 +00:00
|
|
|
// We create a list of randao hash onions for the given number of slots
|
|
|
|
// the simulation will attempt.
|
|
|
|
hashOnions := generateSimulatedRandaoHashOnions(testCase.Config.NumSlots)
|
|
|
|
|
|
|
|
// We then generate initial validator deposits for initializing the
|
|
|
|
// beacon state based where every validator will use the last layer in the randao
|
|
|
|
// onions list as the commitment in the deposit instance.
|
|
|
|
lastRandaoLayer := hashOnions[len(hashOnions)-1]
|
|
|
|
initialDeposits, err := generateInitialSimulatedDeposits(lastRandaoLayer)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not simulate initial validator deposits: %v", err)
|
2019-01-06 15:25:43 +00:00
|
|
|
}
|
|
|
|
|
2019-01-11 10:55:01 +00:00
|
|
|
genesisTime := params.BeaconConfig().GenesisTime.Unix()
|
|
|
|
beaconState, err := state.InitialBeaconState(initialDeposits, uint64(genesisTime), nil)
|
2019-01-06 15:25:43 +00:00
|
|
|
if err != nil {
|
2019-01-11 10:55:01 +00:00
|
|
|
return fmt.Errorf("could not initialize simulated beacon state")
|
2019-01-06 15:25:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// We do not expect hashing initial beacon state and genesis block to
|
|
|
|
// fail, so we can safely ignore the error below.
|
|
|
|
// #nosec G104
|
|
|
|
encodedState, _ := proto.Marshal(beaconState)
|
|
|
|
stateRoot := hashutil.Hash(encodedState)
|
|
|
|
genesisBlock := b.NewGenesisBlock(stateRoot[:])
|
|
|
|
// #nosec G104
|
|
|
|
encodedGenesisBlock, _ := proto.Marshal(genesisBlock)
|
2019-01-11 10:55:01 +00:00
|
|
|
genesisBlockRoot := hashutil.Hash(encodedGenesisBlock)
|
|
|
|
|
|
|
|
// We now keep track of generated blocks for each state transition in
|
|
|
|
// a slice.
|
|
|
|
prevBlockRoots := [][32]byte{genesisBlockRoot}
|
|
|
|
|
|
|
|
// We keep track of the randao layers peeled for each proposer index in a map.
|
|
|
|
layersPeeledForProposer := make(map[uint32]int, len(beaconState.ValidatorRegistry))
|
|
|
|
for idx := range beaconState.ValidatorRegistry {
|
|
|
|
layersPeeledForProposer[uint32(idx)] = 0
|
|
|
|
}
|
2019-01-06 15:25:43 +00:00
|
|
|
|
2019-01-12 01:10:39 +00:00
|
|
|
depositsTrie := trie.NewDepositTrie()
|
|
|
|
averageTimesPerTransition := []time.Duration{}
|
2019-01-06 15:25:43 +00:00
|
|
|
for i := uint64(0); i < testCase.Config.NumSlots; i++ {
|
2019-01-11 10:55:01 +00:00
|
|
|
prevBlockRoot := prevBlockRoots[len(prevBlockRoots)-1]
|
|
|
|
|
2019-01-25 16:20:02 +00:00
|
|
|
committeeArray, err := validators.CrosslinkCommitteesAtSlot(beaconState, i)
|
2019-01-11 10:55:01 +00:00
|
|
|
if err != nil {
|
2019-01-25 16:20:02 +00:00
|
|
|
return fmt.Errorf("could not get crosslink committee: %v", err)
|
2019-01-11 10:55:01 +00:00
|
|
|
}
|
2019-01-25 16:20:02 +00:00
|
|
|
firstCommittee := committeeArray[0].Committee
|
|
|
|
proposerIndex := firstCommittee[i%uint64(len(firstCommittee))]
|
2019-01-11 10:55:01 +00:00
|
|
|
|
|
|
|
// If the slot is marked as skipped in the configuration options,
|
|
|
|
// we simply run the state transition with a nil block argument.
|
|
|
|
if slices.IsInUint64(i, testCase.Config.SkipSlots) {
|
|
|
|
newState, err := state.ExecuteStateTransition(beaconState, nil, prevBlockRoot)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not execute state transition: %v", err)
|
|
|
|
}
|
|
|
|
beaconState = newState
|
|
|
|
layersPeeledForProposer[proposerIndex]++
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-01-12 01:10:39 +00:00
|
|
|
// If the slot is not skipped, we check if we are simulating a deposit at the current slot.
|
|
|
|
var simulatedDeposit *StateTestDeposit
|
|
|
|
for _, deposit := range testCase.Config.Deposits {
|
|
|
|
if deposit.Slot == i {
|
|
|
|
simulatedDeposit = deposit
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2019-01-12 02:11:43 +00:00
|
|
|
var simulatedProposerSlashing *StateTestProposerSlashing
|
|
|
|
for _, pSlashing := range testCase.Config.ProposerSlashings {
|
|
|
|
if pSlashing.Slot == i {
|
|
|
|
simulatedProposerSlashing = pSlashing
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2019-01-14 15:54:27 +00:00
|
|
|
var simulatedCasperSlashing *StateTestCasperSlashing
|
|
|
|
for _, cSlashing := range testCase.Config.CasperSlashings {
|
|
|
|
if cSlashing.Slot == i {
|
|
|
|
simulatedCasperSlashing = cSlashing
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2019-01-14 17:02:49 +00:00
|
|
|
var simulatedValidatorExit *StateTestValidatorExit
|
|
|
|
for _, exit := range testCase.Config.ValidatorExits {
|
|
|
|
if exit.Slot == i {
|
|
|
|
simulatedValidatorExit = exit
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2019-01-12 01:10:39 +00:00
|
|
|
|
2019-01-11 10:55:01 +00:00
|
|
|
layersPeeled := layersPeeledForProposer[proposerIndex]
|
|
|
|
blockRandaoReveal := determineSimulatedBlockRandaoReveal(layersPeeled, hashOnions)
|
|
|
|
|
|
|
|
// We generate a new block to pass into the state transition.
|
|
|
|
newBlock, newBlockRoot, err := generateSimulatedBlock(
|
|
|
|
beaconState,
|
|
|
|
prevBlockRoot,
|
|
|
|
blockRandaoReveal,
|
2019-01-12 01:10:39 +00:00
|
|
|
lastRandaoLayer,
|
|
|
|
simulatedDeposit,
|
|
|
|
depositsTrie,
|
2019-01-12 02:11:43 +00:00
|
|
|
simulatedProposerSlashing,
|
2019-01-14 15:54:27 +00:00
|
|
|
simulatedCasperSlashing,
|
2019-01-14 17:02:49 +00:00
|
|
|
simulatedValidatorExit,
|
2019-01-11 10:55:01 +00:00
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not generate simulated beacon block %v", err)
|
|
|
|
}
|
2019-01-12 01:10:39 +00:00
|
|
|
latestRoot := depositsTrie.Root()
|
|
|
|
beaconState.LatestDepositRootHash32 = latestRoot[:]
|
|
|
|
|
|
|
|
startTime := time.Now()
|
2019-01-11 10:55:01 +00:00
|
|
|
newState, err := state.ExecuteStateTransition(beaconState, newBlock, prevBlockRoot)
|
2019-01-06 15:25:43 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("could not execute state transition: %v", err)
|
|
|
|
}
|
2019-01-12 01:10:39 +00:00
|
|
|
endTime := time.Now()
|
|
|
|
averageTimesPerTransition = append(averageTimesPerTransition, endTime.Sub(startTime))
|
2019-01-11 10:55:01 +00:00
|
|
|
|
|
|
|
// We then keep track of information about the state after the
|
|
|
|
// state transition was applied.
|
2019-01-06 15:25:43 +00:00
|
|
|
beaconState = newState
|
2019-01-11 10:55:01 +00:00
|
|
|
prevBlockRoots = append(prevBlockRoots, newBlockRoot)
|
|
|
|
layersPeeledForProposer[proposerIndex]++
|
2019-01-06 15:25:43 +00:00
|
|
|
}
|
2019-01-11 10:55:01 +00:00
|
|
|
|
2019-01-06 15:25:43 +00:00
|
|
|
log.Infof(
|
2019-01-12 01:10:39 +00:00
|
|
|
"with %d initial deposits, each state transition took average time = %v",
|
2019-01-06 15:25:43 +00:00
|
|
|
testCase.Config.DepositsForChainStart,
|
2019-01-12 02:11:43 +00:00
|
|
|
averageDuration(averageTimesPerTransition),
|
2019-01-06 15:25:43 +00:00
|
|
|
)
|
|
|
|
|
2019-01-12 01:10:39 +00:00
|
|
|
if beaconState.Slot != testCase.Results.Slot {
|
2019-01-06 15:25:43 +00:00
|
|
|
return fmt.Errorf(
|
|
|
|
"incorrect state slot after %d state transitions without blocks, wanted %d, received %d",
|
|
|
|
testCase.Config.NumSlots,
|
|
|
|
testCase.Config.NumSlots,
|
|
|
|
testCase.Results.Slot,
|
|
|
|
)
|
|
|
|
}
|
2019-01-12 01:10:39 +00:00
|
|
|
if len(beaconState.ValidatorRegistry) != testCase.Results.NumValidators {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"incorrect num validators after %d state transitions without blocks, wanted %d, received %d",
|
|
|
|
testCase.Config.NumSlots,
|
|
|
|
testCase.Results.NumValidators,
|
|
|
|
len(beaconState.ValidatorRegistry),
|
|
|
|
)
|
|
|
|
}
|
2019-01-12 02:11:43 +00:00
|
|
|
for _, penalized := range testCase.Results.PenalizedValidators {
|
|
|
|
if beaconState.ValidatorRegistry[penalized].PenalizedSlot == params.BeaconConfig().FarFutureSlot {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"expected validator at index %d to have been penalized",
|
|
|
|
penalized,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2019-01-14 17:02:49 +00:00
|
|
|
for _, exited := range testCase.Results.ExitedValidators {
|
|
|
|
if beaconState.ValidatorRegistry[exited].StatusFlags != pb.ValidatorRecord_INITIATED_EXIT {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"expected validator at index %d to have exited",
|
|
|
|
exited,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2019-01-06 15:25:43 +00:00
|
|
|
return nil
|
|
|
|
}
|
2019-01-12 01:10:39 +00:00
|
|
|
|
2019-01-12 02:11:43 +00:00
|
|
|
func averageDuration(times []time.Duration) time.Duration {
|
2019-01-12 01:10:39 +00:00
|
|
|
sum := int64(0)
|
|
|
|
for _, t := range times {
|
|
|
|
sum += t.Nanoseconds()
|
|
|
|
}
|
2019-01-12 02:11:43 +00:00
|
|
|
return time.Duration(sum / int64(len(times)))
|
2019-01-12 01:10:39 +00:00
|
|
|
}
|