cosmos-sdk/client/keys/utils.go

83 lines
1.7 KiB
Go
Raw Normal View History

2018-02-22 07:17:19 -08:00
package keys
import (
"fmt"
"path/filepath"
2018-02-22 07:17:19 -08:00
"github.com/spf13/viper"
keys "github.com/tendermint/go-crypto/keys"
"github.com/tendermint/tmlibs/cli"
2018-02-28 06:36:04 -08:00
dbm "github.com/tendermint/tmlibs/db"
2018-02-22 07:17:19 -08:00
"github.com/cosmos/cosmos-sdk/client"
)
2018-02-28 06:36:04 -08:00
// KeyDBName is the directory under root where we store the keys
const KeyDBName = "keys"
2018-02-22 07:17:19 -08:00
var (
// keybase is used to make GetKeyBase a singleton
keybase keys.Keybase
)
// used for outputting keys.Info over REST
type KeyOutput struct {
Name string `json:"name"`
Address string `json:"address"`
// TODO add pubkey?
// Pubkey string `json:"pubkey"`
}
2018-02-22 07:17:19 -08:00
// GetKeyBase initializes a keybase based on the configuration
func GetKeyBase() (keys.Keybase, error) {
if keybase == nil {
rootDir := viper.GetString(cli.HomeFlag)
db, err := dbm.NewGoLevelDB(KeyDBName, filepath.Join(rootDir, "keys"))
2018-02-22 07:17:19 -08:00
if err != nil {
return nil, err
}
2018-02-28 06:36:04 -08:00
keybase = client.GetKeyBase(db)
2018-02-22 07:17:19 -08:00
}
return keybase, nil
}
2018-03-05 08:41:50 -08:00
// used to set the keybase manually in test
func SetKeyBase(kb keys.Keybase) {
keybase = kb
}
2018-02-22 07:17:19 -08:00
func printInfo(info keys.Info) {
switch viper.Get(cli.OutputFlag) {
case "text":
addr := info.PubKey.Address().String()
sep := "\t\t"
if len(info.Name) > 7 {
sep = "\t"
}
fmt.Printf("%s%s%s\n", info.Name, sep, addr)
case "json":
json, err := MarshalJSON(info)
if err != nil {
panic(err) // really shouldn't happen...
}
fmt.Println(string(json))
}
}
func printInfos(infos []keys.Info) {
switch viper.Get(cli.OutputFlag) {
case "text":
fmt.Println("All keys:")
for _, i := range infos {
printInfo(i)
}
case "json":
json, err := MarshalJSON(infos)
if err != nil {
panic(err) // really shouldn't happen...
}
fmt.Println(string(json))
}
}