Skip to content
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

feat: clean up gnokey add + add coverage #1212

Merged
merged 22 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
333 changes: 156 additions & 177 deletions tm2/pkg/crypto/keys/client/add.go

Large diffs are not rendered by default.

94 changes: 94 additions & 0 deletions tm2/pkg/crypto/keys/client/add_bech32.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package client

import (
"context"
"flag"
"fmt"

"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/crypto/keys"
)

type AddBech32Cfg struct {
RootCfg *AddCfg

PublicKey string
}

// NewAddBech32Cmd creates a gnokey add bech32 command
func NewAddBech32Cmd(rootCfg *AddCfg, io commands.IO) *commands.Command {
cfg := &AddBech32Cfg{
RootCfg: rootCfg,
}

return commands.NewCommand(
commands.Metadata{
Name: "bech32",
ShortUsage: "add bech32 [flags] <key-name>",
ShortHelp: "adds a public key to the keybase, using the bech32 representation",
},
cfg,
func(_ context.Context, args []string) error {
return execAddBech32(cfg, args, io)
},
)
}

func (c *AddBech32Cfg) RegisterFlags(fs *flag.FlagSet) {
fs.StringVar(
&c.PublicKey,
"pubkey",
"",
"parse a public key in bech32 format and save it to disk",
)
}

func execAddBech32(cfg *AddBech32Cfg, args []string, io commands.IO) error {
// Validate a key name was provided
if len(args) != 1 {
return flag.ErrHelp

Check warning on line 50 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L50

Added line #L50 was not covered by tests
}

name := args[0]

// Read the keybase from the home directory
kb, err := keys.NewKeyBaseFromDir(cfg.RootCfg.RootCfg.Home)
if err != nil {
return fmt.Errorf("unable to read keybase, %w", err)

Check warning on line 58 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L58

Added line #L58 was not covered by tests
}

// Check if the key exists
exists, err := kb.HasByName(name)
if err != nil {
return fmt.Errorf("unable to fetch key, %w", err)

Check warning on line 64 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L64

Added line #L64 was not covered by tests
}

// Get overwrite confirmation, if any
if exists {
overwrite, err := io.GetConfirmation(fmt.Sprintf("Override the existing name %s", name))
if err != nil {
return fmt.Errorf("unable to get confirmation, %w", err)

Check warning on line 71 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L71

Added line #L71 was not covered by tests
}

if !overwrite {
return errOverwriteAborted
}
}

// Parse the public key
publicKey, err := crypto.PubKeyFromBech32(cfg.PublicKey)
if err != nil {
return fmt.Errorf("unable to parse public key from bech32, %w", err)

Check warning on line 82 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L82

Added line #L82 was not covered by tests
}

// Save it offline in the keybase
_, err = kb.CreateOffline(name, publicKey)
if err != nil {
return fmt.Errorf("unable to save public key, %w", err)

Check warning on line 88 in tm2/pkg/crypto/keys/client/add_bech32.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_bech32.go#L88

Added line #L88 was not covered by tests
}

io.Printfln("Key %q saved to disk.\n", name)

return nil
}
202 changes: 202 additions & 0 deletions tm2/pkg/crypto/keys/client/add_bech32_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
package client

import (
"context"
"strings"
"testing"
"time"

"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/crypto/bip39"
"github.com/gnolang/gno/tm2/pkg/crypto/keys"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestAdd_Bech32(t *testing.T) {
t.Parallel()

t.Run("valid bech32 addition", func(t *testing.T) {
t.Parallel()

var (
kbHome = t.TempDir()
baseOptions = BaseOptions{
InsecurePasswordStdin: true,
Home: kbHome,
}

seed = bip39.NewSeed(generateTestMnemonic(t), "")
account = generateKeyFromSeed(seed, "44'/118'/0'/0/0")

keyName = "key-name"
)

ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()

io := commands.NewTestIO()
io.SetIn(strings.NewReader("test1234\ntest1234\n"))

// Create the command
cmd := NewRootCmdWithBaseConfig(io, baseOptions)

args := []string{
"add",
"bech32",
"--insecure-password-stdin",
"--home",
kbHome,
"--pubkey",
account.PubKey().String(),
keyName,
}

require.NoError(t, cmd.ParseAndRun(ctx, args))

// Check the keybase
kb, err := keys.NewKeyBaseFromDir(kbHome)
require.NoError(t, err)

original, err := kb.GetByName(keyName)
require.NoError(t, err)
require.NotNil(t, original)

assert.Equal(t, account.PubKey().Address().String(), original.GetAddress().String())
})

t.Run("valid bech32 addition, overwrite", func(t *testing.T) {
t.Parallel()

var (
kbHome = t.TempDir()
baseOptions = BaseOptions{
InsecurePasswordStdin: true,
Home: kbHome,
}

seed = bip39.NewSeed(generateTestMnemonic(t), "")
originalAccount = generateKeyFromSeed(seed, "44'/118'/0'/0/0")
copyAccount = generateKeyFromSeed(seed, "44'/118'/0'/0/1")

keyName = "key-name"
)

ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()

io := commands.NewTestIO()
io.SetIn(strings.NewReader("test1234\ntest1234\n"))

// Create the command
cmd := NewRootCmdWithBaseConfig(io, baseOptions)

baseArgs := []string{
"add",
"bech32",
"--insecure-password-stdin",
"--home",
kbHome,
keyName,
}

initialArgs := append(baseArgs, []string{
"--pubkey",
originalAccount.PubKey().String(),
}...)

require.NoError(t, cmd.ParseAndRun(ctx, initialArgs))

// Check the keybase
kb, err := keys.NewKeyBaseFromDir(kbHome)
require.NoError(t, err)

original, err := kb.GetByName(keyName)
require.NoError(t, err)

require.Equal(t, originalAccount.PubKey().Address().String(), original.GetAddress().String())

// Overwrite the key
io.SetIn(strings.NewReader("y\ntest1234\ntest1234\n"))

secondaryArgs := append(baseArgs, []string{
"--pubkey",
copyAccount.PubKey().String(),
}...)

cmd = NewRootCmdWithBaseConfig(io, baseOptions)
require.NoError(t, cmd.ParseAndRun(ctx, secondaryArgs))

newKey, err := kb.GetByName(keyName)
require.NoError(t, err)

require.Equal(t, copyAccount.PubKey().Address().String(), newKey.GetAddress().String())
})

t.Run("no overwrite permission", func(t *testing.T) {
t.Parallel()

var (
kbHome = t.TempDir()
baseOptions = BaseOptions{
InsecurePasswordStdin: true,
Home: kbHome,
}

seed = bip39.NewSeed(generateTestMnemonic(t), "")
originalAccount = generateKeyFromSeed(seed, "44'/118'/0'/0/0")
copyAccount = generateKeyFromSeed(seed, "44'/118'/0'/0/1")

keyName = "key-name"
)

ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFn()

io := commands.NewTestIO()
io.SetIn(strings.NewReader("test1234\ntest1234\n"))

// Create the command
cmd := NewRootCmdWithBaseConfig(io, baseOptions)

baseArgs := []string{
"add",
"bech32",
"--insecure-password-stdin",
"--home",
kbHome,
keyName,
}

initialArgs := append(baseArgs, []string{
"--pubkey",
originalAccount.PubKey().String(),
}...)

require.NoError(t, cmd.ParseAndRun(ctx, initialArgs))

// Check the keybase
kb, err := keys.NewKeyBaseFromDir(kbHome)
require.NoError(t, err)

original, err := kb.GetByName(keyName)
require.NoError(t, err)

io.SetIn(strings.NewReader("n\ntest1234\ntest1234\n"))

// Confirm overwrite
secondaryArgs := append(baseArgs, []string{
"--pubkey",
copyAccount.PubKey().String(),
}...)

cmd = NewRootCmdWithBaseConfig(io, baseOptions)
require.ErrorIs(t, cmd.ParseAndRun(ctx, secondaryArgs), errOverwriteAborted)

newKey, err := kb.GetByName(keyName)
require.NoError(t, err)

// Make sure the key is not overwritten
assert.Equal(t, original.GetAddress(), newKey.GetAddress())
})
}
76 changes: 76 additions & 0 deletions tm2/pkg/crypto/keys/client/add_ledger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package client

import (
"context"
"flag"
"fmt"

"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/crypto/keys"
)

// NewAddLedgerCmd creates a gnokey add ledger command
func NewAddLedgerCmd(cfg *AddCfg, io commands.IO) *commands.Command {
return commands.NewCommand(
commands.Metadata{
Name: "ledger",
ShortUsage: "add ledger [flags] <key-name>",
ShortHelp: "adds a Ledger key reference to the keybase",
},
commands.NewEmptyConfig(),
func(_ context.Context, args []string) error {
return execAddLedger(cfg, args, io)
},

Check warning on line 24 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L23-L24

Added lines #L23 - L24 were not covered by tests
)
}

func execAddLedger(cfg *AddCfg, args []string, io commands.IO) error {

Check warning on line 28 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L28

Added line #L28 was not covered by tests
// Validate a key name was provided
if len(args) != 1 {
return flag.ErrHelp

Check warning on line 31 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L30-L31

Added lines #L30 - L31 were not covered by tests
}

name := args[0]

Check warning on line 34 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L34

Added line #L34 was not covered by tests

// Read the keybase from the home directory
kb, err := keys.NewKeyBaseFromDir(cfg.RootCfg.Home)
if err != nil {
return fmt.Errorf("unable to read keybase, %w", err)

Check warning on line 39 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L37-L39

Added lines #L37 - L39 were not covered by tests
}

// Check if the key exists
exists, err := kb.HasByName(name)
if err != nil {
return fmt.Errorf("unable to fetch key, %w", err)

Check warning on line 45 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L43-L45

Added lines #L43 - L45 were not covered by tests
}

// Get overwrite confirmation, if any
if exists {
overwrite, err := io.GetConfirmation(fmt.Sprintf("Override the existing name %s", name))
if err != nil {
return fmt.Errorf("unable to get confirmation, %w", err)

Check warning on line 52 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L49-L52

Added lines #L49 - L52 were not covered by tests
}

if !overwrite {
return errOverwriteAborted

Check warning on line 56 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L55-L56

Added lines #L55 - L56 were not covered by tests
}
}

// Create the ledger reference
info, err := kb.CreateLedger(
name,
keys.Secp256k1,
crypto.Bech32AddrPrefix,
uint32(cfg.Account),
uint32(cfg.Index),
)
if err != nil {
return fmt.Errorf("unable to create Ledger reference in keybase, %w", err)

Check warning on line 69 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L61-L69

Added lines #L61 - L69 were not covered by tests
}

// Print the information
printCreate(info, false, "", io)

Check warning on line 73 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L73

Added line #L73 was not covered by tests

return nil

Check warning on line 75 in tm2/pkg/crypto/keys/client/add_ledger.go

View check run for this annotation

Codecov / codecov/patch

tm2/pkg/crypto/keys/client/add_ledger.go#L75

Added line #L75 was not covered by tests
}
Loading
Loading