-
Couldn't load subscription status.
- Fork 54
feat(cli): add to encrypt priv key #494
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7411da9
feat(cli): add to encrypt priv key
0xHansLee fb30476
feat(cli): add cli to encrypt the existing priv key
0xHansLee 29c1d77
chore(cli): move key related cli to key namespace
0xHansLee 5bbbd28
feat(cli): add show encrypted key cli
0xHansLee 60d1b4c
chore(cli): move prompt out from the func
0xHansLee 5b6711c
test(cli): add encrypt and decrypt test
0xHansLee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| package app_test | ||
|
|
||
| import ( | ||
| "path/filepath" | ||
| "testing" | ||
|
|
||
| k1 "github.com/cometbft/cometbft/crypto/secp256k1" | ||
| "github.com/cometbft/cometbft/privval" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
|
|
||
| "github.com/piplabs/story/client/app" | ||
| ) | ||
|
|
||
| func setupTestEnv(t *testing.T) (string, string, string) { | ||
| t.Helper() | ||
|
|
||
| stateFileDir := filepath.Join(t.TempDir(), "stateFileDir") | ||
| encFileDir := filepath.Join(t.TempDir(), "encFileDir") | ||
| password := "testpassword" | ||
|
|
||
| return stateFileDir, encFileDir, password | ||
| } | ||
|
|
||
| func TestEncryptAndDecrypt_Success(t *testing.T) { | ||
| stateFileDir, encFileDir, password := setupTestEnv(t) | ||
|
|
||
| pv := privval.NewFilePV(k1.GenPrivKey(), "", stateFileDir) | ||
|
|
||
| // Encryption | ||
| err := app.EncryptAndStoreKey(pv.Key, password, encFileDir) | ||
| require.NoError(t, err) | ||
|
|
||
| // Decryption | ||
| loadedKey, err := app.LoadEncryptedPrivKey(password, encFileDir) | ||
| require.NoError(t, err) | ||
|
|
||
| assert.Equal(t, pv.Key, loadedKey, "The decrypted key must match the original.") | ||
| } | ||
|
|
||
| func TestLoadEncryptedPrivKey_WrongPassword(t *testing.T) { | ||
| stateFileDir, encFileDir, password := setupTestEnv(t) | ||
| wrongPassword := "wrongpassword" | ||
|
|
||
| pv := privval.NewFilePV(k1.GenPrivKey(), "", stateFileDir) | ||
|
|
||
| // Encryption | ||
| err := app.EncryptAndStoreKey(pv.Key, password, encFileDir) | ||
| require.NoError(t, err) | ||
|
|
||
| // Decrypt with wrong password | ||
| _, err = app.LoadEncryptedPrivKey(wrongPassword, encFileDir) | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), "wrong password for wallet entered") | ||
| } | ||
|
|
||
| func TestLoadEncryptedPrivKey_FileNotFound(t *testing.T) { | ||
| _, encFileDir, password := setupTestEnv(t) | ||
|
|
||
| _, err := app.LoadEncryptedPrivKey(password, encFileDir) | ||
| require.Error(t, err) | ||
| assert.Contains(t, err.Error(), "failed to read enc_priv_key.json file") | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| //nolint:revive,wrapcheck // This file is taken from Prysm | ||
| package app | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "golang.org/x/crypto/ssh/terminal" | ||
|
|
||
| "github.com/logrusorgru/aurora" | ||
|
|
||
| "github.com/piplabs/story/lib/errors" | ||
| ) | ||
|
|
||
| const ( | ||
| // Constants for passwords. | ||
| minPasswordLength = 8 | ||
|
|
||
| // NewKeyPasswordPromptText for key creation. | ||
| NewKeyPasswordPromptText = "New key password" | ||
| // PasswordPromptText for wallet unlocking. | ||
| PasswordPromptText = "Key password" | ||
| // ConfirmPasswordPromptText for confirming a key password. | ||
| ConfirmPasswordPromptText = "Confirm password" | ||
| ) | ||
|
|
||
| var ( | ||
| au = aurora.NewAurora(true) | ||
|
|
||
| errPasswordWeak = errors.New("password must have at least 8 characters") | ||
| ) | ||
|
|
||
| // PasswordReaderFunc takes in a *file and returns a password using the terminal package. | ||
| func passwordReaderFunc(file *os.File) ([]byte, error) { | ||
| pass, err := terminal.ReadPassword(int(file.Fd())) | ||
|
|
||
| return pass, err | ||
| } | ||
|
|
||
| // PasswordReader has passwordReaderFunc as the default but can be changed for testing purposes. | ||
| var PasswordReader = passwordReaderFunc | ||
|
|
||
| // PasswordPrompt prompts the user for a password, that repeatedly requests the password until it qualifies the | ||
| // passed in validation function. | ||
| func PasswordPrompt(promptText string, validateFunc func(string) error) (string, error) { | ||
| var responseValid bool | ||
| var response string | ||
| for !responseValid { | ||
| fmt.Printf("%s: ", au.Bold(promptText)) | ||
| bytePassword, err := PasswordReader(os.Stdin) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| response = strings.TrimRight(string(bytePassword), "\r\n") | ||
| if err := validateFunc(response); err != nil { | ||
| fmt.Printf("\nEntry not valid: %s\n", au.BrightRed(err)) | ||
| } else { | ||
| fmt.Println("") | ||
| responseValid = true | ||
| } | ||
| } | ||
|
|
||
| return response, nil | ||
| } | ||
|
|
||
| // InputPassword with a custom validator along capabilities of confirming the password. | ||
| func InputPassword( | ||
| promptText, confirmText string, | ||
| shouldConfirmPassword bool, | ||
| passwordValidator func(input string) error, | ||
| ) (string, error) { | ||
| if strings.Contains(strings.ToLower(promptText), "new wallet") { | ||
| fmt.Println("Password requirements: at least 8 characters") | ||
| } | ||
| var hasValidPassword bool | ||
| var password string | ||
| var err error | ||
| for !hasValidPassword { | ||
| password, err = PasswordPrompt(promptText, passwordValidator) | ||
| if err != nil { | ||
| return "", errors.Wrap(err, "could not read password") | ||
| } | ||
| if shouldConfirmPassword { | ||
| passwordConfirmation, err := PasswordPrompt(confirmText, passwordValidator) | ||
| if err != nil { | ||
| return "", errors.Wrap(err, "could not read password confirmation") | ||
| } | ||
| if password != passwordConfirmation { | ||
| fmt.Println(au.BrightRed("Passwords do not match")) | ||
| continue | ||
| } | ||
| hasValidPassword = true | ||
| } else { | ||
| return password, nil | ||
| } | ||
| } | ||
|
|
||
| return password, nil | ||
| } | ||
|
|
||
| // ValidatePasswordInput validates a strong password input for new accounts, | ||
| // including a min length. | ||
| func ValidatePasswordInput(input string) error { | ||
| if len(input) < minPasswordLength { | ||
| return errPasswordWeak | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,7 +15,9 @@ import ( | |
|
|
||
| "cosmossdk.io/math" | ||
|
|
||
| cmtos "github.com/cometbft/cometbft/libs/os" | ||
| stypes "github.com/cosmos/cosmos-sdk/x/staking/types" | ||
| "github.com/ethereum/go-ethereum/crypto" | ||
| "github.com/spf13/cobra" | ||
| "github.com/spf13/pflag" | ||
|
|
||
|
|
@@ -26,9 +28,6 @@ import ( | |
| "github.com/piplabs/story/lib/k1util" | ||
| "github.com/piplabs/story/lib/netconf" | ||
| "github.com/piplabs/story/lib/tracer" | ||
|
|
||
| // Used for ABI embedding of the staking contract. | ||
| _ "embed" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not used |
||
| ) | ||
|
|
||
| func bindRunFlags(cmd *cobra.Command, cfg *config.Config) { | ||
|
|
@@ -61,9 +60,11 @@ func bindInitFlags(flags *pflag.FlagSet, cfg *InitConfig) { | |
| flags.BoolVar(&cfg.SeedMode, "seed-mode", false, "Enable seed mode") | ||
| flags.StringVar(&cfg.PersistentPeers, "persistent-peers", "", "Override the persistent peers (comma-separated)") | ||
| flags.StringVar(&cfg.Moniker, "moniker", "", "Declare a custom moniker for your node") | ||
| flags.BoolVar(&cfg.EncryptPrivKey, "encrypt-priv-key", false, "Encrypt the validator's private key") | ||
| } | ||
|
|
||
| func bindValidatorBaseFlags(cmd *cobra.Command, cfg *baseConfig) { | ||
| libcmd.BindHomeFlag(cmd.Flags(), &cfg.HomeDir) | ||
| cmd.Flags().StringVar(&cfg.RPC, "rpc", "https://mainnet.storyrpc.io", "RPC URL to connect to the network") | ||
| cmd.Flags().StringVar(&cfg.Explorer, "explorer", "https://storyscan.xyz", "URL of the blockchain explorer") | ||
| cmd.Flags().Int64Var(&cfg.ChainID, "chain-id", 1514, "Chain ID to use for the transaction") | ||
|
|
@@ -154,11 +155,16 @@ func bindValidatorKeyExportFlags(cmd *cobra.Command, cfg *exportKeyConfig) { | |
| cmd.Flags().StringVar(&cfg.EvmKeyFile, "evm-key-path", defaultEVMKeyFilePath, "Path to save the exported EVM private key") | ||
| } | ||
|
|
||
| func bindValidatorGenPrivKeyJSONFlags(cmd *cobra.Command, cfg *genPrivKeyJSONConfig) { | ||
| func bindKeyGenPrivKeyJSONFlags(cmd *cobra.Command, cfg *genPrivKeyJSONConfig) { | ||
| bindValidatorKeyFlags(cmd, &cfg.ValidatorKeyFile) | ||
| bindValidatorBaseFlags(cmd, &cfg.baseConfig) | ||
| } | ||
|
|
||
| func bindKeyShowEncryptedFlags(cmd *cobra.Command, cfg *showEncryptedConfig) { | ||
| bindValidatorBaseFlags(cmd, &cfg.baseConfig) | ||
| cmd.Flags().BoolVar(&cfg.ShowPrivate, "show-private", false, "Show private key") | ||
| } | ||
|
|
||
| func bindValidatorKeyFlags(cmd *cobra.Command, keyFilePath *string) { | ||
| defaultKeyFilePath := filepath.Join(config.DefaultHomeDir(), "config", "priv_validator_key.json") | ||
| cmd.Flags().StringVar(keyFilePath, "keyfile", defaultKeyFilePath, "Path to the Tendermint key file") | ||
|
|
@@ -492,6 +498,34 @@ func validateGenPrivKeyJSONFlags(cfg *genPrivKeyJSONConfig) error { | |
| return nil | ||
| } | ||
|
|
||
| func validateEncryptFlags(cfg *baseConfig) error { | ||
| if cmtos.FileExists(cfg.EncPrivKeyFile()) { | ||
| return errors.New("already encrypted private key exists") | ||
| } | ||
|
|
||
| loadEnv() | ||
| pk := os.Getenv("PRIVATE_KEY") | ||
| if pk == "" { | ||
| return errors.New("no private key is provided") | ||
| } | ||
|
|
||
| if _, err := crypto.HexToECDSA(pk); err != nil { | ||
| return errors.New("invalid secp256k1 private key") | ||
| } | ||
|
|
||
| cfg.PrivateKey = pk | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func validateShowEncryptedFlags(cfg *showEncryptedConfig) error { | ||
| if !cmtos.FileExists(cfg.EncPrivKeyFile()) { | ||
| return errors.New("no encrypted private key file") | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| func validateValidatorUnjailFlags(ctx context.Context, cmd *cobra.Command, cfg *unjailConfig) error { | ||
| if err := validateFlags(cmd, []string{}); err != nil { | ||
| return err | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could do more weak criteria, e.g. at least one number.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right. This validation is the same one from Prysm. We could add more.