From 7df2182274df6f950ad9ade6ffcdee6f8a918aed Mon Sep 17 00:00:00 2001 From: Robert Zaremba Date: Tue, 3 Nov 2020 23:52:31 +0100 Subject: [PATCH] wip --- client/keys/add.go | 30 +++---- client/keys/show.go | 12 +-- client/rpc/validators.go | 25 ++---- codec/json.go | 22 ++++- crypto/keyring/output.go | 11 ++- crypto/keys/ed25519/ed25519_test.go | 7 ++ crypto/ledger/ledger_test.go | 8 +- server/tm_cmds.go | 2 +- types/address.go | 1 - .../legacybech32/pk_bench_test.go} | 12 ++- types/bech32/legacybech32/pk_test.go | 26 ++++++ x/auth/legacy/legacytx/stdtx.go | 8 +- x/auth/vesting/types/vesting_account.go | 83 ++++++++----------- x/slashing/client/rest/query.go | 7 +- x/slashing/keeper/keeper.go | 37 +++------ x/slashing/simulation/decoder_test.go | 8 +- x/staking/legacy/v036/types.go | 3 +- 17 files changed, 158 insertions(+), 144 deletions(-) rename types/{address_bench_test.go => bech32/legacybech32/pk_bench_test.go} (74%) create mode 100644 types/bech32/legacybech32/pk_test.go diff --git a/client/keys/add.go b/client/keys/add.go index 734ad24f8042..685ae23b8d1e 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -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()) diff --git a/client/keys/show.go b/client/keys/show.go index 88611bfe9c32..4c705cf8a20f 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -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 } diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 591d3354c56c..0a8fdd1fc56c 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -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" @@ -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"` } @@ -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 @@ -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 diff --git a/codec/json.go b/codec/json.go index b0207cc9736a..0c8dda4b2596 100644 --- a/codec/json.go +++ b/codec/json.go @@ -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 @@ -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 +} diff --git a/crypto/keyring/output.go b/crypto/keyring/output.go index 5f76789caadf..fd3f9b8e8700 100644 --- a/crypto/keyring/output.go +++ b/crypto/keyring/output.go @@ -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 { @@ -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 } @@ -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 } @@ -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 } @@ -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 } diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 6b2ad36dc4f3..a95ae517f1f5 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -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() + +} diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index 9b21e464bcdb..5d463f635351 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -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" @@ -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", diff --git a/server/tm_cmds.go b/server/tm_cmds.go index 43eff54a51a7..7846f7a939d3 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -55,7 +55,7 @@ func ShowValidatorCmd() *cobra.Command { if err != nil { return err } - fmt.Println(out) + fmt.Println(string(out)) return nil }, } diff --git a/types/address.go b/types/address.go index 0f92e8667b3f..e7df4839830a 100644 --- a/types/address.go +++ b/types/address.go @@ -233,7 +233,6 @@ func (aa AccAddress) String() string { } bech32PrefixAccAddr := GetConfig().GetBech32AccountAddrPrefix() - bech32Addr, err := bech32.ConvertAndEncode(bech32PrefixAccAddr, aa.Bytes()) if err != nil { panic(err) diff --git a/types/address_bench_test.go b/types/bech32/legacybech32/pk_bench_test.go similarity index 74% rename from types/address_bench_test.go rename to types/bech32/legacybech32/pk_bench_test.go index 59222dacf9b7..47a6b52bec02 100644 --- a/types/address_bench_test.go +++ b/types/bech32/legacybech32/pk_bench_test.go @@ -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) { @@ -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) } } @@ -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) } diff --git a/types/bech32/legacybech32/pk_test.go b/types/bech32/legacybech32/pk_test.go new file mode 100644 index 000000000000..0f2a63ad9f8e --- /dev/null +++ b/types/bech32/legacybech32/pk_test.go @@ -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) + +} diff --git a/x/auth/legacy/legacytx/stdtx.go b/x/auth/legacy/legacytx/stdtx.go index 270a8d727a21..20ce926e80d8 100644 --- a/x/auth/legacy/legacytx/stdtx.go +++ b/x/auth/legacy/legacytx/stdtx.go @@ -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" @@ -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 } } @@ -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 { diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index e011bd6efbbf..4eaa8030c5c4 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -6,9 +6,11 @@ import ( yaml "gopkg.in/yaml.v2" + "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" vestexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" + "github.com/tendermint/tendermint/crypto" ) // Compile-time type assertions @@ -188,7 +190,7 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) { return nil, err } - alias := vestingAccountYAML{ + out := vestingAccountYAML{ Address: accAddr, AccountNumber: bva.AccountNumber, Sequence: bva.Sequence, @@ -197,23 +199,10 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) { DelegatedVesting: bva.DelegatedVesting, EndTime: bva.EndTime, } - - pk := bva.GetPubKey() - if pk != nil { - pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk) - if err != nil { - return nil, err - } - - alias.PubKey = pks - } - - bz, err := yaml.Marshal(alias) - if err != nil { + if out.PubKey, err = getPKString(bva); err != nil { return nil, err } - - return string(bz), err + return marshalYaml(out) } //----------------------------------------------------------------------------- @@ -316,7 +305,7 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) { return nil, err } - alias := vestingAccountYAML{ + out := vestingAccountYAML{ Address: accAddr, AccountNumber: cva.AccountNumber, Sequence: cva.Sequence, @@ -326,23 +315,10 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) { EndTime: cva.EndTime, StartTime: cva.StartTime, } - - pk := cva.GetPubKey() - if pk != nil { - pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk) - if err != nil { - return nil, err - } - - alias.PubKey = pks - } - - bz, err := yaml.Marshal(alias) - if err != nil { + if out.PubKey, err = getPKString(cva); err != nil { return nil, err } - - return string(bz), err + return marshalYaml(out) } //----------------------------------------------------------------------------- @@ -474,7 +450,7 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) { return nil, err } - alias := vestingAccountYAML{ + out := vestingAccountYAML{ Address: accAddr, AccountNumber: pva.AccountNumber, Sequence: pva.Sequence, @@ -485,23 +461,10 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) { StartTime: pva.StartTime, VestingPeriods: pva.VestingPeriods, } - - pk := pva.GetPubKey() - if pk != nil { - pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk) - if err != nil { - return nil, err - } - - alias.PubKey = pks - } - - bz, err := yaml.Marshal(alias) - if err != nil { + if out.PubKey, err = getPKString(pva); err != nil { return nil, err } - - return string(bz), err + return marshalYaml(out) } //----------------------------------------------------------------------------- @@ -570,3 +533,27 @@ func (dva DelayedVestingAccount) String() string { out, _ := dva.MarshalYAML() return out.(string) } + +type getPK interface { + GetPubKey() crypto.PubKey +} + +func getPKString(g getPK) (string, err) { + if pk := g.GetPubKey(); pk != nil { + // TODO check if it's ok to change a type of ValidatorOutput.PubKey to crypto.PubKey + pk, err := codec.ProtoMarshalJSONI(pk, nil) + if err != nil { + return nil, err + } + return string(pk), err + } + return "", nil +} + +func marshalYaml(i interface{}) (interface{}, error) { + bz, err := yaml.Marshal(i) + if err != nil { + return nil, err + } + return string(bz), nil +} diff --git a/x/slashing/client/rest/query.go b/x/slashing/client/rest/query.go index 0e1c68da145d..fd9be86a0596 100644 --- a/x/slashing/client/rest/query.go +++ b/x/slashing/client/rest/query.go @@ -7,7 +7,7 @@ import ( "github.com/gorilla/mux" "github.com/cosmos/cosmos-sdk/client" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" "github.com/cosmos/cosmos-sdk/types/rest" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -29,12 +29,11 @@ func registerQueryRoutes(clientCtx client.Context, r *mux.Router) { ).Methods("GET") } -// http request handler to query signing info -// [DEPRECATED] +// Deprecated: http request handler to query signing info func signingInfoHandlerFn(clientCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, vars["validatorPubKey"]) + pk, err := legacybech32.GetPubKeyFromBech32(legacybech32.Bech32PubKeyTypeConsPub, vars["validatorPubKey"]) if rest.CheckBadRequestError(w, err) { return } diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index ee46915b745b..099889763c0d 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -3,8 +3,6 @@ package keeper import ( "fmt" - gogotypes "github.com/gogo/protobuf/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" @@ -42,33 +40,27 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { } // AddPubkey sets a address-pubkey relation -func (k Keeper) AddPubkey(ctx sdk.Context, pubkey crypto.PubKey) { +func (k Keeper) AddPubkey(ctx sdk.Context, pubkey crypto.PubKey) error { addr := pubkey.Address() - - pkStr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubkey) + pkProto, err := codec.AssertProtoMsg(pubkey) if err != nil { - panic(fmt.Errorf("error while setting address-pubkey relation: %s", addr)) + return err } - - k.setAddrPubkeyRelation(ctx, addr, pkStr) + store := ctx.KVStore(k.storeKey) + bz := k.cdc.MustMarshalBinaryBare(pkProto) + store.Set(types.AddrPubkeyRelationKey(addr), bz) + return nil } // GetPubkey returns the pubkey from the adddress-pubkey relation func (k Keeper) GetPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKey, error) { store := ctx.KVStore(k.storeKey) - - var pubkey gogotypes.StringValue - err := k.cdc.UnmarshalBinaryBare(store.Get(types.AddrPubkeyRelationKey(address)), &pubkey) - if err != nil { + var pubkey crypto.PubKey + bz := store.Get(types.AddrPubkeyRelationKey(address)) + if bz == nil { return nil, fmt.Errorf("address %s not found", sdk.ConsAddress(address)) } - - pkStr, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, pubkey.Value) - if err != nil { - return pkStr, err - } - - return pkStr, nil + return pubkey, k.cdc.UnmarshalBinaryBare(bz, &pubkey) } // Slash attempts to slash a validator. The slash is delegated to the staking @@ -99,13 +91,6 @@ func (k Keeper) Jail(ctx sdk.Context, consAddr sdk.ConsAddress) { k.sk.Jail(ctx, consAddr) } -func (k Keeper) setAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address, pubkey string) { - store := ctx.KVStore(k.storeKey) - - bz := k.cdc.MustMarshalBinaryBare(&gogotypes.StringValue{Value: pubkey}) - store.Set(types.AddrPubkeyRelationKey(addr), bz) -} - func (k Keeper) deleteAddrPubkeyRelation(ctx sdk.Context, addr crypto.Address) { store := ctx.KVStore(k.storeKey) store.Delete(types.AddrPubkeyRelationKey(addr)) diff --git a/x/slashing/simulation/decoder_test.go b/x/slashing/simulation/decoder_test.go index e6122f0e0a98..d55bd7a28181 100644 --- a/x/slashing/simulation/decoder_test.go +++ b/x/slashing/simulation/decoder_test.go @@ -8,6 +8,7 @@ import ( gogotypes "github.com/gogo/protobuf/types" "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" @@ -29,15 +30,16 @@ func TestDecodeStore(t *testing.T) { dec := simulation.NewDecodeStore(cdc) info := types.NewValidatorSigningInfo(consAddr1, 0, 1, time.Now().UTC(), false, 0) - bechPK := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, delPk1) missed := gogotypes.BoolValue{Value: true} + delPk1Proto, err := codec.AssertProtoMsg(delPk1) + require.NoError(t, err) kvPairs := kv.Pairs{ Pairs: []kv.Pair{ {Key: types.ValidatorSigningInfoKey(consAddr1), Value: cdc.MustMarshalBinaryBare(&info)}, {Key: types.ValidatorMissedBlockBitArrayKey(consAddr1, 6), Value: cdc.MustMarshalBinaryBare(&missed)}, - {Key: types.AddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryBare(&gogotypes.StringValue{Value: bechPK})}, - {Key: []byte{0x99}, Value: []byte{0x99}}, + {Key: types.AddrPubkeyRelationKey(delAddr1), Value: cdc.MustMarshalBinaryBare(delPk1)}, + {Key: []byte{0x99}, Value: []byte{0x99}}, // This test should panic }, } diff --git a/x/staking/legacy/v036/types.go b/x/staking/legacy/v036/types.go index 6c110bbe57dc..258fd7057934 100644 --- a/x/staking/legacy/v036/types.go +++ b/x/staking/legacy/v036/types.go @@ -9,6 +9,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/legacy" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/bech32/legacybech32" v034staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v034" ) @@ -89,7 +90,7 @@ func NewGenesisState( } func (v Validator) MarshalJSON() ([]byte, error) { - bechConsPubKey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, v.ConsPubKey) + bechConsPubKey, err := legacybech32.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, v.ConsPubKey) if err != nil { return nil, err }