2022-03-28 10:23:45 +00:00
|
|
|
package key
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
2022-05-18 10:47:25 +00:00
|
|
|
"errors"
|
2022-03-28 10:23:45 +00:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
2022-12-23 17:35:35 +00:00
|
|
|
"github.com/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/common"
|
|
|
|
"github.com/TrueCloudLab/frostfs-node/cmd/frostfs-cli/internal/commonflags"
|
2022-03-28 10:23:45 +00:00
|
|
|
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
|
|
|
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
2022-05-24 08:22:23 +00:00
|
|
|
"github.com/spf13/cobra"
|
2022-05-18 10:38:45 +00:00
|
|
|
"github.com/spf13/viper"
|
2022-03-28 10:23:45 +00:00
|
|
|
)
|
|
|
|
|
2022-05-18 10:47:25 +00:00
|
|
|
var errCantGenerateKey = errors.New("can't generate new private key")
|
|
|
|
|
2022-09-16 06:48:12 +00:00
|
|
|
// Get returns private key from wallet or binary file.
|
2022-03-28 10:23:45 +00:00
|
|
|
// Ideally we want to touch file-system on the last step.
|
2022-05-18 10:38:45 +00:00
|
|
|
// This function assumes that all flags were bind to viper in a `PersistentPreRun`.
|
2022-05-24 08:22:23 +00:00
|
|
|
func Get(cmd *cobra.Command) *ecdsa.PrivateKey {
|
|
|
|
pk, err := get()
|
|
|
|
common.ExitOnErr(cmd, "can't fetch private key: %w", err)
|
|
|
|
return pk
|
|
|
|
}
|
|
|
|
|
|
|
|
func get() (*ecdsa.PrivateKey, error) {
|
2022-05-18 10:38:45 +00:00
|
|
|
keyDesc := viper.GetString(commonflags.WalletPath)
|
2022-09-16 06:48:12 +00:00
|
|
|
data, err := os.ReadFile(keyDesc)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("%w: %v", ErrFs, err)
|
2022-03-28 10:23:45 +00:00
|
|
|
}
|
|
|
|
|
2022-09-16 06:48:12 +00:00
|
|
|
priv, err := keys.NewPrivateKeyFromBytes(data)
|
|
|
|
if err != nil {
|
|
|
|
w, err := wallet.NewWalletFromFile(keyDesc)
|
|
|
|
if err == nil {
|
|
|
|
return FromWallet(w, viper.GetString(commonflags.Account))
|
|
|
|
}
|
|
|
|
return nil, fmt.Errorf("%w: %v", ErrInvalidKey, err)
|
2022-03-28 10:23:45 +00:00
|
|
|
}
|
2022-09-16 06:48:12 +00:00
|
|
|
return &priv.PrivateKey, nil
|
2022-03-28 10:23:45 +00:00
|
|
|
}
|
|
|
|
|
2022-05-18 10:47:25 +00:00
|
|
|
// GetOrGenerate is similar to get but generates a new key if commonflags.GenerateKey is set.
|
2022-05-24 08:22:23 +00:00
|
|
|
func GetOrGenerate(cmd *cobra.Command) *ecdsa.PrivateKey {
|
|
|
|
pk, err := getOrGenerate()
|
|
|
|
common.ExitOnErr(cmd, "can't fetch private key: %w", err)
|
|
|
|
return pk
|
|
|
|
}
|
|
|
|
|
|
|
|
func getOrGenerate() (*ecdsa.PrivateKey, error) {
|
2022-05-18 10:47:25 +00:00
|
|
|
if viper.GetBool(commonflags.GenerateKey) {
|
|
|
|
priv, err := keys.NewPrivateKey()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("%w: %v", errCantGenerateKey, err)
|
|
|
|
}
|
|
|
|
return &priv.PrivateKey, nil
|
|
|
|
}
|
2022-05-24 08:22:23 +00:00
|
|
|
return get()
|
2022-05-18 10:47:25 +00:00
|
|
|
}
|