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"
|
2020-06-25 16:12:59 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/params"
|
2019-08-21 06:08:30 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/testutil"
|
2020-08-25 15:23:06 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/testutil/assert"
|
2020-07-14 16:51:39 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/shared/testutil/require"
|
2019-08-21 06:08:30 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestPrivateKeyLoading(t *testing.T) {
|
|
|
|
file, err := ioutil.TempFile(testutil.TempDir(), "key")
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err)
|
2020-04-14 16:41:09 +00:00
|
|
|
defer func() {
|
2020-08-25 15:23:06 +00:00
|
|
|
assert.NoError(t, os.Remove(file.Name()))
|
2020-04-14 16:41:09 +00:00
|
|
|
}()
|
2019-09-11 14:58:23 +00:00
|
|
|
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err, "Could not generate key")
|
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
|
|
|
|
2020-06-25 16:12:59 +00:00
|
|
|
err = ioutil.WriteFile(file.Name(), []byte(out), params.BeaconIoConfig().ReadWritePermissions)
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err, "Could not write key to file")
|
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(),
|
|
|
|
}
|
|
|
|
pKey, err := privKey(cfg)
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err, "Could not apply option")
|
2019-09-11 14:58:23 +00:00
|
|
|
newPkey := convertToInterfacePrivkey(pKey)
|
|
|
|
rawBytes, err := key.Raw()
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err)
|
2020-04-14 16:41:09 +00:00
|
|
|
newRaw, err := newPkey.Raw()
|
2020-07-14 16:51:39 +00:00
|
|
|
require.NoError(t, err)
|
2019-09-11 14:58:23 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
}
|