github.com/prysmaticlabs/prysm@v1.4.4/shared/keystore/key_test.go (about)

     1  package keystore
     2  
     3  import (
     4  	"bytes"
     5  	"io/ioutil"
     6  	"path"
     7  	"testing"
     8  
     9  	"github.com/pborman/uuid"
    10  	"github.com/prysmaticlabs/prysm/shared/bls"
    11  	"github.com/prysmaticlabs/prysm/shared/bytesutil"
    12  	"github.com/prysmaticlabs/prysm/shared/testutil/require"
    13  )
    14  
    15  func TestMarshalAndUnmarshal(t *testing.T) {
    16  	testID := uuid.NewRandom()
    17  	blsKey, err := bls.RandKey()
    18  	require.NoError(t, err)
    19  
    20  	key := &Key{
    21  		ID:        testID,
    22  		SecretKey: blsKey,
    23  		PublicKey: blsKey.PublicKey(),
    24  	}
    25  	marshalledObject, err := key.MarshalJSON()
    26  	require.NoError(t, err)
    27  	newKey := &Key{
    28  		ID:        []byte{},
    29  		SecretKey: blsKey,
    30  		PublicKey: blsKey.PublicKey(),
    31  	}
    32  
    33  	err = newKey.UnmarshalJSON(marshalledObject)
    34  	require.NoError(t, err)
    35  	require.Equal(t, true, bytes.Equal(newKey.ID, testID))
    36  }
    37  
    38  func TestStoreRandomKey(t *testing.T) {
    39  	ks := &Keystore{
    40  		keysDirPath: path.Join(t.TempDir(), "keystore"),
    41  		scryptN:     LightScryptN,
    42  		scryptP:     LightScryptP,
    43  	}
    44  	require.NoError(t, storeNewRandomKey(ks, "password"))
    45  }
    46  
    47  func TestNewKeyFromBLS(t *testing.T) {
    48  	b := []byte("hi")
    49  	b32 := bytesutil.ToBytes32(b)
    50  	blskey, err := bls.SecretKeyFromBytes(b32[:])
    51  	require.NoError(t, err)
    52  	key, err := NewKeyFromBLS(blskey)
    53  	require.NoError(t, err)
    54  
    55  	expected := blskey.Marshal()
    56  	require.Equal(t, true, bytes.Equal(expected, key.SecretKey.Marshal()))
    57  	_, err = NewKey()
    58  	require.NoError(t, err)
    59  }
    60  
    61  func TestWriteFile(t *testing.T) {
    62  	tempDir := path.Join(t.TempDir(), "keystore", "file")
    63  	testKeystore := []byte{'t', 'e', 's', 't'}
    64  
    65  	err := writeKeyFile(tempDir, testKeystore)
    66  	require.NoError(t, err)
    67  
    68  	keystore, err := ioutil.ReadFile(tempDir)
    69  	require.NoError(t, err)
    70  	require.Equal(t, true, bytes.Equal(keystore, testKeystore))
    71  }