cosmos-sdk/cmd/basecoin/commands/key.go

72 lines
1.5 KiB
Go
Raw Normal View History

2017-02-07 13:10:17 -08:00
package commands
import (
2017-03-14 14:28:49 -07:00
"encoding/hex"
"encoding/json"
2017-02-07 13:10:17 -08:00
"fmt"
"io/ioutil"
"path"
2017-03-14 14:28:49 -07:00
"strings"
2017-02-07 13:10:17 -08:00
"github.com/spf13/viper"
2017-02-07 13:10:17 -08:00
"github.com/tendermint/go-crypto"
"github.com/tendermint/tmlibs/cli"
2017-02-07 13:10:17 -08:00
)
//---------------------------------------------
// simple implementation of a key
2017-07-05 03:57:52 -07:00
// Address - public address for a key
2017-03-14 14:28:49 -07:00
type Address [20]byte
2017-07-05 03:57:52 -07:00
// MarshalJSON - marshal the json bytes of the address
2017-03-14 14:28:49 -07:00
func (a Address) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%x"`, a[:])), nil
}
2017-07-05 03:57:52 -07:00
// UnmarshalJSON - unmarshal the json bytes of the address
2017-03-14 14:28:49 -07:00
func (a *Address) UnmarshalJSON(addrHex []byte) error {
addr, err := hex.DecodeString(strings.Trim(string(addrHex), `"`))
if err != nil {
return err
}
copy(a[:], addr)
return nil
}
2017-07-05 03:57:52 -07:00
// Key - full private key
2017-02-07 13:10:17 -08:00
type Key struct {
Address Address `json:"address"`
PubKey crypto.PubKey `json:"pub_key"`
PrivKey crypto.PrivKey `json:"priv_key"`
2017-02-07 13:10:17 -08:00
}
2017-07-05 03:57:52 -07:00
// Sign - Implements Signer
2017-02-07 13:10:17 -08:00
func (k *Key) Sign(msg []byte) crypto.Signature {
return k.PrivKey.Sign(msg)
}
2017-07-05 03:57:52 -07:00
// LoadKey - load key from json file
2017-04-15 09:07:27 -07:00
func LoadKey(keyFile string) (*Key, error) {
2017-05-21 19:51:28 -07:00
filePath := keyFile
if !strings.HasPrefix(keyFile, "/") && !strings.HasPrefix(keyFile, ".") {
rootDir := viper.GetString(cli.HomeFlag)
filePath = path.Join(rootDir, keyFile)
}
2017-02-07 13:10:17 -08:00
keyJSONBytes, err := ioutil.ReadFile(filePath)
if err != nil {
2017-04-15 09:07:27 -07:00
return nil, err
2017-02-07 13:10:17 -08:00
}
2017-03-14 14:28:49 -07:00
key := new(Key)
err = json.Unmarshal(keyJSONBytes, key)
2017-02-07 13:10:17 -08:00
if err != nil {
2017-07-05 03:57:52 -07:00
return nil, fmt.Errorf("Error reading key from %v: %v", filePath, err) //never stack trace
2017-02-07 13:10:17 -08:00
}
2017-04-15 09:07:27 -07:00
return key, nil
2017-02-07 13:10:17 -08:00
}