cosmos-sdk/client/keys/utils.go

99 lines
2.2 KiB
Go
Raw Normal View History

2018-02-22 07:17:19 -08:00
package keys
import (
"fmt"
"io"
"path/filepath"
2018-02-22 07:17:19 -08:00
"gopkg.in/yaml.v2"
2018-12-10 06:27:25 -08:00
cryptokeyring "github.com/cosmos/cosmos-sdk/crypto/keyring"
2018-02-22 07:17:19 -08:00
)
// available output formats.
const (
OutputFormatText = "text"
OutputFormatJSON = "json"
// defaultKeyDBName is the client's subdirectory where keys are stored.
defaultKeyDBName = "keys"
)
2018-02-28 06:36:04 -08:00
type bechKeyOutFn func(keyInfo cryptokeyring.Info) (cryptokeyring.KeyOutput, error)
// NewLegacyKeyBaseFromDir initializes a legacy keybase at the rootDir directory. Keybase
// options can be applied when generating this new Keybase.
func NewLegacyKeyBaseFromDir(rootDir string, opts ...cryptokeyring.KeybaseOption) (cryptokeyring.LegacyKeybase, error) {
return getLegacyKeyBaseFromDir(rootDir, opts...)
2018-02-22 07:17:19 -08:00
}
func getLegacyKeyBaseFromDir(rootDir string, opts ...cryptokeyring.KeybaseOption) (cryptokeyring.LegacyKeybase, error) {
return cryptokeyring.NewLegacy(defaultKeyDBName, filepath.Join(rootDir, "keys"), opts...)
2018-03-05 08:41:50 -08:00
}
func printKeyInfo(w io.Writer, keyInfo cryptokeyring.Info, bechKeyOut bechKeyOutFn, output string) {
ko, err := bechKeyOut(keyInfo)
if err != nil {
panic(err)
}
switch output {
case OutputFormatText:
printTextInfos(w, []cryptokeyring.KeyOutput{ko})
case OutputFormatJSON:
out, err := KeysCdc.MarshalJSON(ko)
2018-02-22 07:17:19 -08:00
if err != nil {
2018-04-20 09:51:47 -07:00
panic(err)
2018-02-22 07:17:19 -08:00
}
fmt.Fprintln(w, string(out))
2018-02-22 07:17:19 -08:00
}
}
func printInfos(w io.Writer, infos []cryptokeyring.Info, output string) {
kos, err := cryptokeyring.Bech32KeysOutput(infos)
if err != nil {
panic(err)
}
switch output {
case OutputFormatText:
printTextInfos(w, kos)
case OutputFormatJSON:
out, err := KeysCdc.MarshalJSON(kos)
2018-02-22 07:17:19 -08:00
if err != nil {
2018-04-20 09:51:47 -07:00
panic(err)
2018-02-22 07:17:19 -08:00
}
fmt.Fprintf(w, "%s", out)
2018-02-22 07:17:19 -08:00
}
}
2018-05-28 16:27:34 -07:00
func printTextInfos(w io.Writer, kos []cryptokeyring.KeyOutput) {
out, err := yaml.Marshal(&kos)
if err != nil {
panic(err)
}
fmt.Fprintln(w, string(out))
}
func printKeyAddress(w io.Writer, info cryptokeyring.Info, bechKeyOut bechKeyOutFn) {
ko, err := bechKeyOut(info)
if err != nil {
panic(err)
}
fmt.Fprintln(w, ko.Address)
}
func printPubKey(w io.Writer, info cryptokeyring.Info, bechKeyOut bechKeyOutFn) {
ko, err := bechKeyOut(info)
if err != nil {
panic(err)
}
fmt.Fprintln(w, ko.PubKey)
}