github.com/prysmaticlabs/prysm@v1.4.4/spectest/shared/phase0/shuffling/core/shuffle/shuffle.go (about)

     1  // Package shuffle contains all conformity specification tests
     2  // for validator shuffling logic according to the Ethereum Beacon Node spec.
     3  package shuffle
     4  
     5  import (
     6  	"encoding/hex"
     7  	"path"
     8  	"testing"
     9  
    10  	"github.com/ethereum/go-ethereum/common"
    11  	"github.com/go-yaml/yaml"
    12  	types "github.com/prysmaticlabs/eth2-types"
    13  	"github.com/prysmaticlabs/prysm/beacon-chain/core/helpers"
    14  	"github.com/prysmaticlabs/prysm/shared/testutil"
    15  	"github.com/prysmaticlabs/prysm/shared/testutil/require"
    16  	"github.com/prysmaticlabs/prysm/spectest/utils"
    17  )
    18  
    19  // RunShuffleTests executes "shuffling/core/shuffle" tests.
    20  func RunShuffleTests(t *testing.T, config string) {
    21  	require.NoError(t, utils.SetConfig(t, config))
    22  
    23  	testFolders, testsFolderPath := utils.TestFolders(t, config, "phase0", "shuffling/core/shuffle")
    24  	for _, folder := range testFolders {
    25  		t.Run(folder.Name(), func(t *testing.T) {
    26  			testCaseFile, err := testutil.BazelFileBytes(path.Join(testsFolderPath, folder.Name(), "mapping.yaml"))
    27  			require.NoError(t, err, "Could not read YAML tests directory")
    28  
    29  			testCase := &ShuffleTestCase{}
    30  			require.NoError(t, yaml.Unmarshal(testCaseFile, testCase), "Could not unmarshal YAML file into test struct")
    31  			require.NoError(t, runShuffleTest(t, testCase), "Shuffle test failed")
    32  		})
    33  	}
    34  }
    35  
    36  // RunShuffleTest uses validator set specified from a YAML file, runs the validator shuffle
    37  // algorithm, then compare the output with the expected output from the YAML file.
    38  func runShuffleTest(t *testing.T, testCase *ShuffleTestCase) error {
    39  	baseSeed, err := hex.DecodeString(testCase.Seed[2:])
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	seed := common.BytesToHash(baseSeed)
    45  	testIndices := make([]types.ValidatorIndex, testCase.Count)
    46  	for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ {
    47  		testIndices[i] = i
    48  	}
    49  	shuffledList := make([]types.ValidatorIndex, testCase.Count)
    50  	for i := types.ValidatorIndex(0); uint64(i) < testCase.Count; i++ {
    51  		si, err := helpers.ShuffledIndex(i, testCase.Count, seed)
    52  		if err != nil {
    53  			return err
    54  		}
    55  		shuffledList[i] = si
    56  	}
    57  	require.DeepSSZEqual(t, shuffledList, testCase.Mapping)
    58  	return nil
    59  }