[#1379] neofs-cli: Add key.GetOrGenerate helper

Signed-off-by: Evgenii Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgenii Stratonikov 2022-05-18 13:47:25 +03:00 committed by fyrchik
parent cd46a7478e
commit 094534e31a
2 changed files with 16 additions and 13 deletions

View file

@ -2,6 +2,7 @@ package key
import (
"crypto/ecdsa"
"errors"
"fmt"
"os"
@ -11,6 +12,8 @@ import (
"github.com/spf13/viper"
)
var errCantGenerateKey = errors.New("can't generate new private key")
// Get returns private key from the following sources:
// 1. WIF
// 2. Raw binary key
@ -43,6 +46,18 @@ func Get() (*ecdsa.PrivateKey, error) {
return nil, ErrInvalidKey
}
// GetOrGenerate is similar to get but generates a new key if commonflags.GenerateKey is set.
func GetOrGenerate() (*ecdsa.PrivateKey, error) {
if viper.GetBool(commonflags.GenerateKey) {
priv, err := keys.NewPrivateKey()
if err != nil {
return nil, fmt.Errorf("%w: %v", errCantGenerateKey, err)
}
return &priv.PrivateKey, nil
}
return Get()
}
func getKeyFromFile(keyPath string) (*ecdsa.PrivateKey, error) {
data, err := os.ReadFile(keyPath)
if err != nil {

View file

@ -9,7 +9,6 @@ import (
"strings"
"github.com/mitchellh/go-homedir"
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
internalclient "github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/client"
"github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/commonflags"
"github.com/nspcc-dev/neofs-node/cmd/neofs-cli/internal/key"
@ -62,10 +61,6 @@ and much more!`,
Run: entryPoint,
}
var (
errCantGenerateKey = errors.New("can't generate new private key")
)
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
@ -140,14 +135,7 @@ func initConfig() {
// getKey returns private key that was provided in global arguments.
func getKey() (*ecdsa.PrivateKey, error) {
if viper.GetBool(commonflags.GenerateKey) {
priv, err := keys.NewPrivateKey()
if err != nil {
return nil, errCantGenerateKey
}
return &priv.PrivateKey, nil
}
return getKeyNoGenerate()
return key.GetOrGenerate()
}
func getKeyNoGenerate() (*ecdsa.PrivateKey, error) {