2019-08-21 06:08:30 +00:00
|
|
|
package p2p
|
|
|
|
|
|
|
|
import (
|
2019-09-11 14:58:23 +00:00
|
|
|
"bytes"
|
2019-08-21 06:08:30 +00:00
|
|
|
"crypto/rand"
|
2019-09-12 00:04:35 +00:00
|
|
|
"encoding/hex"
|
2019-08-21 06:08:30 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
2019-09-11 14:58:23 +00:00
|
|
|
"github.com/libp2p/go-libp2p-core/crypto"
|
2019-08-21 06:08:30 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/testutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestPrivateKeyLoading(t *testing.T) {
|
|
|
|
file, err := ioutil.TempFile(testutil.TempDir(), "key")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2020-04-14 16:41:09 +00:00
|
|
|
defer func() {
|
|
|
|
if err := os.Remove(file.Name()); err != nil {
|
|
|
|
t.Log(err)
|
|
|
|
}
|
|
|
|
}()
|
2019-09-11 14:58:23 +00:00
|
|
|
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
|
2019-08-21 06:08:30 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Could not generate key: %v", err)
|
|
|
|
}
|
2019-09-12 00:04:35 +00:00
|
|
|
raw, err := key.Raw()
|
2019-09-11 14:58:23 +00:00
|
|
|
if err != nil {
|
2019-09-12 00:04:35 +00:00
|
|
|
panic(err)
|
2019-09-11 14:58:23 +00:00
|
|
|
}
|
2019-09-12 00:04:35 +00:00
|
|
|
out := hex.EncodeToString(raw)
|
2019-09-11 14:58:23 +00:00
|
|
|
|
2019-09-12 00:04:35 +00:00
|
|
|
err = ioutil.WriteFile(file.Name(), []byte(out), 0600)
|
2019-08-21 06:08:30 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Could not write key to file: %v", err)
|
|
|
|
}
|
2019-09-12 00:04:35 +00:00
|
|
|
log.WithField("file", file.Name()).WithField("key", out).Info("Wrote key to file")
|
2019-08-21 06:08:30 +00:00
|
|
|
cfg := &Config{
|
|
|
|
PrivateKey: file.Name(),
|
2019-08-24 23:56:40 +00:00
|
|
|
Encoding: "ssz",
|
2019-08-21 06:08:30 +00:00
|
|
|
}
|
|
|
|
pKey, err := privKey(cfg)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("Could not apply option: %v", err)
|
|
|
|
}
|
2019-09-11 14:58:23 +00:00
|
|
|
newPkey := convertToInterfacePrivkey(pKey)
|
|
|
|
rawBytes, err := key.Raw()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
2020-04-14 16:41:09 +00:00
|
|
|
newRaw, err := newPkey.Raw()
|
2019-09-11 14:58:23 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if !bytes.Equal(newRaw, rawBytes) {
|
|
|
|
t.Errorf("Private keys do not match got %#x but wanted %#x", rawBytes, newRaw)
|
2019-08-21 06:08:30 +00:00
|
|
|
}
|
|
|
|
}
|