Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-zaremba committed Nov 3, 2020
1 parent 2324c4e commit 7df2182
Show file tree
Hide file tree
Showing 17 changed files with 158 additions and 144 deletions.
30 changes: 15 additions & 15 deletions client/keys/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,21 @@ the flag --nosort is set.
Args: cobra.ExactArgs(1),
RunE: runAddCmdPrepare,
}
flags := cmd.Flags()
flags.StringSlice(flagMultisig, nil, "Construct and store a multisig public key (implies --pubkey)")
flags.Int(flagMultiSigThreshold, 1, "K out of N required signatures. For use in conjunction with --multisig")
flags.Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied")
flags.String(FlagPublicKey, "", "Parse a public key in bech32 format and save it to disk")
flags.BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic")
flags.Bool(flags.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device")
flags.Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
flags.Bool(flagNoBackup, false, "Don't print out seed phrase (if others are watching the terminal)")
flags.Bool(flags.FlagDryRun, false, "Perform action, but don't add key to local keystore")
flags.String(flagHDPath, "", "Manual HD Path derivation (overrides BIP44 config)")
flags.Uint32(flagCoinType, sdk.GetConfig().GetCoinType(), "coin type number for HD derivation")
flags.Uint32(flagAccount, 0, "Account number for HD derivation")
flags.Uint32(flagIndex, 0, "Address index number for HD derivation")
flags.String(flags.FlagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for")
f := cmd.Flags()
f.StringSlice(flagMultisig, nil, "Construct and store a multisig public key (implies --pubkey)")
f.Int(flagMultiSigThreshold, 1, "K out of N required signatures. For use in conjunction with --multisig")
f.Bool(flagNoSort, false, "Keys passed to --multisig are taken in the order they're supplied")
f.String(FlagPublicKey, "", "Parse a public key in bech32 format and save it to disk")
f.BoolP(flagInteractive, "i", false, "Interactively prompt user for BIP39 passphrase and mnemonic")
f.Bool(flags.FlagUseLedger, false, "Store a local reference to a private key on a Ledger device")
f.Bool(flagRecover, false, "Provide seed phrase to recover existing key instead of creating")
f.Bool(flagNoBackup, false, "Don't print out seed phrase (if others are watching the terminal)")
f.Bool(flags.FlagDryRun, false, "Perform action, but don't add key to local keystore")
f.String(flagHDPath, "", "Manual HD Path derivation (overrides BIP44 config)")
f.Uint32(flagCoinType, sdk.GetConfig().GetCoinType(), "coin type number for HD derivation")
f.Uint32(flagAccount, 0, "Account number for HD derivation")
f.Uint32(flagIndex, 0, "Address index number for HD derivation")
f.String(flags.FlagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for")

cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
Expand Down
12 changes: 6 additions & 6 deletions client/keys/show.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,12 @@ consisting of all the keys provided by name and multisig threshold.`,
Args: cobra.MinimumNArgs(1),
RunE: runShowCmd,
}
flags := cmd.Flags()
flags.String(FlagBechPrefix, sdk.PrefixAccount, "The Bech32 prefix encoding for a key (acc|val|cons)")
flags.BoolP(FlagAddress, "a", false, "Output the address only (overrides --output)")
flags.BoolP(FlagPublicKey, "p", false, "Output the public key only (overrides --output)")
flags.BoolP(FlagDevice, "d", false, "Output the address in a ledger device")
flags.Int(flagMultiSigThreshold, 1, "K out of N required signatures")
f := cmd.Flags()
f.String(FlagBechPrefix, sdk.PrefixAccount, "The Bech32 prefix encoding for a key (acc|val|cons)")
f.BoolP(FlagAddress, "a", false, "Output the address only (overrides --output)")
f.BoolP(FlagPublicKey, "p", false, "Output the public key only (overrides --output)")
f.BoolP(FlagDevice, "d", false, "Output the address in a ledger device")
f.Int(flagMultiSigThreshold, 1, "K out of N required signatures")

return cmd
}
Expand Down
25 changes: 9 additions & 16 deletions client/rpc/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/gorilla/mux"
"github.com/spf13/cobra"

"github.com/tendermint/tendermint/crypto"
tmtypes "github.com/tendermint/tendermint/types"

"github.com/cosmos/cosmos-sdk/client"
Expand Down Expand Up @@ -63,10 +64,10 @@ func ValidatorCommand() *cobra.Command {
return cmd
}

// Validator output in bech32 format
// Validator output
type ValidatorOutput struct {
Address sdk.ConsAddress `json:"address"`
PubKey string `json:"pub_key"`
PubKey crypto.PubKey `json:"pub_key"`
ProposerPriority int64 `json:"proposer_priority"`
VotingPower int64 `json:"voting_power"`
}
Expand Down Expand Up @@ -98,18 +99,13 @@ func (rvo ResultValidatorsOutput) String() string {
return b.String()
}

func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error) {
bechValPubkey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, validator.PubKey)
if err != nil {
return ValidatorOutput{}, err
}

func validatorOutput(validator *tmtypes.Validator) ValidatorOutput {
return ValidatorOutput{
Address: sdk.ConsAddress(validator.Address),
PubKey: bechValPubkey,
PubKey: validator.PubKey,
ProposerPriority: validator.ProposerPriority,
VotingPower: validator.VotingPower,
}, nil
}
}

// GetValidators from client
Expand All @@ -125,19 +121,16 @@ func GetValidators(clientCtx client.Context, height *int64, page, limit *int) (R
return ResultValidatorsOutput{}, err
}

outputValidatorsRes := ResultValidatorsOutput{
out := ResultValidatorsOutput{
BlockHeight: validatorsRes.BlockHeight,
Validators: make([]ValidatorOutput, len(validatorsRes.Validators)),
}

for i := 0; i < len(validatorsRes.Validators); i++ {
outputValidatorsRes.Validators[i], err = bech32ValidatorOutput(validatorsRes.Validators[i])
if err != nil {
return ResultValidatorsOutput{}, err
}
out.Validators[i] = validatorOutput(validatorsRes.Validators[i])
}

return outputValidatorsRes, nil
return out, nil
}

// REST
Expand Down
22 changes: 18 additions & 4 deletions codec/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)

var defaultJM = &jsonpb.Marshaler{OrigName: true, EmitDefaults: true, AnyResolver: nil}

// ProtoMarshalJSON provides an auxiliary function to return Proto3 JSON encoded
// bytes of a message.
func ProtoMarshalJSON(msg proto.Message, resolver jsonpb.AnyResolver) ([]byte, error) {
// We use the OrigName because camel casing fields just doesn't make sense.
// EmitDefaults is also often the more expected behavior for CLI users
jm := &jsonpb.Marshaler{OrigName: true, EmitDefaults: true, AnyResolver: resolver}
jm := defaultJM
if resolver != nil {
jm = &jsonpb.Marshaler{OrigName: true, EmitDefaults: true, AnyResolver: resolver}
}
err := types.UnpackInterfaces(msg, types.ProtoJSONPacker{JSONPBMarshaler: jm})
if err != nil {
return nil, err
Expand All @@ -33,9 +38,18 @@ func ProtoMarshalJSON(msg proto.Message, resolver jsonpb.AnyResolver) ([]byte, e
// ProtoMarshalJSONI same as ProtoMarshalJSON, but does msg type inspection to assert
// that it implements `proto.Message` and return an error if it doesn't.
func ProtoMarshalJSONI(msg interface{}, resolver jsonpb.AnyResolver) ([]byte, error) {
msgProto, ok := msg.(proto.Message)
if !ok {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting protobuf Message type, got %T", msgProto)
msgProto, err := AssertProtoMsg(msg)
if err != nil {
return nil, err
}
return ProtoMarshalJSON(msgProto, resolver)
}

// AssertProtoMsg casts i to a proto.Message. Returns an error if it's not possible.
func AssertProtoMsg(i interface{}) (proto.Message, error) {
pm, ok := i.(proto.Message)
if !ok {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting protobuf Message type, got %T", i)
}
return pm, nil
}
11 changes: 7 additions & 4 deletions crypto/keyring/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package keyring

import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/bech32/legacybech32"
)

// TODO: Update this file and remove legacybech32 ?

// KeyOutput defines a structure wrapping around an Info object used for output
// functionality.
type KeyOutput struct {
Expand Down Expand Up @@ -52,7 +55,7 @@ func Bech32KeysOutput(infos []Info) ([]KeyOutput, error) {
func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error) {
consAddr := sdk.ConsAddress(keyInfo.GetPubKey().Address().Bytes())

bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, keyInfo.GetPubKey())
bechPubKey, err := legacybech32.Bech32ifyPubKey(legacybech32.Bech32PubKeyTypeConsPub, keyInfo.GetPubKey())
if err != nil {
return KeyOutput{}, err
}
Expand All @@ -64,7 +67,7 @@ func Bech32ConsKeyOutput(keyInfo Info) (KeyOutput, error) {
func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error) {
valAddr := sdk.ValAddress(keyInfo.GetPubKey().Address().Bytes())

bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeValPub, keyInfo.GetPubKey())
bechPubKey, err := legacybech32.Bech32ifyPubKey(legacybech32.Bech32PubKeyTypeValPub, keyInfo.GetPubKey())
if err != nil {
return KeyOutput{}, err
}
Expand All @@ -77,7 +80,7 @@ func Bech32ValKeyOutput(keyInfo Info) (KeyOutput, error) {
// public keys will be added.
func Bech32KeyOutput(keyInfo Info) (KeyOutput, error) {
accAddr := sdk.AccAddress(keyInfo.GetPubKey().Address().Bytes())
bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, keyInfo.GetPubKey())
bechPubKey, err := legacybech32.Bech32ifyPubKey(legacybech32.Bech32PubKeyTypeAccPub, keyInfo.GetPubKey())
if err != nil {
return KeyOutput{}, err
}
Expand All @@ -90,7 +93,7 @@ func Bech32KeyOutput(keyInfo Info) (KeyOutput, error) {
for i, pk := range mInfo.PubKeys {
accAddr := sdk.AccAddress(pk.PubKey.Address().Bytes())

bechPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk.PubKey)
bechPubKey, err := legacybech32.Bech32ifyPubKey(legacybech32.Bech32PubKeyTypeAccPub, pk.PubKey)
if err != nil {
return KeyOutput{}, err
}
Expand Down
7 changes: 7 additions & 0 deletions crypto/keys/ed25519/ed25519_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,10 @@ func TestMarshalAmino_BackwardsCompatibility(t *testing.T) {
})
}
}

// TODO - finish this test to show who the key will be presented in YAML
func TestMarshalYAML(t *testing.T) {
privKey := ed25519.GenPrivKey()
pubKey := privKey.PubKey()

}
8 changes: 4 additions & 4 deletions crypto/ledger/ledger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import (
"testing"

"github.com/stretchr/testify/require"

tmcrypto "github.com/tendermint/tendermint/crypto"

"github.com/cosmos/cosmos-sdk/codec"
cryptoAmino "github.com/cosmos/cosmos-sdk/crypto/codec"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/testutil"
Expand All @@ -32,10 +32,10 @@ func TestPublicKeyUnsafe(t *testing.T) {
fmt.Sprintf("%x", cdc.Amino.MustMarshalBinaryBare(priv.PubKey())),
"Is your device using test mnemonic: %s ?", testutil.TestMnemonic)

pubKeyAddr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, priv.PubKey())
out, err := codec.ProtoMarshalJSONI(pk, nil)
require.NoError(t, err)
require.Equal(t, "cosmospub1addwnpepqd87l8xhcnrrtzxnkql7k55ph8fr9jarf4hn6udwukfprlalu8lgw0urza0",
pubKeyAddr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic)
// TODO: require.Equal(t, out, ...)
fmt.Println("TODO ledger_test.go", out)

addr := sdk.AccAddress(priv.PubKey().Address()).String()
require.Equal(t, "cosmos1w34k53py5v5xyluazqpq65agyajavep2rflq6h",
Expand Down
2 changes: 1 addition & 1 deletion server/tm_cmds.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func ShowValidatorCmd() *cobra.Command {
if err != nil {
return err
}
fmt.Println(out)
fmt.Println(string(out))
return nil
},
}
Expand Down
1 change: 0 additions & 1 deletion types/address.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,6 @@ func (aa AccAddress) String() string {
}

bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix()

bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixAccAddr, aa.Bytes())
if err != nil {
panic(err)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package types_test
package legacybech32

import (
"math/rand"
"testing"
"time"

"github.com/stretchr/testify/require"

"github.com/cosmos/cosmos-sdk/crypto/keys/ed25519"
"github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
)

func BenchmarkBech32ifyPubKey(b *testing.B) {
Expand All @@ -23,7 +21,7 @@ func BenchmarkBech32ifyPubKey(b *testing.B) {
rng.Read(pk.Key)
b.StartTimer()

_, err := types.Bech32ifyPubKey(types.Bech32PubKeyTypeConsPub, pk)
_, err := Bech32ifyPubKey(Bech32PubKeyTypeConsPub, pk)
require.NoError(b, err)
}
}
Expand All @@ -39,11 +37,11 @@ func BenchmarkGetPubKeyFromBech32(b *testing.B) {
b.StopTimer()
rng.Read(pk.Key)

pkStr, err := types.Bech32ifyPubKey(types.Bech32PubKeyTypeConsPub, pk)
pkStr, err := Bech32ifyPubKey(Bech32PubKeyTypeConsPub, pk)
require.NoError(b, err)

b.StartTimer()
pk2, err := types.GetPubKeyFromBech32(types.Bech32PubKeyTypeConsPub, pkStr)
pk2, err := GetPubKeyFromBech32(Bech32PubKeyTypeConsPub, pkStr)
require.NoError(b, err)
require.Equal(b, pk, pk2)
}
Expand Down
26 changes: 26 additions & 0 deletions types/bech32/legacybech32/pk_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package legacybech32

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/ledger"
"github.com/cosmos/cosmos-sdk/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
)

func TestBeach32ifPbKey(t *testing.T) {
require := require.New(t)
path := *hd.NewFundraiserParams(0, sdk.CoinType, 0)
priv, err := ledger.NewPrivKeySecp256k1Unsafe(path)
require.Nil(err, "%s", err)
require.NotNil(priv)

pubKeyAddr, err := Bech32ifyPubKey(Bech32PubKeyTypeAccPub, priv.PubKey())
require.NoError(err)
require.Equal("cosmospub1addwnpepqd87l8xhcnrrtzxnkql7k55ph8fr9jarf4hn6udwukfprlalu8lgw0urza0",
pubKeyAddr, "Is your device using test mnemonic: %s ?", testutil.TestMnemonic)

}
8 changes: 4 additions & 4 deletions x/auth/legacy/legacytx/stdtx.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/tendermint/tendermint/crypto"
"gopkg.in/yaml.v2"

"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/legacy"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
Expand Down Expand Up @@ -92,13 +93,12 @@ func (ss StdSignature) GetPubKey() crypto.PubKey {
func (ss StdSignature) MarshalYAML() (interface{}, error) {
var (
bz []byte
pubkey string
pubkey []byte
err error
)

if ss.PubKey != nil {
pubkey, err = sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, ss.GetPubKey())
if err != nil {
if pubkey, err = codec.ProtoMarshalJSONI(ss.PubKey, nil); err != nil {
return nil, err
}
}
Expand All @@ -107,7 +107,7 @@ func (ss StdSignature) MarshalYAML() (interface{}, error) {
PubKey string
Signature string
}{
PubKey: pubkey,
PubKey: string(pubkey),
Signature: fmt.Sprintf("%X", ss.Signature),
})
if err != nil {
Expand Down
Loading

0 comments on commit 7df2182

Please sign in to comment.