forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey.go
80 lines (71 loc) · 1.97 KB
/
key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package testutil
import (
"fmt"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// GenerateCoinKey generates a new key mnemonic along with its address.
func GenerateCoinKey(algo keyring.SignatureAlgo, cdc codec.Codec) (sdk.AccAddress, string, error) {
// generate a private key, with mnemonic
info, secret, err := keyring.NewInMemory(cdc).NewMnemonic(
"name",
keyring.English,
sdk.GetFullBIP44Path(),
keyring.DefaultBIP39Passphrase,
algo,
)
if err != nil {
return sdk.AccAddress{}, "", err
}
addr, err := info.GetAddress()
if err != nil {
return sdk.AccAddress{}, "", err
}
return addr, secret, nil
}
// GenerateSaveCoinKey generates a new key mnemonic with its address.
// If mnemonic is provided then it's used for key generation.
// The key is saved in the keyring. The function returns error if overwrite=true and the key
// already exists.
func GenerateSaveCoinKey(
keybase keyring.Keyring,
keyName, mnemonic string,
overwrite bool,
algo keyring.SignatureAlgo,
hdPath string,
) (sdk.AccAddress, string, error) {
exists := false
_, err := keybase.Key(keyName)
if err == nil {
exists = true
}
// ensure no overwrite
if !overwrite && exists {
return sdk.AccAddress{}, "", fmt.Errorf("key already exists, overwrite is disabled")
}
if exists {
if err := keybase.Delete(keyName); err != nil {
return sdk.AccAddress{}, "", fmt.Errorf("failed to overwrite key")
}
}
var (
record *keyring.Record
secret string
)
// generate or recover a new account
if mnemonic != "" {
secret = mnemonic
record, err = keybase.NewAccount(keyName, mnemonic, keyring.DefaultBIP39Passphrase, hdPath, algo)
} else {
record, secret, err = keybase.NewMnemonic(keyName, keyring.English, hdPath, keyring.DefaultBIP39Passphrase, algo)
}
if err != nil {
return sdk.AccAddress{}, "", err
}
addr, err := record.GetAddress()
if err != nil {
return nil, "", err
}
return addr, secret, nil
}