From 90e9370bd80d9a3d41f7203ddb71166865561569 Mon Sep 17 00:00:00 2001 From: Marie Gauthier Date: Mon, 9 Nov 2020 17:01:43 +0100 Subject: [PATCH] Replace tmcrypto.PubKey by our own cryptotypes.PubKey (#7419) * WIP on removing tm pub/privkey * Fix part of crypto tests * Add PrivKeyLedgerSecp256K1 proto type * Use BasePrivKey for ledger priv key type * Refacto continued * First round * x/staking * Continue porting * x/* done * Make build pass * More conversion * Remove IntoTmPubKey * Fix test * Remove crypto.PubKey in some other places * Revert ledger changes * Fix comment * Remove useless function * Add To/FromTmPublicKey * Add migrate tests * Fix test * Fix another test * Rename tm conversion functions * Less code * Rename BasePrivKey to LedgerPrivKey * Add changelog * Rename functions Co-authored-by: Amaury Martiny Co-authored-by: Alessio Treglia --- CHANGELOG.md | 4 + client/account_retriever.go | 5 +- client/debug/main.go | 4 +- client/keys/add.go | 6 +- client/keys/show.go | 4 +- client/keys/show_test.go | 5 +- client/rpc/validators.go | 7 +- client/test_helpers.go | 5 +- client/tx/tx.go | 4 +- crypto/armor.go | 9 +- crypto/armor_test.go | 3 +- crypto/codec/amino.go | 18 +-- crypto/codec/proto.go | 10 -- crypto/codec/tm.go | 57 +++++++ crypto/hd/algo.go | 8 +- crypto/keyring/info.go | 49 +++--- crypto/keyring/keyring.go | 33 +++-- crypto/keyring/keyring_test.go | 10 +- crypto/keyring/legacy.go | 6 +- crypto/keyring/output_test.go | 4 +- crypto/keyring/types.go | 5 +- crypto/keys/ed25519/ed25519.go | 28 +--- crypto/keys/ed25519/ed25519_test.go | 10 +- crypto/keys/internal/benchmarking/bench.go | 8 +- crypto/keys/multisig/codec.go | 5 - crypto/keys/multisig/multisig.go | 26 ++-- crypto/keys/multisig/multisig_test.go | 31 ++-- crypto/keys/secp256k1/bench_test.go | 5 +- crypto/keys/secp256k1/secp256k1.go | 6 +- crypto/keys/secp256k1/secp256k1_test.go | 10 +- crypto/ledger/encode_test.go | 6 +- crypto/ledger/ledger_secp256k1.go | 18 +-- crypto/ledger/ledger_test.go | 11 +- crypto/types/multisig/multisignature.go | 8 +- crypto/types/multisig/pubkey.go | 9 +- crypto/types/types.go | 37 +++-- server/tm_cmds.go | 10 +- simapp/helpers/test_helpers.go | 5 +- simapp/simd/cmd/testnet.go | 6 +- simapp/test_helpers.go | 20 ++- tests/mocks/account_retriever.go | 6 +- testutil/network/network.go | 6 +- testutil/testdata/tx.go | 5 +- types/address.go | 57 ++----- types/address_test.go | 4 +- types/rest/rest_test.go | 14 +- types/simulation/account.go | 9 +- types/tx/signing/signature.go | 7 +- types/tx/types.go | 5 +- types/tx_msg.go | 5 +- x/auth/ante/ante_test.go | 104 ++++++------- x/auth/ante/basic.go | 5 +- x/auth/ante/basic_test.go | 18 +-- x/auth/ante/fee_test.go | 7 +- x/auth/ante/setup_test.go | 8 +- x/auth/ante/sigverify.go | 5 +- x/auth/ante/sigverify_test.go | 47 +++--- x/auth/ante/testutil_test.go | 8 +- x/auth/client/cli/cli_test.go | 6 +- x/auth/keeper/keeper.go | 6 +- x/auth/legacy/legacytx/stdsign.go | 9 +- x/auth/legacy/legacytx/stdtx.go | 12 +- x/auth/legacy/legacytx/stdtx_test.go | 12 +- x/auth/legacy/v038/types.go | 27 ++-- x/auth/legacy/v039/migrate_test.go | 104 +++++++++++++ x/auth/legacy/v039/types.go | 37 ++--- x/auth/signing/sig_verifiable_tx.go | 5 +- x/auth/signing/verify.go | 5 +- x/auth/signing/verify_test.go | 4 +- x/auth/testutil/suite.go | 8 +- x/auth/tx/builder.go | 21 +-- x/auth/tx/sigs.go | 10 +- x/auth/types/account.go | 17 ++- x/auth/vesting/types/test_common.go | 5 +- x/bank/app_test.go | 18 +-- x/bank/simulation/operations.go | 11 +- x/distribution/types/common_test.go | 5 +- x/evidence/keeper/keeper_test.go | 6 +- x/evidence/types/expected_keepers.go | 5 +- x/genutil/legacy/v038/migrate.go | 3 - x/genutil/legacy/v039/migrate.go | 3 - x/genutil/types/types.go | 7 +- x/genutil/utils.go | 8 +- x/gov/common_test.go | 4 +- x/gov/keeper/tally_test.go | 4 +- x/ibc/core/02-client/keeper/client_test.go | 3 +- x/ibc/core/02-client/keeper/keeper_test.go | 8 +- x/ibc/core/02-client/types/genesis_test.go | 3 +- .../06-solomachine/types/consensus_state.go | 11 +- .../06-solomachine/types/header.go | 11 +- .../06-solomachine/types/proof.go | 5 +- .../06-solomachine/types/solomachine.go | 9 +- .../types/misbehaviour_handle_test.go | 3 +- .../07-tendermint/types/misbehaviour_test.go | 3 +- .../07-tendermint/types/tendermint_test.go | 3 +- .../07-tendermint/types/update_test.go | 3 +- x/ibc/testing/chain.go | 8 +- x/ibc/testing/chain_test.go | 5 +- x/ibc/testing/mock/privval.go | 6 +- x/ibc/testing/solomachine.go | 16 +- x/slashing/genesis.go | 2 +- x/slashing/keeper/hooks.go | 3 +- x/slashing/keeper/infractions.go | 5 +- x/slashing/keeper/keeper.go | 10 +- x/slashing/simulation/operations.go | 3 +- x/staking/client/cli/tx.go | 4 +- x/staking/genesis.go | 16 +- x/staking/handler_test.go | 14 +- x/staking/keeper/msg_server.go | 2 +- x/staking/keeper/validator_test.go | 4 +- x/staking/legacy/v034/types.go | 26 ++-- x/staking/legacy/v036/migrate_test.go | 103 +++++++++++++ x/staking/legacy/v036/types.go | 5 +- x/staking/legacy/v038/types.go | 5 +- x/staking/teststaking/helper.go | 10 +- x/staking/teststaking/tm.go | 43 ++++++ x/staking/teststaking/validator.go | 4 +- x/staking/types/commission_test.go | 23 +-- x/staking/types/data_test.go | 7 +- x/staking/types/delegation_test.go | 39 ++--- x/staking/types/exported.go | 7 +- x/staking/types/historical_info_test.go | 31 ++-- x/staking/types/keys.go | 16 +- x/staking/types/keys_test.go | 23 +-- x/staking/types/msg.go | 7 +- x/staking/types/msg_test.go | 34 ++--- x/staking/types/params_test.go | 7 +- x/staking/types/validator.go | 93 +++++------- x/staking/types/validator_test.go | 139 +++++++++--------- 129 files changed, 1079 insertions(+), 900 deletions(-) create mode 100644 crypto/codec/tm.go create mode 100644 x/auth/legacy/v039/migrate_test.go create mode 100644 x/staking/legacy/v036/migrate_test.go create mode 100644 x/staking/teststaking/tm.go diff --git a/CHANGELOG.md b/CHANGELOG.md index c10fd1385b1e..bbe06901e1ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## [v0.40.0-rc3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0-rc3) - 2020-11-06 +### Client Breaking + +* (x/staking) [\#7419](https://github.com/cosmos/cosmos-sdk/pull/7419) The `TmConsPubKey` method on ValidatorI has been removed and replaced instead by `ConsPubKey` (which returns a SDK `cryptotypes.PubKey`) and `TmConsPublicKey` (which returns a Tendermint proto PublicKey). + ### Improvements * (tendermint) [\#7828](https://github.com/cosmos/cosmos-sdk/pull/7828) Update tendermint dependency to v0.34.0-rc6 diff --git a/client/account_retriever.go b/client/account_retriever.go index 51c0a7fa9bcc..8e2fd14c1fcd 100644 --- a/client/account_retriever.go +++ b/client/account_retriever.go @@ -1,15 +1,14 @@ package client import ( - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) // Account defines a read-only version of the auth module's AccountI. type Account interface { GetAddress() sdk.AccAddress - GetPubKey() crypto.PubKey // can return nil. + GetPubKey() cryptotypes.PubKey // can return nil. GetAccountNumber() uint64 GetSequence() uint64 } diff --git a/client/debug/main.go b/client/debug/main.go index ab9ec0cf8a32..54b75e712b64 100644 --- a/client/debug/main.go +++ b/client/debug/main.go @@ -8,10 +8,10 @@ import ( "strings" "github.com/spf13/cobra" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/version" @@ -34,7 +34,7 @@ func Cmd() *cobra.Command { // getPubKeyFromString returns a Tendermint PubKey (PubKeyEd25519) by attempting // to decode the pubkey string from hex, base64, and finally bech32. If all // encodings fail, an error is returned. -func getPubKeyFromString(pkstr string) (crypto.PubKey, error) { +func getPubKeyFromString(pkstr string) (cryptotypes.PubKey, error) { bz, err := hex.DecodeString(pkstr) if err == nil { if len(bz) == ed25519.PubKeySize { diff --git a/client/keys/add.go b/client/keys/add.go index b2e267e83e8a..c91f639c4a6e 100644 --- a/client/keys/add.go +++ b/client/keys/add.go @@ -9,7 +9,6 @@ import ( bip39 "github.com/cosmos/go-bip39" "github.com/spf13/cobra" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" @@ -18,6 +17,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -152,7 +152,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf multisigKeys, _ := cmd.Flags().GetStringSlice(flagMultisig) if len(multisigKeys) != 0 { - var pks []crypto.PubKey + var pks []cryptotypes.PubKey multisigThreshold, _ := cmd.Flags().GetInt(flagMultiSigThreshold) if err := validateMultisigThreshold(multisigThreshold, len(multisigKeys)); err != nil { @@ -247,7 +247,7 @@ func RunAddCmd(cmd *cobra.Command, args []string, kb keyring.Keyring, inBuf *buf } if len(mnemonic) == 0 { - // read entropy seed straight from crypto.Rand and convert to mnemonic + // read entropy seed straight from tmcrypto.Rand and convert to mnemonic entropySeed, err := bip39.NewEntropy(mnemonicEntropySize) if err != nil { return err diff --git a/client/keys/show.go b/client/keys/show.go index 102f29793b4a..2cb3c457f2ec 100644 --- a/client/keys/show.go +++ b/client/keys/show.go @@ -5,13 +5,13 @@ import ( "fmt" "github.com/spf13/cobra" - tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/ledger" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -61,7 +61,7 @@ func runShowCmd(cmd *cobra.Command, args []string) (err error) { return fmt.Errorf("%s is not a valid name or address: %v", args[0], err) } } else { - pks := make([]tmcrypto.PubKey, len(args)) + pks := make([]cryptotypes.PubKey, len(args)) for i, keyref := range args { info, err := fetchKey(clientCtx.Keyring, keyref) if err != nil { diff --git a/client/keys/show_test.go b/client/keys/show_test.go index e68107b58ba1..882a80683a18 100644 --- a/client/keys/show_test.go +++ b/client/keys/show_test.go @@ -7,14 +7,13 @@ import ( "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,7 +22,7 @@ func Test_multiSigKey_Properties(t *testing.T) { tmpKey1 := secp256k1.GenPrivKeyFromSecret([]byte("mySecret")) pk := multisig.NewLegacyAminoPubKey( 1, - []crypto.PubKey{tmpKey1.PubKey()}, + []cryptotypes.PubKey{tmpKey1.PubKey()}, ) tmp := keyring.NewMultiInfo("myMultisig", pk) diff --git a/client/rpc/validators.go b/client/rpc/validators.go index 591d3354c56c..0a15f4bc93db 100644 --- a/client/rpc/validators.go +++ b/client/rpc/validators.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" ) @@ -99,7 +100,11 @@ func (rvo ResultValidatorsOutput) String() string { } func bech32ValidatorOutput(validator *tmtypes.Validator) (ValidatorOutput, error) { - bechValPubkey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, validator.PubKey) + pk, err := cryptocodec.FromTmPubKeyInterface(validator.PubKey) + if err != nil { + return ValidatorOutput{}, err + } + bechValPubkey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pk) if err != nil { return ValidatorOutput{}, err } diff --git a/client/test_helpers.go b/client/test_helpers.go index 1140298fda42..214184b50f17 100644 --- a/client/test_helpers.go +++ b/client/test_helpers.go @@ -3,8 +3,7 @@ package client import ( "fmt" - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -26,7 +25,7 @@ func (t TestAccount) GetAddress() sdk.AccAddress { } // GetPubKey implements client Account.GetPubKey -func (t TestAccount) GetPubKey() crypto.PubKey { +func (t TestAccount) GetPubKey() cryptotypes.PubKey { return nil } diff --git a/client/tx/tx.go b/client/tx/tx.go index fb0e71280501..d1814c36359f 100644 --- a/client/tx/tx.go +++ b/client/tx/tx.go @@ -8,13 +8,13 @@ import ( "os" "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/input" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/rest" @@ -343,7 +343,7 @@ func PrepareFactory(clientCtx client.Context, txf Factory) (Factory, error) { // corresponding SignatureV2 if the signing is successful. func SignWithPrivKey( signMode signing.SignMode, signerData authsigning.SignerData, - txBuilder client.TxBuilder, priv crypto.PrivKey, txConfig client.TxConfig, + txBuilder client.TxBuilder, priv cryptotypes.PrivKey, txConfig client.TxConfig, accSeq uint64, ) (signing.SignatureV2, error) { var sigV2 signing.SignatureV2 diff --git a/crypto/armor.go b/crypto/armor.go index d0637c709d13..3ee472707a71 100644 --- a/crypto/armor.go +++ b/crypto/armor.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec/legacy" cryptoAmino "github.com/cosmos/cosmos-sdk/crypto/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -124,7 +125,7 @@ func unarmorBytes(armorStr, blockType string) (bz []byte, header map[string]stri // encrypt/decrypt with armor // Encrypt and armor the private key. -func EncryptArmorPrivKey(privKey crypto.PrivKey, passphrase string, algo string) string { +func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase string, algo string) string { saltBytes, encBytes := encryptPrivKey(privKey, passphrase) header := map[string]string{ "kdf": "bcrypt", @@ -143,7 +144,7 @@ func EncryptArmorPrivKey(privKey crypto.PrivKey, passphrase string, algo string) // encrypt the given privKey with the passphrase using a randomly // generated salt and the xsalsa20 cipher. returns the salt and the // encrypted priv key. -func encryptPrivKey(privKey crypto.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { +func encryptPrivKey(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { saltBytes = crypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) @@ -158,7 +159,7 @@ func encryptPrivKey(privKey crypto.PrivKey, passphrase string) (saltBytes []byte } // UnarmorDecryptPrivKey returns the privkey byte slice, a string of the algo type, and an error -func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey crypto.PrivKey, algo string, err error) { +func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey cryptotypes.PrivKey, algo string, err error) { blockType, header, encBytes, err := armor.DecodeArmor(armorStr) if err != nil { return privKey, "", err @@ -190,7 +191,7 @@ func UnarmorDecryptPrivKey(armorStr string, passphrase string) (privKey crypto.P return privKey, header[headerType], err } -func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey crypto.PrivKey, err error) { +func decryptPrivKey(saltBytes []byte, encBytes []byte, passphrase string) (privKey cryptotypes.PrivKey, err error) { key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), BcryptSecurityParameter) if err != nil { return privKey, sdkerrors.Wrap(err, "error generating bcrypt key from passphrase") diff --git a/crypto/armor_test.go b/crypto/armor_test.go index 3e5f256faa75..3267ca98a78c 100644 --- a/crypto/armor_test.go +++ b/crypto/armor_test.go @@ -19,6 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types" ) @@ -46,7 +47,7 @@ func TestArmorUnarmorPrivKey(t *testing.T) { require.Contains(t, err.Error(), "unrecognized armor type") // armor key manually - encryptPrivKeyFn := func(privKey tmcrypto.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { + encryptPrivKeyFn := func(privKey cryptotypes.PrivKey, passphrase string) (saltBytes []byte, encBytes []byte) { saltBytes = tmcrypto.CRandBytes(16) key, err := bcrypt.GenerateFromPassword(saltBytes, []byte(passphrase), crypto.BcryptSecurityParameter) require.NoError(t, err) diff --git a/crypto/codec/amino.go b/crypto/codec/amino.go index 5a98acbac364..5cd61c3dd31f 100644 --- a/crypto/codec/amino.go +++ b/crypto/codec/amino.go @@ -1,8 +1,6 @@ package codec import ( - "github.com/tendermint/tendermint/crypto" - tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/sr25519" "github.com/cosmos/cosmos-sdk/codec" @@ -22,16 +20,9 @@ func init() { // RegisterCrypto registers all crypto dependency types with the provided Amino // codec. func RegisterCrypto(cdc *codec.LegacyAmino) { - // TODO We now register both Tendermint's PubKey and our own PubKey. In the - // long-term, we should move away from Tendermint's PubKey, and delete this - // first line. - cdc.RegisterInterface((*crypto.PubKey)(nil), nil) cdc.RegisterInterface((*cryptotypes.PubKey)(nil), nil) cdc.RegisterConcrete(sr25519.PubKey{}, sr25519.PubKeyName, nil) - // TODO Same as above, for ED25519 - cdc.RegisterConcrete(tmed25519.PubKey{}, - tmed25519.PubKeyName, nil) cdc.RegisterConcrete(&ed25519.PubKey{}, ed25519.PubKeyName, nil) cdc.RegisterConcrete(&secp256k1.PubKey{}, @@ -39,12 +30,9 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&kmultisig.LegacyAminoPubKey{}, kmultisig.PubKeyAminoRoute, nil) - cdc.RegisterInterface((*crypto.PrivKey)(nil), nil) + cdc.RegisterInterface((*cryptotypes.PrivKey)(nil), nil) cdc.RegisterConcrete(sr25519.PrivKey{}, sr25519.PrivKeyName, nil) - // TODO Same as above - cdc.RegisterConcrete(tmed25519.PrivKey{}, - tmed25519.PrivKeyName, nil) cdc.RegisterConcrete(&ed25519.PrivKey{}, ed25519.PrivKeyName, nil) cdc.RegisterConcrete(&secp256k1.PrivKey{}, @@ -52,13 +40,13 @@ func RegisterCrypto(cdc *codec.LegacyAmino) { } // PrivKeyFromBytes unmarshals private key bytes and returns a PrivKey -func PrivKeyFromBytes(privKeyBytes []byte) (privKey crypto.PrivKey, err error) { +func PrivKeyFromBytes(privKeyBytes []byte) (privKey cryptotypes.PrivKey, err error) { err = amino.UnmarshalBinaryBare(privKeyBytes, &privKey) return } // PubKeyFromBytes unmarshals public key bytes and returns a PubKey -func PubKeyFromBytes(pubKeyBytes []byte) (pubKey crypto.PubKey, err error) { +func PubKeyFromBytes(pubKeyBytes []byte) (pubKey cryptotypes.PubKey, err error) { err = amino.UnmarshalBinaryBare(pubKeyBytes, &pubKey) return } diff --git a/crypto/codec/proto.go b/crypto/codec/proto.go index 845e60bf82e4..9c07ca110596 100644 --- a/crypto/codec/proto.go +++ b/crypto/codec/proto.go @@ -1,8 +1,6 @@ package codec import ( - tmcrypto "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" @@ -12,14 +10,6 @@ import ( // RegisterInterfaces registers the sdk.Tx interface. func RegisterInterfaces(registry codectypes.InterfaceRegistry) { - // TODO We now register both Tendermint's PubKey and our own PubKey. In the - // long-term, we should move away from Tendermint's PubKey, and delete - // these lines. - registry.RegisterInterface("tendermint.crypto.PubKey", (*tmcrypto.PubKey)(nil)) - registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &ed25519.PubKey{}) - registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &secp256k1.PubKey{}) - registry.RegisterImplementations((*tmcrypto.PubKey)(nil), &multisig.LegacyAminoPubKey{}) - registry.RegisterInterface("cosmos.crypto.PubKey", (*cryptotypes.PubKey)(nil)) registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &ed25519.PubKey{}) registry.RegisterImplementations((*cryptotypes.PubKey)(nil), &secp256k1.PubKey{}) diff --git a/crypto/codec/tm.go b/crypto/codec/tm.go new file mode 100644 index 000000000000..6633f60c2377 --- /dev/null +++ b/crypto/codec/tm.go @@ -0,0 +1,57 @@ +package codec + +import ( + tmcrypto "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/encoding" + tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +// FromTmProtoPublicKey converts a TM's tmprotocrypto.PublicKey into our own PubKey. +func FromTmProtoPublicKey(protoPk tmprotocrypto.PublicKey) (cryptotypes.PubKey, error) { + switch protoPk := protoPk.Sum.(type) { + case *tmprotocrypto.PublicKey_Ed25519: + return &ed25519.PubKey{ + Key: protoPk.Ed25519, + }, nil + default: + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v from Tendermint public key", protoPk) + } +} + +// ToTmProtoPublicKey converts our own PubKey to TM's tmprotocrypto.PublicKey. +func ToTmProtoPublicKey(pk cryptotypes.PubKey) (tmprotocrypto.PublicKey, error) { + switch pk := pk.(type) { + case *ed25519.PubKey: + return tmprotocrypto.PublicKey{ + Sum: &tmprotocrypto.PublicKey_Ed25519{ + Ed25519: pk.Key, + }, + }, nil + default: + return tmprotocrypto.PublicKey{}, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "cannot convert %v to Tendermint public key", pk) + } +} + +// FromTmPubKeyInterface converts TM's tmcrypto.PubKey to our own PubKey. +func FromTmPubKeyInterface(tmPk tmcrypto.PubKey) (cryptotypes.PubKey, error) { + tmProtoPk, err := encoding.PubKeyToProto(tmPk) + if err != nil { + return nil, err + } + + return FromTmProtoPublicKey(tmProtoPk) +} + +// ToTmPubKeyInterface converts our own PubKey to TM's tmcrypto.PubKey. +func ToTmPubKeyInterface(pk cryptotypes.PubKey) (tmcrypto.PubKey, error) { + tmProtoPk, err := ToTmProtoPublicKey(pk) + if err != nil { + return nil, err + } + + return encoding.PubKeyFromProto(tmProtoPk) +} diff --git a/crypto/hd/algo.go b/crypto/hd/algo.go index 30636c56df06..f934ad08aece 100644 --- a/crypto/hd/algo.go +++ b/crypto/hd/algo.go @@ -2,9 +2,9 @@ package hd import ( bip39 "github.com/cosmos/go-bip39" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/types" ) // PubKeyType defines an algorithm to derive key-pairs which can be used for cryptographic signing. @@ -28,11 +28,11 @@ var ( ) type DeriveFn func(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) -type GenerateFn func(bz []byte) crypto.PrivKey +type GenerateFn func(bz []byte) types.PrivKey type WalletGenerator interface { Derive(mnemonic string, bip39Passphrase, hdPath string) ([]byte, error) - Generate(bz []byte) crypto.PrivKey + Generate(bz []byte) types.PrivKey } type secp256k1Algo struct { @@ -62,7 +62,7 @@ func (s secp256k1Algo) Derive() DeriveFn { // Generate generates a secp256k1 private key from the given bytes. func (s secp256k1Algo) Generate() GenerateFn { - return func(bz []byte) crypto.PrivKey { + return func(bz []byte) types.PrivKey { var bzArr = make([]byte, secp256k1.PrivKeySize) copy(bzArr, bz) diff --git a/crypto/keyring/info.go b/crypto/keyring/info.go index 366e474d227e..f05e2f0ddef6 100644 --- a/crypto/keyring/info.go +++ b/crypto/keyring/info.go @@ -3,11 +3,10 @@ package keyring import ( "fmt" - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types" ) @@ -18,7 +17,7 @@ type Info interface { // Name of the key GetName() string // Public key - GetPubKey() crypto.PubKey + GetPubKey() cryptotypes.PubKey // Address GetAddress() types.AccAddress // Bip44 Path @@ -37,13 +36,13 @@ var ( // localInfo is the public information about a locally stored key // Note: Algo must be last field in struct for backwards amino compatibility type localInfo struct { - Name string `json:"name"` - PubKey crypto.PubKey `json:"pubkey"` - PrivKeyArmor string `json:"privkey.armor"` - Algo hd.PubKeyType `json:"algo"` + Name string `json:"name"` + PubKey cryptotypes.PubKey `json:"pubkey"` + PrivKeyArmor string `json:"privkey.armor"` + Algo hd.PubKeyType `json:"algo"` } -func newLocalInfo(name string, pub crypto.PubKey, privArmor string, algo hd.PubKeyType) Info { +func newLocalInfo(name string, pub cryptotypes.PubKey, privArmor string, algo hd.PubKeyType) Info { return &localInfo{ Name: name, PubKey: pub, @@ -63,7 +62,7 @@ func (i localInfo) GetName() string { } // GetType implements Info interface -func (i localInfo) GetPubKey() crypto.PubKey { +func (i localInfo) GetPubKey() cryptotypes.PubKey { return i.PubKey } @@ -85,13 +84,13 @@ func (i localInfo) GetPath() (*hd.BIP44Params, error) { // ledgerInfo is the public information about a Ledger key // Note: Algo must be last field in struct for backwards amino compatibility type ledgerInfo struct { - Name string `json:"name"` - PubKey crypto.PubKey `json:"pubkey"` - Path hd.BIP44Params `json:"path"` - Algo hd.PubKeyType `json:"algo"` + Name string `json:"name"` + PubKey cryptotypes.PubKey `json:"pubkey"` + Path hd.BIP44Params `json:"path"` + Algo hd.PubKeyType `json:"algo"` } -func newLedgerInfo(name string, pub crypto.PubKey, path hd.BIP44Params, algo hd.PubKeyType) Info { +func newLedgerInfo(name string, pub cryptotypes.PubKey, path hd.BIP44Params, algo hd.PubKeyType) Info { return &ledgerInfo{ Name: name, PubKey: pub, @@ -111,7 +110,7 @@ func (i ledgerInfo) GetName() string { } // GetPubKey implements Info interface -func (i ledgerInfo) GetPubKey() crypto.PubKey { +func (i ledgerInfo) GetPubKey() cryptotypes.PubKey { return i.PubKey } @@ -134,12 +133,12 @@ func (i ledgerInfo) GetPath() (*hd.BIP44Params, error) { // offlineInfo is the public information about an offline key // Note: Algo must be last field in struct for backwards amino compatibility type offlineInfo struct { - Name string `json:"name"` - PubKey crypto.PubKey `json:"pubkey"` - Algo hd.PubKeyType `json:"algo"` + Name string `json:"name"` + PubKey cryptotypes.PubKey `json:"pubkey"` + Algo hd.PubKeyType `json:"algo"` } -func newOfflineInfo(name string, pub crypto.PubKey, algo hd.PubKeyType) Info { +func newOfflineInfo(name string, pub cryptotypes.PubKey, algo hd.PubKeyType) Info { return &offlineInfo{ Name: name, PubKey: pub, @@ -158,7 +157,7 @@ func (i offlineInfo) GetName() string { } // GetPubKey implements Info interface -func (i offlineInfo) GetPubKey() crypto.PubKey { +func (i offlineInfo) GetPubKey() cryptotypes.PubKey { return i.PubKey } @@ -178,20 +177,20 @@ func (i offlineInfo) GetPath() (*hd.BIP44Params, error) { } type multisigPubKeyInfo struct { - PubKey crypto.PubKey `json:"pubkey"` - Weight uint `json:"weight"` + PubKey cryptotypes.PubKey `json:"pubkey"` + Weight uint `json:"weight"` } // multiInfo is the public information about a multisig key type multiInfo struct { Name string `json:"name"` - PubKey crypto.PubKey `json:"pubkey"` + PubKey cryptotypes.PubKey `json:"pubkey"` Threshold uint `json:"threshold"` PubKeys []multisigPubKeyInfo `json:"pubkeys"` } // NewMultiInfo creates a new multiInfo instance -func NewMultiInfo(name string, pub crypto.PubKey) Info { +func NewMultiInfo(name string, pub cryptotypes.PubKey) Info { multiPK := pub.(*multisig.LegacyAminoPubKey) pubKeys := make([]multisigPubKeyInfo, len(multiPK.PubKeys)) @@ -219,7 +218,7 @@ func (i multiInfo) GetName() string { } // GetPubKey implements Info interface -func (i multiInfo) GetPubKey() crypto.PubKey { +func (i multiInfo) GetPubKey() cryptotypes.PubKey { return i.PubKey } diff --git a/crypto/keyring/keyring.go b/crypto/keyring/keyring.go index 0d0e41b7c3da..d3220b5b43ef 100644 --- a/crypto/keyring/keyring.go +++ b/crypto/keyring/keyring.go @@ -22,6 +22,7 @@ import ( cryptoamino "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/ledger" + "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -76,10 +77,10 @@ type Keyring interface { SaveLedgerKey(uid string, algo SignatureAlgo, hrp string, coinType, account, index uint32) (Info, error) // SavePubKey stores a public key and returns the persisted Info structure. - SavePubKey(uid string, pubkey tmcrypto.PubKey, algo hd.PubKeyType) (Info, error) + SavePubKey(uid string, pubkey types.PubKey, algo hd.PubKeyType) (Info, error) // SaveMultisig stores and returns a new multsig (offline) key reference. - SaveMultisig(uid string, pubkey tmcrypto.PubKey) (Info, error) + SaveMultisig(uid string, pubkey types.PubKey) (Info, error) Signer @@ -90,10 +91,10 @@ type Keyring interface { // Signer is implemented by key stores that want to provide signing capabilities. type Signer interface { // Sign sign byte messages with a user key. - Sign(uid string, msg []byte) ([]byte, tmcrypto.PubKey, error) + Sign(uid string, msg []byte) ([]byte, types.PubKey, error) // SignByAddress sign byte messages with a user key providing the address. - SignByAddress(address sdk.Address, msg []byte) ([]byte, tmcrypto.PubKey, error) + SignByAddress(address sdk.Address, msg []byte) ([]byte, types.PubKey, error) } // Importer is implemented by key stores that support import of public and private keys. @@ -224,13 +225,13 @@ func (ks keystore) ExportPrivKeyArmor(uid, encryptPassphrase string) (armor stri } // ExportPrivateKeyObject exports an armored private key object. -func (ks keystore) ExportPrivateKeyObject(uid string) (tmcrypto.PrivKey, error) { +func (ks keystore) ExportPrivateKeyObject(uid string) (types.PrivKey, error) { info, err := ks.Key(uid) if err != nil { return nil, err } - var priv tmcrypto.PrivKey + var priv types.PrivKey switch linfo := info.(type) { case localInfo: @@ -301,13 +302,13 @@ func (ks keystore) ImportPubKey(uid string, armor string) error { return nil } -func (ks keystore) Sign(uid string, msg []byte) ([]byte, tmcrypto.PubKey, error) { +func (ks keystore) Sign(uid string, msg []byte) ([]byte, types.PubKey, error) { info, err := ks.Key(uid) if err != nil { return nil, nil, err } - var priv tmcrypto.PrivKey + var priv types.PrivKey switch i := info.(type) { case localInfo: @@ -335,7 +336,7 @@ func (ks keystore) Sign(uid string, msg []byte) ([]byte, tmcrypto.PubKey, error) return sig, priv.PubKey(), nil } -func (ks keystore) SignByAddress(address sdk.Address, msg []byte) ([]byte, tmcrypto.PubKey, error) { +func (ks keystore) SignByAddress(address sdk.Address, msg []byte) ([]byte, types.PubKey, error) { key, err := ks.KeyByAddress(address) if err != nil { return nil, nil, err @@ -359,7 +360,7 @@ func (ks keystore) SaveLedgerKey(uid string, algo SignatureAlgo, hrp string, coi return ks.writeLedgerKey(uid, priv.PubKey(), *hdPath, algo.Name()) } -func (ks keystore) writeLedgerKey(name string, pub tmcrypto.PubKey, path hd.BIP44Params, algo hd.PubKeyType) (Info, error) { +func (ks keystore) writeLedgerKey(name string, pub types.PubKey, path hd.BIP44Params, algo hd.PubKeyType) (Info, error) { info := newLedgerInfo(name, pub, path, algo) if err := ks.writeInfo(info); err != nil { return nil, err @@ -368,11 +369,11 @@ func (ks keystore) writeLedgerKey(name string, pub tmcrypto.PubKey, path hd.BIP4 return info, nil } -func (ks keystore) SaveMultisig(uid string, pubkey tmcrypto.PubKey) (Info, error) { +func (ks keystore) SaveMultisig(uid string, pubkey types.PubKey) (Info, error) { return ks.writeMultisigKey(uid, pubkey) } -func (ks keystore) SavePubKey(uid string, pubkey tmcrypto.PubKey, algo hd.PubKeyType) (Info, error) { +func (ks keystore) SavePubKey(uid string, pubkey types.PubKey, algo hd.PubKeyType) (Info, error) { return ks.writeOfflineKey(uid, pubkey, algo) } @@ -533,7 +534,7 @@ func (ks keystore) SupportedAlgorithms() (SigningAlgoList, SigningAlgoList) { // SignWithLedger signs a binary message with the ledger device referenced by an Info object // and returns the signed bytes and the public key. It returns an error if the device could // not be queried or it returned an error. -func SignWithLedger(info Info, msg []byte) (sig []byte, pub tmcrypto.PubKey, err error) { +func SignWithLedger(info Info, msg []byte) (sig []byte, pub types.PubKey, err error) { switch info.(type) { case *ledgerInfo, ledgerInfo: default: @@ -691,7 +692,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) { } } -func (ks keystore) writeLocalKey(name string, priv tmcrypto.PrivKey, algo hd.PubKeyType) (Info, error) { +func (ks keystore) writeLocalKey(name string, priv types.PrivKey, algo hd.PubKeyType) (Info, error) { // encrypt private key using keyring pub := priv.PubKey() @@ -753,7 +754,7 @@ func (ks keystore) existsInDb(info Info) (bool, error) { return false, nil } -func (ks keystore) writeOfflineKey(name string, pub tmcrypto.PubKey, algo hd.PubKeyType) (Info, error) { +func (ks keystore) writeOfflineKey(name string, pub types.PubKey, algo hd.PubKeyType) (Info, error) { info := newOfflineInfo(name, pub, algo) err := ks.writeInfo(info) if err != nil { @@ -763,7 +764,7 @@ func (ks keystore) writeOfflineKey(name string, pub tmcrypto.PubKey, algo hd.Pub return info, nil } -func (ks keystore) writeMultisigKey(name string, pub tmcrypto.PubKey) (Info, error) { +func (ks keystore) writeMultisigKey(name string, pub types.PubKey) (Info, error) { info := NewMultiInfo(name, pub) err := ks.writeInfo(info) if err != nil { diff --git a/crypto/keyring/keyring_test.go b/crypto/keyring/keyring_test.go index 0cd75c9b44dc..540ea57bf3fe 100644 --- a/crypto/keyring/keyring_test.go +++ b/crypto/keyring/keyring_test.go @@ -8,13 +8,13 @@ import ( "github.com/99designs/keyring" bip39 "github.com/cosmos/go-bip39" "github.com/stretchr/testify/require" - tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -166,7 +166,7 @@ func TestSignVerifyKeyRing(t *testing.T) { // let's try to validate and make sure it only works when everything is proper cases := []struct { - key tmcrypto.PubKey + key types.PubKey data []byte sig []byte valid bool @@ -380,7 +380,7 @@ func TestInMemoryCreateMultisig(t *testing.T) { kb, err := New("keybasename", "memory", "", nil) require.NoError(t, err) multi := multisig.NewLegacyAminoPubKey( - 1, []tmcrypto.PubKey{ + 1, []types.PubKey{ secp256k1.GenPrivKey().PubKey(), }, ) @@ -521,7 +521,7 @@ func TestInMemorySignVerify(t *testing.T) { // let's try to validate and make sure it only works when everything is proper cases := []struct { - key tmcrypto.PubKey + key types.PubKey data []byte sig []byte valid bool @@ -947,7 +947,7 @@ func TestAltKeyring_SaveMultisig(t *testing.T) { key := "multi" pub := multisig.NewLegacyAminoPubKey( 2, - []tmcrypto.PubKey{ + []types.PubKey{ &secp256k1.PubKey{Key: mnemonic1.GetPubKey().Bytes()}, &secp256k1.PubKey{Key: mnemonic2.GetPubKey().Bytes()}, }, diff --git a/crypto/keyring/legacy.go b/crypto/keyring/legacy.go index 2332266d4563..59bdc3fc5dad 100644 --- a/crypto/keyring/legacy.go +++ b/crypto/keyring/legacy.go @@ -6,11 +6,11 @@ import ( "strings" "github.com/pkg/errors" - tmcrypto "github.com/tendermint/tendermint/crypto" tmos "github.com/tendermint/tendermint/libs/os" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/crypto" + "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -101,13 +101,13 @@ func (kb dbKeybase) Get(name string) (Info, error) { // ExportPrivateKeyObject returns a PrivKey object given the key name and // passphrase. An error is returned if the key does not exist or if the Info for // the key is invalid. -func (kb dbKeybase) ExportPrivateKeyObject(name string, passphrase string) (tmcrypto.PrivKey, error) { +func (kb dbKeybase) ExportPrivateKeyObject(name string, passphrase string) (types.PrivKey, error) { info, err := kb.Get(name) if err != nil { return nil, err } - var priv tmcrypto.PrivKey + var priv types.PrivKey switch i := info.(type) { case localInfo: diff --git a/crypto/keyring/output_test.go b/crypto/keyring/output_test.go index dc98ad62bc8a..c43b36bf7ce0 100644 --- a/crypto/keyring/output_test.go +++ b/crypto/keyring/output_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -16,7 +16,7 @@ func TestBech32KeysOutput(t *testing.T) { bechTmpKey := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, tmpKey) tmpAddr := sdk.AccAddress(tmpKey.Address().Bytes()) - multisigPks := kmultisig.NewLegacyAminoPubKey(1, []crypto.PubKey{tmpKey}) + multisigPks := kmultisig.NewLegacyAminoPubKey(1, []types.PubKey{tmpKey}) multiInfo := NewMultiInfo("multisig", multisigPks) accAddr := sdk.AccAddress(multiInfo.GetPubKey().Address().Bytes()) bechPubKey := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, multiInfo.GetPubKey()) diff --git a/crypto/keyring/types.go b/crypto/keyring/types.go index 443896d785b2..0b893ea4cccc 100644 --- a/crypto/keyring/types.go +++ b/crypto/keyring/types.go @@ -1,9 +1,8 @@ package keyring import ( - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/hd" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) // Language is a language to create the BIP 39 mnemonic in. @@ -68,5 +67,5 @@ type ( // DeriveKeyFunc defines the function to derive a new key from a seed and hd path DeriveKeyFunc func(mnemonic string, bip39Passphrase, hdPath string, algo hd.PubKeyType) ([]byte, error) // PrivKeyGenFunc defines the function to convert derived key bytes to a tendermint private key - PrivKeyGenFunc func(bz []byte, algo hd.PubKeyType) (crypto.PrivKey, error) + PrivKeyGenFunc func(bz []byte, algo hd.PubKeyType) (cryptotypes.PrivKey, error) ) diff --git a/crypto/keys/ed25519/ed25519.go b/crypto/keys/ed25519/ed25519.go index 4c935a076064..17368c4b12ff 100644 --- a/crypto/keys/ed25519/ed25519.go +++ b/crypto/keys/ed25519/ed25519.go @@ -7,7 +7,6 @@ import ( "io" "github.com/tendermint/tendermint/crypto" - tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" "github.com/tendermint/tendermint/crypto/tmhash" "github.com/cosmos/cosmos-sdk/codec" @@ -18,8 +17,8 @@ import ( //------------------------------------- const ( - PrivKeyName = "cosmos/PrivKeyEd25519" - PubKeyName = "cosmos/PubKeyEd25519" + PrivKeyName = "tendermint/PrivKeyEd25519" + PubKeyName = "tendermint/PubKeyEd25519" // PubKeySize is is the size, in bytes, of public keys as used in this package. PubKeySize = 32 // PrivKeySize is the size, in bytes, of private keys as used in this package. @@ -56,7 +55,7 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) { // PubKey gets the corresponding public key from the private key. // // Panics if the private key is not initialized. -func (privKey *PrivKey) PubKey() crypto.PubKey { +func (privKey *PrivKey) PubKey() cryptotypes.PubKey { // If the latter 32 bytes of the privkey are all zero, privkey is not // initialized. initialized := false @@ -78,7 +77,7 @@ func (privKey *PrivKey) PubKey() crypto.PubKey { // Equals - you probably don't need to use this. // Runs in constant time based on length of the keys. -func (privKey *PrivKey) Equals(other crypto.PrivKey) bool { +func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool { if privKey.Type() != other.Type() { return false } @@ -150,7 +149,6 @@ func GenPrivKeyFromSecret(secret []byte) *PrivKey { var _ cryptotypes.PubKey = &PubKey{} var _ codec.AminoMarshaler = &PubKey{} -var _ cryptotypes.IntoTmPubKey = &PubKey{} // Address is the SHA256-20 of the raw pubkey bytes. func (pubKey *PubKey) Address() crypto.Address { @@ -182,7 +180,7 @@ func (pubKey *PubKey) Type() string { return keyType } -func (pubKey *PubKey) Equals(other crypto.PubKey) bool { +func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { if pubKey.Type() != other.Type() { return false } @@ -216,19 +214,3 @@ func (pubKey PubKey) MarshalAminoJSON() ([]byte, error) { func (pubKey *PubKey) UnmarshalAminoJSON(bz []byte) error { return pubKey.UnmarshalAmino(bz) } - -// AsTmPubKey converts our own PubKey into a Tendermint ED25519 pubkey. -func (pubKey *PubKey) AsTmPubKey() crypto.PubKey { - return tmed25519.PubKey(pubKey.Key) -} - -// FromTmEd25519 converts a Tendermint ED25519 pubkey into our own ED25519 -// PubKey. -func FromTmEd25519(pubKey crypto.PubKey) (*PubKey, error) { - tmPk, ok := pubKey.(tmed25519.PubKey) - if !ok { - return nil, fmt.Errorf("expected %T, got %T", tmed25519.PubKey{}, pubKey) - } - - return &PubKey{Key: []byte(tmPk)}, nil -} diff --git a/crypto/keys/ed25519/ed25519_test.go b/crypto/keys/ed25519/ed25519_test.go index 6b2ad36dc4f3..59cce4066ac2 100644 --- a/crypto/keys/ed25519/ed25519_test.go +++ b/crypto/keys/ed25519/ed25519_test.go @@ -9,10 +9,10 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/sr25519" "github.com/cosmos/cosmos-sdk/codec" ed25519 "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) @@ -51,7 +51,7 @@ func TestPubKeyEquals(t *testing.T) { testCases := []struct { msg string pubKey cryptotypes.PubKey - other crypto.PubKey + other cryptotypes.PubKey expectEq bool }{ { @@ -71,7 +71,7 @@ func TestPubKeyEquals(t *testing.T) { { "different types", ed25519PubKey, - sr25519.GenPrivKey().PubKey(), + secp256k1.GenPrivKey().PubKey(), false, }, } @@ -90,7 +90,7 @@ func TestPrivKeyEquals(t *testing.T) { testCases := []struct { msg string privKey cryptotypes.PrivKey - other crypto.PrivKey + other cryptotypes.PrivKey expectEq bool }{ { @@ -110,7 +110,7 @@ func TestPrivKeyEquals(t *testing.T) { { "different types", ed25519PrivKey, - sr25519.GenPrivKey(), + secp256k1.GenPrivKey(), false, }, } diff --git a/crypto/keys/internal/benchmarking/bench.go b/crypto/keys/internal/benchmarking/bench.go index b74b901db937..a789da91f9c9 100644 --- a/crypto/keys/internal/benchmarking/bench.go +++ b/crypto/keys/internal/benchmarking/bench.go @@ -4,7 +4,7 @@ import ( "io" "testing" - "github.com/tendermint/tendermint/crypto" + "github.com/cosmos/cosmos-sdk/crypto/types" ) // The code in this file is adapted from agl/ed25519. @@ -24,7 +24,7 @@ func (zeroReader) Read(buf []byte) (int, error) { // BenchmarkKeyGeneration benchmarks the given key generation algorithm using // a dummy reader. -func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) crypto.PrivKey) { +func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) types.PrivKey) { var zero zeroReader for i := 0; i < b.N; i++ { generateKey(zero) @@ -33,7 +33,7 @@ func BenchmarkKeyGeneration(b *testing.B, generateKey func(reader io.Reader) cry // BenchmarkSigning benchmarks the given signing algorithm using // the provided privkey. -func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) { +func BenchmarkSigning(b *testing.B, priv types.PrivKey) { message := []byte("Hello, world!") b.ResetTimer() for i := 0; i < b.N; i++ { @@ -47,7 +47,7 @@ func BenchmarkSigning(b *testing.B, priv crypto.PrivKey) { // BenchmarkVerification benchmarks the given verification algorithm using // the provided privkey on a constant message. -func BenchmarkVerification(b *testing.B, priv crypto.PrivKey) { +func BenchmarkVerification(b *testing.B, priv types.PrivKey) { pub := priv.PubKey() // use a short message, so this time doesn't get dominated by hashing. message := []byte("Hello, world!") diff --git a/crypto/keys/multisig/codec.go b/crypto/keys/multisig/codec.go index c282d012270e..b92576e4f3f5 100644 --- a/crypto/keys/multisig/codec.go +++ b/crypto/keys/multisig/codec.go @@ -1,7 +1,6 @@ package multisig import ( - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/sr25519" "github.com/cosmos/cosmos-sdk/codec" @@ -19,10 +18,6 @@ const ( var AminoCdc = codec.NewLegacyAmino() func init() { - // TODO We now register both Tendermint's PubKey and our own PubKey. In the - // long-term, we should move away from Tendermint's PubKey, and delete this - // first line. - AminoCdc.RegisterInterface((*crypto.PubKey)(nil), nil) AminoCdc.RegisterInterface((*cryptotypes.PubKey)(nil), nil) AminoCdc.RegisterConcrete(ed25519.PubKey{}, ed25519.PubKeyName, nil) diff --git a/crypto/keys/multisig/multisig.go b/crypto/keys/multisig/multisig.go index 836eadbe16af..590e5ba11001 100644 --- a/crypto/keys/multisig/multisig.go +++ b/crypto/keys/multisig/multisig.go @@ -5,10 +5,8 @@ import ( tmcrypto "github.com/tendermint/tendermint/crypto" - proto "github.com/gogo/protobuf/proto" - "github.com/cosmos/cosmos-sdk/codec/types" - crypto "github.com/cosmos/cosmos-sdk/crypto/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" multisigtypes "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) @@ -18,7 +16,7 @@ var _ types.UnpackInterfacesMessage = &LegacyAminoPubKey{} // NewLegacyAminoPubKey returns a new LegacyAminoPubKey. // Panics if len(pubKeys) < k or 0 >= k. -func NewLegacyAminoPubKey(k int, pubKeys []tmcrypto.PubKey) *LegacyAminoPubKey { +func NewLegacyAminoPubKey(k int, pubKeys []cryptotypes.PubKey) *LegacyAminoPubKey { if k <= 0 { panic("threshold k of n multisignature: k <= 0") } @@ -32,8 +30,8 @@ func NewLegacyAminoPubKey(k int, pubKeys []tmcrypto.PubKey) *LegacyAminoPubKey { return &LegacyAminoPubKey{Threshold: uint32(k), PubKeys: anyPubKeys} } -// Address implements crypto.PubKey Address method -func (m *LegacyAminoPubKey) Address() tmcrypto.Address { +// Address implements cryptotypes.PubKey Address method +func (m *LegacyAminoPubKey) Address() cryptotypes.Address { return tmcrypto.AddressHash(m.Bytes()) } @@ -91,7 +89,7 @@ func (m *LegacyAminoPubKey) VerifyMultisignature(getSignBytes multisigtypes.GetS return nil } -// VerifySignature implements crypto.PubKey VerifySignature method, +// VerifySignature implements cryptotypes.PubKey VerifySignature method, // it panics because it can't handle MultiSignatureData // cf. https://github.com/cosmos/cosmos-sdk/issues/7109#issuecomment-686329936 func (m *LegacyAminoPubKey) VerifySignature(msg []byte, sig []byte) bool { @@ -99,11 +97,11 @@ func (m *LegacyAminoPubKey) VerifySignature(msg []byte, sig []byte) bool { } // GetPubKeys implements the PubKey.GetPubKeys method -func (m *LegacyAminoPubKey) GetPubKeys() []tmcrypto.PubKey { +func (m *LegacyAminoPubKey) GetPubKeys() []cryptotypes.PubKey { if m != nil { - pubKeys := make([]tmcrypto.PubKey, len(m.PubKeys)) + pubKeys := make([]cryptotypes.PubKey, len(m.PubKeys)) for i := 0; i < len(m.PubKeys); i++ { - pubKeys[i] = m.PubKeys[i].GetCachedValue().(tmcrypto.PubKey) + pubKeys[i] = m.PubKeys[i].GetCachedValue().(cryptotypes.PubKey) } return pubKeys } @@ -113,7 +111,7 @@ func (m *LegacyAminoPubKey) GetPubKeys() []tmcrypto.PubKey { // Equals returns true if m and other both have the same number of keys, and // all constituent keys are the same, and in the same order. -func (m *LegacyAminoPubKey) Equals(key tmcrypto.PubKey) bool { +func (m *LegacyAminoPubKey) Equals(key cryptotypes.PubKey) bool { otherKey, ok := key.(multisigtypes.PubKey) if !ok { return false @@ -145,7 +143,7 @@ func (m *LegacyAminoPubKey) Type() string { // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (m *LegacyAminoPubKey) UnpackInterfaces(unpacker types.AnyUnpacker) error { for _, any := range m.PubKeys { - var pk crypto.PubKey + var pk cryptotypes.PubKey err := unpacker.UnpackAny(any, &pk) if err != nil { return err @@ -154,11 +152,11 @@ func (m *LegacyAminoPubKey) UnpackInterfaces(unpacker types.AnyUnpacker) error { return nil } -func packPubKeys(pubKeys []tmcrypto.PubKey) ([]*types.Any, error) { +func packPubKeys(pubKeys []cryptotypes.PubKey) ([]*types.Any, error) { anyPubKeys := make([]*types.Any, len(pubKeys)) for i := 0; i < len(pubKeys); i++ { - any, err := types.NewAnyWithValue(pubKeys[i].(proto.Message)) + any, err := types.NewAnyWithValue(pubKeys[i]) if err != nil { return nil, err } diff --git a/crypto/keys/multisig/multisig_test.go b/crypto/keys/multisig/multisig_test.go index 9c18c97d0691..2b91e74eb6c5 100644 --- a/crypto/keys/multisig/multisig_test.go +++ b/crypto/keys/multisig/multisig_test.go @@ -3,19 +3,16 @@ package multisig_test import ( "testing" - tmcrypto "github.com/tendermint/tendermint/crypto" - - "github.com/cosmos/cosmos-sdk/codec/types" - crypto "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/crypto/types/multisig" - "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" - "github.com/stretchr/testify/require" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/types/tx/signing" + "github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx" ) func TestAddress(t *testing.T) { @@ -30,12 +27,12 @@ func TestEquals(t *testing.T) { pubKey1 := secp256k1.GenPrivKey().PubKey() pubKey2 := secp256k1.GenPrivKey().PubKey() - multisigKey := kmultisig.NewLegacyAminoPubKey(1, []tmcrypto.PubKey{pubKey1, pubKey2}) - otherMultisigKey := kmultisig.NewLegacyAminoPubKey(1, []tmcrypto.PubKey{pubKey1, multisigKey}) + multisigKey := kmultisig.NewLegacyAminoPubKey(1, []cryptotypes.PubKey{pubKey1, pubKey2}) + otherMultisigKey := kmultisig.NewLegacyAminoPubKey(1, []cryptotypes.PubKey{pubKey1, multisigKey}) testCases := []struct { msg string - other tmcrypto.PubKey + other cryptotypes.PubKey expectEq bool }{ { @@ -255,8 +252,8 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { ab, err := kmultisig.AminoCdc.MarshalBinaryLengthPrefixed(multisigKey) require.NoError(t, err) - // like other crypto.Pubkey implementations (e.g. ed25519.PubKey), - // LegacyAminoPubKey should be deserializable into a crypto.LegacyAminoPubKey: + // like other cryptotypes.Pubkey implementations (e.g. ed25519.PubKey), + // LegacyAminoPubKey should be deserializable into a cryptotypes.LegacyAminoPubKey: var pubKey kmultisig.LegacyAminoPubKey err = kmultisig.AminoCdc.UnmarshalBinaryLengthPrefixed(ab, &pubKey) require.NoError(t, err) @@ -264,8 +261,8 @@ func TestPubKeyMultisigThresholdAminoToIface(t *testing.T) { require.Equal(t, multisigKey.Equals(&pubKey), true) } -func generatePubKeysAndSignatures(n int, msg []byte) (pubKeys []tmcrypto.PubKey, signatures []signing.SignatureData) { - pubKeys = make([]tmcrypto.PubKey, n) +func generatePubKeysAndSignatures(n int, msg []byte) (pubKeys []cryptotypes.PubKey, signatures []signing.SignatureData) { + pubKeys = make([]cryptotypes.PubKey, n) signatures = make([]signing.SignatureData, n) for i := 0; i < n; i++ { @@ -279,12 +276,12 @@ func generatePubKeysAndSignatures(n int, msg []byte) (pubKeys []tmcrypto.PubKey, } func generateNestedMultiSignature(n int, msg []byte) (multisig.PubKey, *signing.MultiSignatureData) { - pubKeys := make([]tmcrypto.PubKey, n) + pubKeys := make([]cryptotypes.PubKey, n) signatures := make([]signing.SignatureData, n) - bitArray := crypto.NewCompactBitArray(n) + bitArray := cryptotypes.NewCompactBitArray(n) for i := 0; i < n; i++ { nestedPks, nestedSigs := generatePubKeysAndSignatures(5, msg) - nestedBitArray := crypto.NewCompactBitArray(5) + nestedBitArray := cryptotypes.NewCompactBitArray(5) for j := 0; j < 5; j++ { nestedBitArray.SetIndex(j, true) } diff --git a/crypto/keys/secp256k1/bench_test.go b/crypto/keys/secp256k1/bench_test.go index e36f2df4b6e7..423f7a5a52de 100644 --- a/crypto/keys/secp256k1/bench_test.go +++ b/crypto/keys/secp256k1/bench_test.go @@ -4,13 +4,12 @@ import ( "io" "testing" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/internal/benchmarking" + "github.com/cosmos/cosmos-sdk/crypto/types" ) func BenchmarkKeyGeneration(b *testing.B) { - benchmarkKeygenWrapper := func(reader io.Reader) crypto.PrivKey { + benchmarkKeygenWrapper := func(reader io.Reader) types.PrivKey { priv := genPrivKey(reader) return &PrivKey{Key: priv} } diff --git a/crypto/keys/secp256k1/secp256k1.go b/crypto/keys/secp256k1/secp256k1.go index 77d546812c37..eebe72a45242 100644 --- a/crypto/keys/secp256k1/secp256k1.go +++ b/crypto/keys/secp256k1/secp256k1.go @@ -34,7 +34,7 @@ func (privKey *PrivKey) Bytes() []byte { // PubKey performs the point-scalar multiplication from the privKey on the // generator point to get the pubkey. -func (privKey *PrivKey) PubKey() crypto.PubKey { +func (privKey *PrivKey) PubKey() cryptotypes.PubKey { _, pubkeyObject := secp256k1.PrivKeyFromBytes(secp256k1.S256(), privKey.Key) pk := pubkeyObject.SerializeCompressed() return &PubKey{Key: pk} @@ -42,7 +42,7 @@ func (privKey *PrivKey) PubKey() crypto.PubKey { // Equals - you probably don't need to use this. // Runs in constant time based on length of the -func (privKey *PrivKey) Equals(other crypto.PrivKey) bool { +func (privKey *PrivKey) Equals(other cryptotypes.LedgerPrivKey) bool { return privKey.Type() == other.Type() && subtle.ConstantTimeCompare(privKey.Bytes(), other.Bytes()) == 1 } @@ -173,7 +173,7 @@ func (pubKey *PubKey) Type() string { return keyType } -func (pubKey *PubKey) Equals(other crypto.PubKey) bool { +func (pubKey *PubKey) Equals(other cryptotypes.PubKey) bool { return pubKey.Type() == other.Type() && bytes.Equal(pubKey.Bytes(), other.Bytes()) } diff --git a/crypto/keys/secp256k1/secp256k1_test.go b/crypto/keys/secp256k1/secp256k1_test.go index 0133d68509f5..d96b1dc38216 100644 --- a/crypto/keys/secp256k1/secp256k1_test.go +++ b/crypto/keys/secp256k1/secp256k1_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/sr25519" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) @@ -143,7 +143,7 @@ func TestPubKeyEquals(t *testing.T) { testCases := []struct { msg string pubKey cryptotypes.PubKey - other crypto.PubKey + other cryptotypes.PubKey expectEq bool }{ { @@ -163,7 +163,7 @@ func TestPubKeyEquals(t *testing.T) { { "different types", secp256K1PubKey, - sr25519.GenPrivKey().PubKey(), + ed25519.GenPrivKey().PubKey(), false, }, } @@ -182,7 +182,7 @@ func TestPrivKeyEquals(t *testing.T) { testCases := []struct { msg string privKey cryptotypes.PrivKey - other crypto.PrivKey + other cryptotypes.PrivKey expectEq bool }{ { @@ -202,7 +202,7 @@ func TestPrivKeyEquals(t *testing.T) { { "different types", secp256K1PrivKey, - sr25519.GenPrivKey(), + ed25519.GenPrivKey(), false, }, } diff --git a/crypto/ledger/encode_test.go b/crypto/ledger/encode_test.go index 6e0cf99f5242..447891fde768 100644 --- a/crypto/ledger/encode_test.go +++ b/crypto/ledger/encode_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" - tcrypto "github.com/tendermint/tendermint/crypto" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) type byter interface { @@ -51,12 +51,12 @@ func TestNilEncodings(t *testing.T) { require.EqualValues(t, a, b) // Check nil PubKey. - var c, d tcrypto.PubKey + var c, d cryptotypes.PubKey checkAminoJSON(t, &c, &d, true) require.EqualValues(t, c, d) // Check nil PrivKey. - var e, f tcrypto.PrivKey + var e, f cryptotypes.PrivKey checkAminoJSON(t, &e, &f, true) require.EqualValues(t, e, f) diff --git a/crypto/ledger/ledger_secp256k1.go b/crypto/ledger/ledger_secp256k1.go index 3afdbac5f321..659181d30648 100644 --- a/crypto/ledger/ledger_secp256k1.go +++ b/crypto/ledger/ledger_secp256k1.go @@ -8,10 +8,10 @@ import ( "github.com/pkg/errors" tmbtcec "github.com/tendermint/btcd/btcec" - tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + "github.com/cosmos/cosmos-sdk/crypto/types" ) var ( @@ -43,7 +43,7 @@ type ( // CachedPubKey should be private, but we want to encode it via // go-amino so we can view the address later, even without having the // ledger attached. - CachedPubKey tmcrypto.PubKey + CachedPubKey types.PubKey Path hd.BIP44Params } ) @@ -53,7 +53,7 @@ type ( // This function is marked as unsafe as it will retrieve a pubkey without user verification. // It can only be used to verify a pubkey but never to create new accounts/keys. In that case, // please refer to NewPrivKeySecp256k1 -func NewPrivKeySecp256k1Unsafe(path hd.BIP44Params) (tmcrypto.PrivKey, error) { +func NewPrivKeySecp256k1Unsafe(path hd.BIP44Params) (types.LedgerPrivKey, error) { device, err := getDevice() if err != nil { return nil, err @@ -70,7 +70,7 @@ func NewPrivKeySecp256k1Unsafe(path hd.BIP44Params) (tmcrypto.PrivKey, error) { // NewPrivKeySecp256k1 will generate a new key and store the public key for later use. // The request will require user confirmation and will show account and index in the device -func NewPrivKeySecp256k1(path hd.BIP44Params, hrp string) (tmcrypto.PrivKey, string, error) { +func NewPrivKeySecp256k1(path hd.BIP44Params, hrp string) (types.LedgerPrivKey, string, error) { device, err := getDevice() if err != nil { return nil, "", err @@ -86,7 +86,7 @@ func NewPrivKeySecp256k1(path hd.BIP44Params, hrp string) (tmcrypto.PrivKey, str } // PubKey returns the cached public key. -func (pkl PrivKeyLedgerSecp256k1) PubKey() tmcrypto.PubKey { +func (pkl PrivKeyLedgerSecp256k1) PubKey() types.PubKey { return pkl.CachedPubKey } @@ -102,7 +102,7 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) { } // ShowAddress triggers a ledger device to show the corresponding address. -func ShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey, +func ShowAddress(path hd.BIP44Params, expectedPubKey types.PubKey, accountAddressPrefix string) error { device, err := getDevice() if err != nil { @@ -154,7 +154,7 @@ func (pkl PrivKeyLedgerSecp256k1) Bytes() []byte { // Equals implements the PrivKey interface. It makes sure two private keys // refer to the same public key. -func (pkl PrivKeyLedgerSecp256k1) Equals(other tmcrypto.PrivKey) bool { +func (pkl PrivKeyLedgerSecp256k1) Equals(other types.LedgerPrivKey) bool { if otherKey, ok := other.(PrivKeyLedgerSecp256k1); ok { return pkl.CachedPubKey.Equals(otherKey.CachedPubKey) } @@ -234,7 +234,7 @@ func sign(device SECP256K1, pkl PrivKeyLedgerSecp256k1, msg []byte) ([]byte, err // // since this involves IO, it may return an error, which is not exposed // in the PubKey interface, so this function allows better error handling -func getPubKeyUnsafe(device SECP256K1, path hd.BIP44Params) (tmcrypto.PubKey, error) { +func getPubKeyUnsafe(device SECP256K1, path hd.BIP44Params) (types.PubKey, error) { publicKey, err := device.GetPublicKeySECP256K1(path.DerivationPath()) if err != nil { return nil, fmt.Errorf("please open Cosmos app on the Ledger device - error: %v", err) @@ -258,7 +258,7 @@ func getPubKeyUnsafe(device SECP256K1, path hd.BIP44Params) (tmcrypto.PubKey, er // // Since this involves IO, it may return an error, which is not exposed // in the PubKey interface, so this function allows better error handling. -func getPubKeyAddrSafe(device SECP256K1, path hd.BIP44Params, hrp string) (tmcrypto.PubKey, string, error) { +func getPubKeyAddrSafe(device SECP256K1, path hd.BIP44Params, hrp string) (types.PubKey, string, error) { publicKey, addr, err := device.GetAddressPubKeySECP256K1(path.DerivationPath(), hrp) if err != nil { return nil, "", fmt.Errorf("address %s rejected", addr) diff --git a/crypto/ledger/ledger_test.go b/crypto/ledger/ledger_test.go index 9b21e464bcdb..bc85b2feba0e 100644 --- a/crypto/ledger/ledger_test.go +++ b/crypto/ledger/ledger_test.go @@ -6,10 +6,9 @@ import ( "github.com/stretchr/testify/require" - tmcrypto "github.com/tendermint/tendermint/crypto" - cryptoAmino "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -58,7 +57,7 @@ func TestPublicKeyUnsafeHDPath(t *testing.T) { const numIters = 10 - privKeys := make([]tmcrypto.PrivKey, numIters) + privKeys := make([]types.LedgerPrivKey, numIters) // Check with device for i := uint32(0); i < 10; i++ { @@ -70,8 +69,8 @@ func TestPublicKeyUnsafeHDPath(t *testing.T) { require.NotNil(t, priv) // Check other methods - require.NoError(t, priv.(PrivKeyLedgerSecp256k1).ValidateKey()) tmp := priv.(PrivKeyLedgerSecp256k1) + require.NoError(t, tmp.ValidateKey()) (&tmp).AssertIsPrivKeyInner() pubKeyAddr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, priv.PubKey()) @@ -151,7 +150,7 @@ func TestPublicKeyHDPath(t *testing.T) { const numIters = 10 - privKeys := make([]tmcrypto.PrivKey, numIters) + privKeys := make([]types.LedgerPrivKey, numIters) // Check with device for i := uint32(0); i < 10; i++ { @@ -170,8 +169,8 @@ func TestPublicKeyHDPath(t *testing.T) { "Is your device using test mnemonic: %s ?", testutil.TestMnemonic) // Check other methods - require.NoError(t, priv.(PrivKeyLedgerSecp256k1).ValidateKey()) tmp := priv.(PrivKeyLedgerSecp256k1) + require.NoError(t, tmp.ValidateKey()) (&tmp).AssertIsPrivKeyInner() pubKeyAddr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, priv.PubKey()) diff --git a/crypto/types/multisig/multisignature.go b/crypto/types/multisig/multisignature.go index b13072e28047..20e3ef1129e4 100644 --- a/crypto/types/multisig/multisignature.go +++ b/crypto/types/multisig/multisignature.go @@ -4,8 +4,6 @@ import ( "fmt" "strings" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) @@ -27,7 +25,7 @@ func NewMultisig(n int) *signing.MultiSignatureData { } // GetIndex returns the index of pk in keys. Returns -1 if not found -func getIndex(pk crypto.PubKey, keys []crypto.PubKey) int { +func getIndex(pk types.PubKey, keys []types.PubKey) int { for i := 0; i < len(keys); i++ { if pk.Equals(keys[i]) { return i @@ -60,7 +58,7 @@ func AddSignature(mSig *signing.MultiSignatureData, sig signing.SignatureData, i // AddSignatureFromPubKey adds a signature to the multisig, at the index in // keys corresponding to the provided pubkey. -func AddSignatureFromPubKey(mSig *signing.MultiSignatureData, sig signing.SignatureData, pubkey crypto.PubKey, keys []crypto.PubKey) error { +func AddSignatureFromPubKey(mSig *signing.MultiSignatureData, sig signing.SignatureData, pubkey types.PubKey, keys []types.PubKey) error { if mSig == nil { return fmt.Errorf("value of mSig is nil %v", mSig) } @@ -85,6 +83,6 @@ func AddSignatureFromPubKey(mSig *signing.MultiSignatureData, sig signing.Signat return nil } -func AddSignatureV2(mSig *signing.MultiSignatureData, sig signing.SignatureV2, keys []crypto.PubKey) error { +func AddSignatureV2(mSig *signing.MultiSignatureData, sig signing.SignatureV2, keys []types.PubKey) error { return AddSignatureFromPubKey(mSig, sig.Data, sig.PubKey, keys) } diff --git a/crypto/types/multisig/pubkey.go b/crypto/types/multisig/pubkey.go index 51d432f59ca7..2e778bae6fd1 100644 --- a/crypto/types/multisig/pubkey.go +++ b/crypto/types/multisig/pubkey.go @@ -1,22 +1,21 @@ package multisig import ( - "github.com/tendermint/tendermint/crypto" - + "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) // PubKey defines a type which supports multi-signature verification via MultiSignatureData // which supports multiple SignMode's. type PubKey interface { - crypto.PubKey + types.PubKey // VerifyMultisignature verifies the provide multi-signature represented by MultiSignatureData // using getSignBytes to retrieve the sign bytes to verify against for the provided mode. VerifyMultisignature(getSignBytes GetSignBytesFunc, sig *signing.MultiSignatureData) error - // GetPubKeys returns the crypto.PubKey's nested within the multi-sig PubKey - GetPubKeys() []crypto.PubKey + // GetPubKeys returns the types.PubKey's nested within the multi-sig PubKey + GetPubKeys() []types.PubKey // GetThreshold returns the threshold number of signatures that must be obtained to verify a signature. GetThreshold() uint diff --git a/crypto/types/types.go b/crypto/types/types.go index bce35d716d3f..eccdba73813d 100644 --- a/crypto/types/types.go +++ b/crypto/types/types.go @@ -5,26 +5,39 @@ import ( tmcrypto "github.com/tendermint/tendermint/crypto" ) -// PubKey interface extends proto.Message -// and tendermint crypto.PubKey +// PubKey defines a public key and extends proto.Message. type PubKey interface { proto.Message - tmcrypto.PubKey + + Address() Address + Bytes() []byte + VerifySignature(msg []byte, sig []byte) bool + Equals(PubKey) bool + Type() string +} + +// LedgerPrivKey defines a private key that is not a proto message. For now, +// LedgerSecp256k1 keys are not converted to proto.Message yet, this is why +// they use LedgerPrivKey instead of PrivKey. All other keys must use PrivKey +// instead of LedgerPrivKey. +// TODO https://github.com/cosmos/cosmos-sdk/issues/7357. +type LedgerPrivKey interface { + Bytes() []byte + Sign(msg []byte) ([]byte, error) + PubKey() PubKey + Equals(LedgerPrivKey) bool + Type() string } -// PrivKey interface extends proto.Message -// and tendermint crypto.PrivKey +// PrivKey defines a private key and extends proto.Message. For now, it extends +// LedgerPrivKey (see godoc for LedgerPrivKey). Ultimately, we should remove +// LedgerPrivKey and add its methods here directly. +// TODO https://github.com/cosmos/cosmos-sdk/issues/7357. type PrivKey interface { proto.Message - tmcrypto.PrivKey + LedgerPrivKey } type ( Address = tmcrypto.Address ) - -// IntoTmPubKey allows our own PubKey types be converted into Tendermint's -// pubkey types. -type IntoTmPubKey interface { - AsTmPubKey() tmcrypto.PubKey -} diff --git a/server/tm_cmds.go b/server/tm_cmds.go index abea9c116fb6..b05a88f797da 100644 --- a/server/tm_cmds.go +++ b/server/tm_cmds.go @@ -39,7 +39,7 @@ func ShowNodeIDCmd() *cobra.Command { } } -// ShowValidator - ported from Tendermint, show this node's validator info +// ShowValidatorCmd - ported from Tendermint, show this node's validator info func ShowValidatorCmd() *cobra.Command { cmd := cobra.Command{ Use: "show-validator", @@ -59,12 +59,16 @@ func ShowValidatorCmd() *cobra.Command { return printlnJSON(valPubKey) } - pubkey, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, valPubKey) + pubkey, err := cryptocodec.FromTmPubKeyInterface(valPubKey) + if err != nil { + return err + } + pubkeyBech32, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubkey) if err != nil { return err } - fmt.Println(pubkey) + fmt.Println(pubkeyBech32) return nil }, } diff --git a/simapp/helpers/test_helpers.go b/simapp/helpers/test_helpers.go index 9e8a4d97143e..9ccecbd976c4 100644 --- a/simapp/helpers/test_helpers.go +++ b/simapp/helpers/test_helpers.go @@ -4,9 +4,8 @@ import ( "math/rand" "time" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -20,7 +19,7 @@ const ( ) // GenTx generates a signed mock transaction. -func GenTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, accSeqs []uint64, priv ...crypto.PrivKey) (sdk.Tx, error) { +func GenTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accNums, accSeqs []uint64, priv ...cryptotypes.PrivKey) (sdk.Tx, error) { sigs := make([]signing.SignatureV2, len(priv)) // create a random length memo diff --git a/simapp/simd/cmd/testnet.go b/simapp/simd/cmd/testnet.go index d17e57fb95f7..3355c04b4e71 100644 --- a/simapp/simd/cmd/testnet.go +++ b/simapp/simd/cmd/testnet.go @@ -12,7 +12,6 @@ import ( "github.com/spf13/cobra" tmconfig "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" tmos "github.com/tendermint/tendermint/libs/os" tmrand "github.com/tendermint/tendermint/libs/rand" "github.com/tendermint/tendermint/types" @@ -23,6 +22,7 @@ import ( "github.com/cosmos/cosmos-sdk/client/tx" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/server" srvconfig "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" @@ -116,7 +116,7 @@ func InitTestnet( } nodeIDs := make([]string, numValidators) - valPubKeys := make([]crypto.PubKey, numValidators) + valPubKeys := make([]cryptotypes.PubKey, numValidators) simappConfig := srvconfig.DefaultConfig() simappConfig.MinGasPrices = minGasPrices @@ -311,7 +311,7 @@ func initGenFiles( func collectGenFiles( clientCtx client.Context, nodeConfig *tmconfig.Config, chainID string, - nodeIDs []string, valPubKeys []crypto.PubKey, numValidators int, + nodeIDs []string, valPubKeys []cryptotypes.PubKey, numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, ) error { diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 6624c1df3fbc..22df884fbb25 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -11,7 +11,6 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/types" @@ -20,7 +19,9 @@ import ( bam "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp/helpers" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/errors" @@ -92,10 +93,7 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs bondAmt := sdk.NewInt(1000000) for _, val := range valSet.Validators { - // Currently validator requires tmcrypto.ed25519 keys, which don't support - // our Marshaling interfaces, so we need to pack them into our version of ed25519. - // There is ongoing work to add secp256k1 keys (https://github.com/cosmos/cosmos-sdk/pull/7604). - pk, err := ed25519.FromTmEd25519(val.PubKey) + pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) require.NoError(t, err) pkAny, err := codectypes.PackAny(pk) require.NoError(t, err) @@ -230,7 +228,7 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress { } // AddTestAddrsFromPubKeys adds the addresses into the SimApp providing only the public keys. -func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []crypto.PubKey, accAmt sdk.Int) { +func AddTestAddrsFromPubKeys(app *SimApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) { initCoins := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), accAmt)) setTotalSupply(app, ctx, accAmt, len(pubKeys)) @@ -328,7 +326,7 @@ func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.C // returned. func SignCheckDeliver( t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, - chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...crypto.PrivKey, + chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { tx, err := helpers.GenTx( @@ -377,7 +375,7 @@ func SignCheckDeliver( // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. -func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...crypto.PrivKey) ([]sdk.Tx, error) { +func GenSequenceOfTxs(txGen client.TxConfig, msgs []sdk.Msg, accNums []uint64, initSeqNums []uint64, numToGenerate int, priv ...cryptotypes.PrivKey) ([]sdk.Tx, error) { txs := make([]sdk.Tx, numToGenerate) var err error for i := 0; i < numToGenerate; i++ { @@ -407,8 +405,8 @@ func incrementAllSequenceNumbers(initSeqNums []uint64) { } // CreateTestPubKeys returns a total of numPubKeys public keys in ascending order. -func CreateTestPubKeys(numPubKeys int) []crypto.PubKey { - var publicKeys []crypto.PubKey +func CreateTestPubKeys(numPubKeys int) []cryptotypes.PubKey { + var publicKeys []cryptotypes.PubKey var buffer bytes.Buffer // start at 10 to avoid changing 1 to 01, 2 to 02, etc @@ -424,7 +422,7 @@ func CreateTestPubKeys(numPubKeys int) []crypto.PubKey { } // NewPubKeyFromHex returns a PubKey from a hex string. -func NewPubKeyFromHex(pk string) (res crypto.PubKey) { +func NewPubKeyFromHex(pk string) (res cryptotypes.PubKey) { pkBytes, err := hex.DecodeString(pk) if err != nil { panic(err) diff --git a/tests/mocks/account_retriever.go b/tests/mocks/account_retriever.go index 23b02b7dce2b..37fa1aa64da0 100644 --- a/tests/mocks/account_retriever.go +++ b/tests/mocks/account_retriever.go @@ -6,9 +6,9 @@ package mocks import ( client "github.com/cosmos/cosmos-sdk/client" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" types "github.com/cosmos/cosmos-sdk/types" gomock "github.com/golang/mock/gomock" - crypto "github.com/tendermint/tendermint/crypto" reflect "reflect" ) @@ -50,10 +50,10 @@ func (mr *MockAccountMockRecorder) GetAddress() *gomock.Call { } // GetPubKey mocks base method -func (m *MockAccount) GetPubKey() crypto.PubKey { +func (m *MockAccount) GetPubKey() cryptotypes.PubKey { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPubKey") - ret0, _ := ret[0].(crypto.PubKey) + ret0, _ := ret[0].(cryptotypes.PubKey) return ret0 } diff --git a/testutil/network/network.go b/testutil/network/network.go index 1ee11f8c933d..a50c6fa935af 100644 --- a/testutil/network/network.go +++ b/testutil/network/network.go @@ -16,7 +16,6 @@ import ( "github.com/stretchr/testify/require" tmcfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" tmflags "github.com/tendermint/tendermint/libs/cli/flags" "github.com/tendermint/tendermint/libs/log" tmrand "github.com/tendermint/tendermint/libs/rand" @@ -32,6 +31,7 @@ import ( codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/server" "github.com/cosmos/cosmos-sdk/server/api" srvconfig "github.com/cosmos/cosmos-sdk/server/config" @@ -148,7 +148,7 @@ type ( Ctx *server.Context Dir string NodeID string - PubKey crypto.PubKey + PubKey cryptotypes.PubKey Moniker string APIAddress string RPCAddress string @@ -184,7 +184,7 @@ func New(t *testing.T, cfg Config) *Network { monikers := make([]string, cfg.NumValidators) nodeIDs := make([]string, cfg.NumValidators) - valPubKeys := make([]crypto.PubKey, cfg.NumValidators) + valPubKeys := make([]cryptotypes.PubKey, cfg.NumValidators) var ( genAccounts []authtypes.GenesisAccount diff --git a/testutil/testdata/tx.go b/testutil/testdata/tx.go index 09e1e365f1ca..153846083074 100644 --- a/testutil/testdata/tx.go +++ b/testutil/testdata/tx.go @@ -3,14 +3,13 @@ package testdata import ( "encoding/json" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) // KeyTestPubAddr generates a new secp256k1 keypair. -func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { +func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) diff --git a/types/address.go b/types/address.go index 345c44fa8e1c..a6d65e7a703e 100644 --- a/types/address.go +++ b/types/address.go @@ -8,16 +8,12 @@ import ( "fmt" "strings" - "github.com/tendermint/tendermint/crypto" - tmed25519 "github.com/tendermint/tendermint/crypto/ed25519" yaml "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/codec/legacy" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/bech32" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) const ( @@ -452,7 +448,7 @@ func ConsAddressFromBech32(address string) (addr ConsAddress, err error) { } // get ConsAddress from pubkey -func GetConsAddress(pubkey crypto.PubKey) ConsAddress { +func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress { return ConsAddress(pubkey.Address()) } @@ -616,7 +612,8 @@ const ( // Bech32ifyPubKey returns a Bech32 encoded string containing the appropriate // prefix based on the key type provided for a given PublicKey. -func Bech32ifyPubKey(pkt Bech32PubKeyType, pubkey crypto.PubKey) (string, error) { +// TODO: Remove Bech32ifyPubKey and all usages (cosmos/cosmos-sdk/issues/#7357) +func Bech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) (string, error) { var bech32Prefix string switch pkt { @@ -631,22 +628,11 @@ func Bech32ifyPubKey(pkt Bech32PubKeyType, pubkey crypto.PubKey) (string, error) } - // This piece of code is to keep backwards-compatibility. - // For ed25519 keys, our own ed25519 is registered in Amino under a - // different name than TM's ed25519. But since users are already using - // TM's ed25519 bech32 encoding, we explicitly say to bech32-encode our own - // ed25519 the same way as TM's ed25519. - // TODO: Remove Bech32ifyPubKey and all usages (cosmos/cosmos-sdk/issues/#7357) - pkToMarshal := pubkey - if ed25519Pk, ok := pubkey.(*ed25519.PubKey); ok { - pkToMarshal = ed25519Pk.AsTmPubKey() - } - - return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshalBinaryBare(pkToMarshal)) + return bech32.ConvertAndEncode(bech32Prefix, legacy.Cdc.MustMarshalBinaryBare(pubkey)) } // MustBech32ifyPubKey calls Bech32ifyPubKey except it panics on error. -func MustBech32ifyPubKey(pkt Bech32PubKeyType, pubkey crypto.PubKey) string { +func MustBech32ifyPubKey(pkt Bech32PubKeyType, pubkey cryptotypes.PubKey) string { res, err := Bech32ifyPubKey(pkt, pubkey) if err != nil { panic(err) @@ -657,7 +643,7 @@ func MustBech32ifyPubKey(pkt Bech32PubKeyType, pubkey crypto.PubKey) string { // GetPubKeyFromBech32 returns a PublicKey from a bech32-encoded PublicKey with // a given key type. -func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (crypto.PubKey, error) { +func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (cryptotypes.PubKey, error) { var bech32Prefix string switch pkt { @@ -677,36 +663,11 @@ func GetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) (crypto.PubKey, return nil, err } - aminoPk, err := cryptocodec.PubKeyFromBytes(bz) - if err != nil { - return nil, err - } - - var protoPk crypto.PubKey - switch aminoPk.(type) { - - // We are bech32ifying some secp256k1 keys in tests. - case *secp256k1.PubKey: - protoPk = aminoPk - case *ed25519.PubKey: - protoPk = aminoPk - - // Real-life case. - case tmed25519.PubKey: - protoPk = &ed25519.PubKey{ - Key: aminoPk.Bytes(), - } - - default: - // We only allow ed25519 pubkeys to be bech32-ed right now. - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "bech32 pubkey does not support %T", aminoPk) - } - - return protoPk, nil + return cryptocodec.PubKeyFromBytes(bz) } // MustGetPubKeyFromBech32 calls GetPubKeyFromBech32 except it panics on error. -func MustGetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) crypto.PubKey { +func MustGetPubKeyFromBech32(pkt Bech32PubKeyType, pubkeyStr string) cryptotypes.PubKey { res, err := GetPubKeyFromBech32(pkt, pubkeyStr) if err != nil { panic(err) diff --git a/types/address_test.go b/types/address_test.go index 9de4bea4f360..5796c891acb0 100644 --- a/types/address_test.go +++ b/types/address_test.go @@ -10,11 +10,11 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/tendermint/tendermint/crypto" "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types" ) @@ -509,7 +509,7 @@ func (s *addressTestSuite) TestGetConsAddress() { pk := secp256k1.GenPrivKey().PubKey() s.Require().NotEqual(types.GetConsAddress(pk), pk.Address()) s.Require().True(bytes.Equal(types.GetConsAddress(pk).Bytes(), pk.Address().Bytes())) - s.Require().Panics(func() { types.GetConsAddress(crypto.PubKey(nil)) }) + s.Require().Panics(func() { types.GetConsAddress(cryptotypes.PubKey(nil)) }) } func (s *addressTestSuite) TestGetFromBech32() { diff --git a/types/rest/rest_test.go b/types/rest/rest_test.go index b4bf386117cc..0a3e16b29d6d 100644 --- a/types/rest/rest_test.go +++ b/types/rest/rest_test.go @@ -12,13 +12,13 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" @@ -176,15 +176,15 @@ func TestParseQueryHeight(t *testing.T) { func TestProcessPostResponse(t *testing.T) { // mock account // PubKey field ensures amino encoding is used first since standard - // JSON encoding will panic on crypto.PubKey + // JSON encoding will panic on cryptotypes.PubKey t.Parallel() type mockAccount struct { - Address types.AccAddress `json:"address"` - Coins types.Coins `json:"coins"` - PubKey crypto.PubKey `json:"public_key"` - AccountNumber uint64 `json:"account_number"` - Sequence uint64 `json:"sequence"` + Address types.AccAddress `json:"address"` + Coins types.Coins `json:"coins"` + PubKey cryptotypes.PubKey `json:"public_key"` + AccountNumber uint64 `json:"account_number"` + Sequence uint64 `json:"sequence"` } // setup diff --git a/types/simulation/account.go b/types/simulation/account.go index b0c6b7bd687a..e031b5a9ebbe 100644 --- a/types/simulation/account.go +++ b/types/simulation/account.go @@ -3,10 +3,9 @@ package simulation import ( "math/rand" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -14,10 +13,10 @@ import ( // eventually more useful data can be placed in here. // (e.g. number of coins) type Account struct { - PrivKey crypto.PrivKey - PubKey crypto.PubKey + PrivKey cryptotypes.PrivKey + PubKey cryptotypes.PubKey Address sdk.AccAddress - ConsKey crypto.PrivKey + ConsKey cryptotypes.PrivKey } // Equals returns true if two accounts are equal diff --git a/types/tx/signing/signature.go b/types/tx/signing/signature.go index 0966cc06f71a..1323543f023a 100644 --- a/types/tx/signing/signature.go +++ b/types/tx/signing/signature.go @@ -3,9 +3,8 @@ package signing import ( "fmt" - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) // SignatureV2 is a convenience type that is easier to use in application logic @@ -15,7 +14,7 @@ import ( // signatures. type SignatureV2 struct { // PubKey is the public key to use for verifying the signature - PubKey crypto.PubKey + PubKey cryptotypes.PubKey // Data is the actual data of the signature which includes SignMode's and // the signatures themselves for either single or multi-signatures. @@ -104,5 +103,5 @@ func (sds *SignatureDescriptors) UnpackInterfaces(unpacker codectypes.AnyUnpacke // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method func (sd *SignatureDescriptor) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return unpacker.UnpackAny(sd.PublicKey, new(crypto.PubKey)) + return unpacker.UnpackAny(sd.PublicKey, new(cryptotypes.PubKey)) } diff --git a/types/tx/types.go b/types/tx/types.go index 436f2cd9bc4d..c572d448a898 100644 --- a/types/tx/types.go +++ b/types/tx/types.go @@ -4,9 +4,8 @@ import ( "fmt" "strings" - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -180,7 +179,7 @@ func (m *AuthInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method func (m *SignerInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return unpacker.UnpackAny(m.PublicKey, new(crypto.PubKey)) + return unpacker.UnpackAny(m.PublicKey, new(cryptotypes.PubKey)) } // RegisterInterfaces registers the sdk.Tx interface. diff --git a/types/tx_msg.go b/types/tx_msg.go index e75b7b6ae62a..ddc07fa16b40 100644 --- a/types/tx_msg.go +++ b/types/tx_msg.go @@ -1,9 +1,8 @@ package types import ( + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/gogo/protobuf/proto" - - "github.com/tendermint/tendermint/crypto" ) type ( @@ -42,7 +41,7 @@ type ( // Signature defines an interface for an application application-defined // concrete transaction type to be able to set and return transaction signatures. Signature interface { - GetPubKey() crypto.PubKey + GetPubKey() cryptotypes.PubKey GetSignature() []byte } diff --git a/x/auth/ante/ante_test.go b/x/auth/ante/ante_test.go index 0d9ef82f44be..7659f3e1043d 100644 --- a/x/auth/ante/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -8,11 +8,11 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -35,7 +35,7 @@ func (suite *AnteTestSuite) TestSimulateGasCost() { feeAmount := testdata.NewTestFeeAmount() gasLimit := testdata.NewTestGasLimit() accSeqs := []uint64{0, 0, 0} - privs := []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv} + privs := []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv} accNums := []uint64{0, 1, 2} testCases := []TestCase{ @@ -91,7 +91,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { // Variable data per test case var ( - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accNums []uint64 accSeqs []uint64 ) @@ -100,7 +100,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { { "check no signatures fails", func() { - privs, accNums, accSeqs = []crypto.PrivKey{}, []uint64{}, []uint64{} + privs, accNums, accSeqs = []cryptotypes.PrivKey{}, []uint64{}, []uint64{} // Create tx manually to test the tx's signers suite.Require().NoError(suite.txBuilder.SetMsgs(msgs...)) @@ -117,7 +117,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { { "num sigs dont match GetSigners", func() { - privs, accNums, accSeqs = []crypto.PrivKey{priv0}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{priv0}, []uint64{0}, []uint64{0} }, false, false, @@ -126,7 +126,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigErrors() { { "unrecognized account", func() { - privs, accNums, accSeqs = []crypto.PrivKey{priv0, priv1, priv2}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{priv0, priv1, priv2}, []uint64{0, 1, 2}, []uint64{0, 0, 0} }, false, false, @@ -169,7 +169,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -180,7 +180,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, true, @@ -189,7 +189,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { { "new tx from wrong account number", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} }, false, false, @@ -198,7 +198,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { { "new tx from correct account number", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} }, false, true, @@ -210,7 +210,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { msg1 := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) msg2 := testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg1, msg2} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} }, false, false, @@ -219,7 +219,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbers() { { "new tx with correct account numbers", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{2, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{2, 0} }, false, true, @@ -251,7 +251,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -262,7 +262,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, true, @@ -271,7 +271,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { { "new tx from wrong account number", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{1} }, false, false, @@ -280,7 +280,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { { "new tx from correct account number", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} }, false, true, @@ -293,7 +293,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { msg2 := testdata.NewTestMsg(accounts[1].acc.GetAddress(), accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg1, msg2} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{1, 0}, []uint64{2, 0} }, false, false, @@ -303,7 +303,7 @@ func (suite *AnteTestSuite) TestAnteHandlerAccountNumbersAtBlockHeightZero() { "new tx with another signer and correct account numbers", func() { // Note that accNums is [0,0] at block 0. - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 0}, []uint64{2, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 0}, []uint64{2, 0} }, false, true, @@ -334,7 +334,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -345,7 +345,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { msg := testdata.NewTestMsg(accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, true, @@ -354,7 +354,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { { "test sending it again fails (replay protection)", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, false, @@ -363,7 +363,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { { "fix sequence, should pass", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{1} }, false, true, @@ -376,7 +376,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { msg2 := testdata.NewTestMsg(accounts[2].acc.GetAddress(), accounts[0].acc.GetAddress()) msgs = []sdk.Msg{msg1, msg2} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{2, 0, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{2, 0, 0} }, false, true, @@ -394,7 +394,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { func() { msg := testdata.NewTestMsg(accounts[1].acc.GetAddress()) msgs = []sdk.Msg{msg} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} }, false, false, @@ -415,7 +415,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSequences() { msg := testdata.NewTestMsg(accounts[0].acc.GetAddress(), accounts[1].acc.GetAddress()) msgs = []sdk.Msg{msg} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{3, 2} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{3, 2} }, false, true, @@ -445,7 +445,7 @@ func (suite *AnteTestSuite) TestAnteHandlerFees() { msgs := []sdk.Msg{testdata.NewTestMsg(addr0)} feeAmount := testdata.NewTestFeeAmount() gasLimit := testdata.NewTestGasLimit() - privs, accNums, accSeqs := []crypto.PrivKey{priv0}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv0}, []uint64{0}, []uint64{0} testCases := []struct { desc string @@ -517,7 +517,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMemoGas() { // Same data for every test cases accounts := suite.CreateTestAccounts(1) msgs := []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} - privs, accNums, accSeqs := []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} // Variable data per test case var ( @@ -596,7 +596,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -605,7 +605,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { "signers in order", func() { msgs = []sdk.Msg{msg1, msg2, msg3} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{0, 0, 0} suite.txBuilder.SetMemo("Check signers are in expected order and different account numbers works") }, false, @@ -616,7 +616,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { "change sequence numbers (only accounts 0 and 1 sign)", func() { msgs = []sdk.Msg{msg1} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{1, 1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv}, []uint64{0, 1}, []uint64{1, 1} }, false, true, @@ -626,7 +626,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { "change sequence numbers (only accounts 1 and 2 sign)", func() { msgs = []sdk.Msg{msg2} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[2].priv, accounts[0].priv}, []uint64{2, 0}, []uint64{1, 2} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[2].priv, accounts[0].priv}, []uint64{2, 0}, []uint64{1, 2} }, false, true, @@ -636,7 +636,7 @@ func (suite *AnteTestSuite) TestAnteHandlerMultiSigner() { "everyone signs again", func() { msgs = []sdk.Msg{msg1, msg2, msg3} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{3, 2, 2} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv, accounts[1].priv, accounts[2].priv}, []uint64{0, 1, 2}, []uint64{3, 2, 2} }, false, true, @@ -668,7 +668,7 @@ func (suite *AnteTestSuite) TestAnteHandlerBadSignBytes() { feeAmount sdk.Coins gasLimit uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -680,7 +680,7 @@ func (suite *AnteTestSuite) TestAnteHandlerBadSignBytes() { feeAmount = testdata.NewTestFeeAmount() gasLimit = testdata.NewTestGasLimit() msgs = []sdk.Msg{msg0} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, true, @@ -752,7 +752,7 @@ func (suite *AnteTestSuite) TestAnteHandlerBadSignBytes() { func() { feeAmount = testdata.NewTestFeeAmount() gasLimit = testdata.NewTestGasLimit() - privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{0}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[1].priv}, []uint64{0}, []uint64{1} }, false, false, @@ -762,7 +762,7 @@ func (suite *AnteTestSuite) TestAnteHandlerBadSignBytes() { "test wrong signer if public doesn't exist", func() { msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{1}, []uint64{0} }, false, false, @@ -792,7 +792,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -800,7 +800,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { { "test good tx", func() { - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} msgs = []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} }, false, @@ -835,7 +835,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { acc1 := suite.app.AccountKeeper.GetAccount(suite.ctx, accounts[1].acc.GetAddress()) suite.Require().Nil(acc1.GetPubKey()) - privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{0} msgs = []sdk.Msg{testdata.NewTestMsg(accounts[1].acc.GetAddress())} suite.txBuilder.SetMsgs(msgs...) suite.txBuilder.SetFeeAmount(feeAmount) @@ -858,7 +858,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { suite.Require().Nil(acc1.GetPubKey()) // Set incorrect accSeq, to generate incorrect signature. - privs, accNums, accSeqs = []crypto.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{1} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[1].priv}, []uint64{1}, []uint64{1} }, false, false, @@ -888,11 +888,11 @@ func (suite *AnteTestSuite) TestAnteHandlerSetPubKey() { } } -func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []crypto.PubKey, signatures [][]byte) { - pubkeys = make([]crypto.PubKey, n) +func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []cryptotypes.PubKey, signatures [][]byte) { + pubkeys = make([]cryptotypes.PubKey, n) signatures = make([][]byte, n) for i := 0; i < n; i++ { - var privkey crypto.PrivKey + var privkey cryptotypes.PrivKey privkey = secp256k1.GenPrivKey() // TODO: also generate ed25519 keys as below when ed25519 keys are @@ -910,7 +910,7 @@ func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []crypto.P return } -func expectedGasCostByKeys(pubkeys []crypto.PubKey) uint64 { +func expectedGasCostByKeys(pubkeys []cryptotypes.PubKey) uint64 { cost := uint64(0) for _, pubkey := range pubkeys { pubkeyType := strings.ToLower(fmt.Sprintf("%T", pubkey)) @@ -927,8 +927,8 @@ func expectedGasCostByKeys(pubkeys []crypto.PubKey) uint64 { } func TestCountSubkeys(t *testing.T) { - genPubKeys := func(n int) []crypto.PubKey { - var ret []crypto.PubKey + genPubKeys := func(n int) []cryptotypes.PubKey { + var ret []cryptotypes.PubKey for i := 0; i < n; i++ { ret = append(ret, secp256k1.GenPrivKey().PubKey()) } @@ -938,10 +938,10 @@ func TestCountSubkeys(t *testing.T) { singleLevelMultiKey := kmultisig.NewLegacyAminoPubKey(4, genPubKeys(5)) multiLevelSubKey1 := kmultisig.NewLegacyAminoPubKey(4, genPubKeys(5)) multiLevelSubKey2 := kmultisig.NewLegacyAminoPubKey(4, genPubKeys(5)) - multiLevelMultiKey := kmultisig.NewLegacyAminoPubKey(2, []crypto.PubKey{ + multiLevelMultiKey := kmultisig.NewLegacyAminoPubKey(2, []cryptotypes.PubKey{ multiLevelSubKey1, multiLevelSubKey2, secp256k1.GenPrivKey().PubKey()}) type args struct { - pub crypto.PubKey + pub cryptotypes.PubKey } testCases := []struct { name string @@ -965,7 +965,7 @@ func (suite *AnteTestSuite) TestAnteHandlerSigLimitExceeded() { // Same data for every test cases accounts := suite.CreateTestAccounts(8) var addrs []sdk.AccAddress - var privs []crypto.PrivKey + var privs []cryptotypes.PrivKey for i := 0; i < 8; i++ { addrs = append(addrs, accounts[i].acc.GetAddress()) privs = append(privs, accounts[i].priv) @@ -1019,7 +1019,7 @@ func (suite *AnteTestSuite) TestCustomSignatureVerificationGasConsumer() { var ( accNums []uint64 msgs []sdk.Msg - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accSeqs []uint64 ) @@ -1028,7 +1028,7 @@ func (suite *AnteTestSuite) TestCustomSignatureVerificationGasConsumer() { "verify that an secp256k1 account gets rejected", func() { msgs = []sdk.Msg{testdata.NewTestMsg(accounts[0].acc.GetAddress())} - privs, accNums, accSeqs = []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} }, false, false, @@ -1067,7 +1067,7 @@ func (suite *AnteTestSuite) TestAnteHandlerReCheck() { suite.txBuilder.SetMemo("thisisatestmemo") // test that operations skipped on recheck do not run - privs, accNums, accSeqs := []crypto.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{accounts[0].priv}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) diff --git a/x/auth/ante/basic.go b/x/auth/ante/basic.go index f722e51a04ec..7ed834ebaa37 100644 --- a/x/auth/ante/basic.go +++ b/x/auth/ante/basic.go @@ -1,10 +1,9 @@ package ante import ( - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec/legacy" "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -110,7 +109,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim continue } - var pubkey crypto.PubKey + var pubkey cryptotypes.PubKey acc := cgts.ak.GetAccount(ctx, signer) diff --git a/x/auth/ante/basic_test.go b/x/auth/ante/basic_test.go index 8b304d180e51..08567348857e 100644 --- a/x/auth/ante/basic_test.go +++ b/x/auth/ante/basic_test.go @@ -3,13 +3,11 @@ package ante_test import ( "strings" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - "github.com/cosmos/cosmos-sdk/types/tx/signing" - - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" + "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/ante" ) @@ -28,7 +26,7 @@ func (suite *AnteTestSuite) TestValidateBasic() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{}, []uint64{}, []uint64{} + privs, accNums, accSeqs := []cryptotypes.PrivKey{}, []uint64{}, []uint64{} invalidTx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -38,7 +36,7 @@ func (suite *AnteTestSuite) TestValidateBasic() { suite.Require().NotNil(err, "Did not error on invalid tx") - privs, accNums, accSeqs = []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs = []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} validTx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -69,7 +67,7 @@ func (suite *AnteTestSuite) TestValidateMemo() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} suite.txBuilder.SetMemo(strings.Repeat("01234567890", 500)) invalidTx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -120,7 +118,7 @@ func (suite *AnteTestSuite) TestConsumeGasForTxSize() { suite.txBuilder.SetGasLimit(gasLimit) suite.txBuilder.SetMemo(strings.Repeat("01234567890", 10)) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -214,7 +212,7 @@ func (suite *AnteTestSuite) TestTxHeightTimeoutDecorator() { suite.txBuilder.SetMemo(strings.Repeat("01234567890", 10)) suite.txBuilder.SetTimeoutHeight(tc.timeout) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) diff --git a/x/auth/ante/fee_test.go b/x/auth/ante/fee_test.go index 4264baf399bb..84e5adb60db7 100644 --- a/x/auth/ante/fee_test.go +++ b/x/auth/ante/fee_test.go @@ -1,10 +1,9 @@ package ante_test import ( + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" - "github.com/tendermint/tendermint/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth/ante" ) @@ -27,7 +26,7 @@ func (suite *AnteTestSuite) TestEnsureMempoolFees() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -76,7 +75,7 @@ func (suite *AnteTestSuite) TestDeductFees() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) diff --git a/x/auth/ante/setup_test.go b/x/auth/ante/setup_test.go index 8454ec26a191..4942665cac04 100644 --- a/x/auth/ante/setup_test.go +++ b/x/auth/ante/setup_test.go @@ -1,10 +1,8 @@ package ante_test import ( + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" - - "github.com/tendermint/tendermint/crypto" - sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/ante" @@ -25,7 +23,7 @@ func (suite *AnteTestSuite) TestSetup() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -60,7 +58,7 @@ func (suite *AnteTestSuite) TestRecoverPanic() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) diff --git a/x/auth/ante/sigverify.go b/x/auth/ante/sigverify.go index 80ea9317e1c7..79fbbcdc676a 100644 --- a/x/auth/ante/sigverify.go +++ b/x/auth/ante/sigverify.go @@ -5,11 +5,10 @@ import ( "encoding/hex" "fmt" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -424,7 +423,7 @@ func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (types } // CountSubKeys counts the total number of keys for a multi-sig public key. -func CountSubKeys(pub crypto.PubKey) int { +func CountSubKeys(pub cryptotypes.PubKey) int { v, ok := pub.(*kmultisig.LegacyAminoPubKey) if !ok { return 1 diff --git a/x/auth/ante/sigverify_test.go b/x/auth/ante/sigverify_test.go index 2eb235b2f1be..337618fab50f 100644 --- a/x/auth/ante/sigverify_test.go +++ b/x/auth/ante/sigverify_test.go @@ -3,13 +3,12 @@ package ante_test import ( "fmt" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil/testdata" @@ -30,7 +29,7 @@ func (suite *AnteTestSuite) TestSetPubKey() { priv3, pub3, addr3 := testdata.KeyTestPubAddr() addrs := []sdk.AccAddress{addr1, addr2, addr3} - pubs := []crypto.PubKey{pub1, pub2, pub3} + pubs := []cryptotypes.PubKey{pub1, pub2, pub3} msgs := make([]sdk.Msg, len(addrs)) // set accounts and create msg for each address @@ -47,7 +46,7 @@ func (suite *AnteTestSuite) TestSetPubKey() { suite.txBuilder.SetFeeAmount(feeAmount) suite.txBuilder.SetGasLimit(gasLimit) - privs, accNums, accSeqs := []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0} tx, err := suite.CreateTestTx(privs, accNums, accSeqs, suite.ctx.ChainID()) suite.Require().NoError(err) @@ -85,7 +84,7 @@ func (suite *AnteTestSuite) TestConsumeSignatureVerificationGas() { type args struct { meter sdk.GasMeter sig signing.SignatureData - pubkey crypto.PubKey + pubkey cryptotypes.PubKey params types.Params } tests := []struct { @@ -148,20 +147,20 @@ func (suite *AnteTestSuite) TestSigVerification() { type testCase struct { name string - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accNums []uint64 accSeqs []uint64 recheck bool shouldErr bool } testCases := []testCase{ - {"no signers", []crypto.PrivKey{}, []uint64{}, []uint64{}, false, true}, - {"not enough signers", []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0}, false, true}, - {"wrong order signers", []crypto.PrivKey{priv3, priv2, priv1}, []uint64{2, 1, 0}, []uint64{0, 0, 0}, false, true}, - {"wrong accnums", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{7, 8, 9}, []uint64{0, 0, 0}, false, true}, - {"wrong sequences", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{3, 4, 5}, false, true}, - {"valid tx", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}, false, false}, - {"no err on recheck", []crypto.PrivKey{}, []uint64{}, []uint64{}, true, false}, + {"no signers", []cryptotypes.PrivKey{}, []uint64{}, []uint64{}, false, true}, + {"not enough signers", []cryptotypes.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0}, false, true}, + {"wrong order signers", []cryptotypes.PrivKey{priv3, priv2, priv1}, []uint64{2, 1, 0}, []uint64{0, 0, 0}, false, true}, + {"wrong accnums", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{7, 8, 9}, []uint64{0, 0, 0}, false, true}, + {"wrong sequences", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{3, 4, 5}, false, true}, + {"valid tx", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}, false, false}, + {"no err on recheck", []cryptotypes.PrivKey{}, []uint64{}, []uint64{}, true, false}, } for i, tc := range testCases { suite.ctx = suite.ctx.WithIsReCheckTx(tc.recheck) @@ -233,20 +232,20 @@ func (suite *AnteTestSuite) TestSigVerification_ExplicitAmino() { type testCase struct { name string - privs []crypto.PrivKey + privs []cryptotypes.PrivKey accNums []uint64 accSeqs []uint64 recheck bool shouldErr bool } testCases := []testCase{ - {"no signers", []crypto.PrivKey{}, []uint64{}, []uint64{}, false, true}, - {"not enough signers", []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0}, false, true}, - {"wrong order signers", []crypto.PrivKey{priv3, priv2, priv1}, []uint64{2, 1, 0}, []uint64{0, 0, 0}, false, true}, - {"wrong accnums", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{7, 8, 9}, []uint64{0, 0, 0}, false, true}, - {"wrong sequences", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{3, 4, 5}, false, true}, - {"valid tx", []crypto.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}, false, false}, - {"no err on recheck", []crypto.PrivKey{}, []uint64{}, []uint64{}, true, false}, + {"no signers", []cryptotypes.PrivKey{}, []uint64{}, []uint64{}, false, true}, + {"not enough signers", []cryptotypes.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0}, false, true}, + {"wrong order signers", []cryptotypes.PrivKey{priv3, priv2, priv1}, []uint64{2, 1, 0}, []uint64{0, 0, 0}, false, true}, + {"wrong accnums", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{7, 8, 9}, []uint64{0, 0, 0}, false, true}, + {"wrong sequences", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{3, 4, 5}, false, true}, + {"valid tx", []cryptotypes.PrivKey{priv1, priv2, priv3}, []uint64{0, 1, 2}, []uint64{0, 0, 0}, false, false}, + {"no err on recheck", []cryptotypes.PrivKey{}, []uint64{}, []uint64{}, true, false}, } for i, tc := range testCases { suite.ctx = suite.ctx.WithIsReCheckTx(tc.recheck) @@ -270,7 +269,7 @@ func (suite *AnteTestSuite) TestSigVerification_ExplicitAmino() { func (suite *AnteTestSuite) TestSigIntegration() { // generate private keys - privs := []crypto.PrivKey{ + privs := []cryptotypes.PrivKey{ secp256k1.GenPrivKey(), secp256k1.GenPrivKey(), secp256k1.GenPrivKey(), @@ -288,7 +287,7 @@ func (suite *AnteTestSuite) TestSigIntegration() { suite.Require().Equal(initialSigCost*uint64(len(privs)), doubleCost-initialCost) } -func (suite *AnteTestSuite) runSigDecorators(params types.Params, _ bool, privs ...crypto.PrivKey) (sdk.Gas, error) { +func (suite *AnteTestSuite) runSigDecorators(params types.Params, _ bool, privs ...cryptotypes.PrivKey) (sdk.Gas, error) { suite.SetupTest(true) // setup suite.txBuilder = suite.clientCtx.TxConfig.NewTxBuilder() @@ -343,7 +342,7 @@ func (suite *AnteTestSuite) TestIncrementSequenceDecorator() { msgs := []sdk.Msg{testdata.NewTestMsg(addr)} suite.Require().NoError(suite.txBuilder.SetMsgs(msgs...)) - privs := []crypto.PrivKey{priv} + privs := []cryptotypes.PrivKey{priv} accNums := []uint64{suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetAccountNumber()} accSeqs := []uint64{suite.app.AccountKeeper.GetAccount(suite.ctx, addr).GetSequence()} feeAmount := testdata.NewTestFeeAmount() diff --git a/x/auth/ante/testutil_test.go b/x/auth/ante/testutil_test.go index 9d8924eea765..5a1cfc4ec44c 100644 --- a/x/auth/ante/testutil_test.go +++ b/x/auth/ante/testutil_test.go @@ -6,11 +6,11 @@ import ( "testing" "github.com/stretchr/testify/suite" - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/tx" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -24,7 +24,7 @@ import ( // TestAccount represents an account used in the tests in x/auth/ante. type TestAccount struct { acc types.AccountI - priv crypto.PrivKey + priv cryptotypes.PrivKey } // AnteTestSuite is a test suite to be used with ante handler tests. @@ -86,7 +86,7 @@ func (suite *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { } // CreateTestTx is a helper function to create a tx given multiple inputs. -func (suite *AnteTestSuite) CreateTestTx(privs []crypto.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { +func (suite *AnteTestSuite) CreateTestTx(privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, error) { // First round: we gather all the signer infos. We use the "set empty // signature" hack to do that. var sigsV2 []signing.SignatureV2 @@ -142,7 +142,7 @@ type TestCase struct { } // CreateTestTx is a helper function to create a tx given multiple inputs. -func (suite *AnteTestSuite) RunTestCase(privs []crypto.PrivKey, msgs []sdk.Msg, feeAmount sdk.Coins, gasLimit uint64, accNums, accSeqs []uint64, chainID string, tc TestCase) { +func (suite *AnteTestSuite) RunTestCase(privs []cryptotypes.PrivKey, msgs []sdk.Msg, feeAmount sdk.Coins, gasLimit uint64, accNums, accSeqs []uint64, chainID string, tc TestCase) { suite.Run(fmt.Sprintf("Case %s", tc.desc), func() { suite.Require().NoError(suite.txBuilder.SetMsgs(msgs...)) suite.txBuilder.SetFeeAmount(feeAmount) diff --git a/x/auth/client/cli/cli_test.go b/x/auth/client/cli/cli_test.go index 4961e91c37fb..4ba383139c30 100644 --- a/x/auth/client/cli/cli_test.go +++ b/x/auth/client/cli/cli_test.go @@ -1,5 +1,3 @@ -// +build norace - package cli_test import ( @@ -12,7 +10,6 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - tmcrypto "github.com/tendermint/tendermint/crypto" tmcli "github.com/tendermint/tendermint/libs/cli" "github.com/cosmos/cosmos-sdk/client" @@ -22,6 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/crypto/keyring" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil" clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli" @@ -63,7 +61,7 @@ func (s *IntegrationTestSuite) SetupSuite() { account2, _, err := kb.NewMnemonic("newAccount2", keyring.English, sdk.FullFundraiserPath, hd.Secp256k1) s.Require().NoError(err) - multi := kmultisig.NewLegacyAminoPubKey(2, []tmcrypto.PubKey{account1.GetPubKey(), account2.GetPubKey()}) + multi := kmultisig.NewLegacyAminoPubKey(2, []cryptotypes.PubKey{account1.GetPubKey(), account2.GetPubKey()}) _, err = kb.SaveMultisig("multi", multi) s.Require().NoError(err) diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go index 86189b62a24d..75724f7d3c81 100644 --- a/x/auth/keeper/keeper.go +++ b/x/auth/keeper/keeper.go @@ -4,10 +4,10 @@ import ( "fmt" gogotypes "github.com/gogo/protobuf/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -35,7 +35,7 @@ type AccountKeeperI interface { IterateAccounts(sdk.Context, func(types.AccountI) bool) // Fetch the public key of an account at a specified address - GetPubKey(sdk.Context, sdk.AccAddress) (crypto.PubKey, error) + GetPubKey(sdk.Context, sdk.AccAddress) (cryptotypes.PubKey, error) // Fetch the sequence of an account at a specified address. GetSequence(sdk.Context, sdk.AccAddress) (uint64, error) @@ -90,7 +90,7 @@ func (ak AccountKeeper) Logger(ctx sdk.Context) log.Logger { } // GetPubKey Returns the PubKey of the account at address -func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, error) { +func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (cryptotypes.PubKey, error) { acc := ak.GetAccount(ctx, addr) if acc == nil { return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr) diff --git a/x/auth/legacy/legacytx/stdsign.go b/x/auth/legacy/legacytx/stdsign.go index 49792d3a211d..2ba194dad843 100644 --- a/x/auth/legacy/legacytx/stdsign.go +++ b/x/auth/legacy/legacytx/stdsign.go @@ -3,11 +3,10 @@ package legacytx import ( "encoding/json" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -57,8 +56,8 @@ func StdSignBytes(chainID string, accnum, sequence, timeout uint64, fee StdFee, // Deprecated: StdSignature represents a sig type StdSignature struct { - crypto.PubKey `json:"pub_key" yaml:"pub_key"` // optional - Signature []byte `json:"signature" yaml:"signature"` + cryptotypes.PubKey `json:"pub_key" yaml:"pub_key"` // optional + Signature []byte `json:"signature" yaml:"signature"` } // StdSignatureToSignatureV2 converts a StdSignature to a SignatureV2 @@ -75,7 +74,7 @@ func StdSignatureToSignatureV2(cdc *codec.LegacyAmino, sig StdSignature) (signin }, nil } -func pubKeySigToSigData(cdc *codec.LegacyAmino, key crypto.PubKey, sig []byte) (signing.SignatureData, error) { +func pubKeySigToSigData(cdc *codec.LegacyAmino, key cryptotypes.PubKey, sig []byte) (signing.SignatureData, error) { multiPK, ok := key.(multisig.PubKey) if !ok { return &signing.SingleSignatureData{ diff --git a/x/auth/legacy/legacytx/stdtx.go b/x/auth/legacy/legacytx/stdtx.go index 270a8d727a21..ba3215010ed6 100644 --- a/x/auth/legacy/legacytx/stdtx.go +++ b/x/auth/legacy/legacytx/stdtx.go @@ -3,11 +3,11 @@ package legacytx import ( "fmt" - "github.com/tendermint/tendermint/crypto" "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/codec/legacy" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -73,7 +73,7 @@ func (fee StdFee) GasPrices() sdk.DecCoins { } // Deprecated -func NewStdSignature(pk crypto.PubKey, sig []byte) StdSignature { +func NewStdSignature(pk cryptotypes.PubKey, sig []byte) StdSignature { return StdSignature{PubKey: pk, Signature: sig} } @@ -82,9 +82,9 @@ func (ss StdSignature) GetSignature() []byte { return ss.Signature } -// GetPubKey returns the public key of a signature as a crypto.PubKey using the +// GetPubKey returns the public key of a signature as a cryptotypes.PubKey using the // Amino codec. -func (ss StdSignature) GetPubKey() crypto.PubKey { +func (ss StdSignature) GetPubKey() cryptotypes.PubKey { return ss.PubKey } @@ -238,8 +238,8 @@ func (tx StdTx) GetSignaturesV2() ([]signing.SignatureV2, error) { // GetPubkeys returns the pubkeys of signers if the pubkey is included in the signature // If pubkey is not included in the signature, then nil is in the slice instead -func (tx StdTx) GetPubKeys() []crypto.PubKey { - pks := make([]crypto.PubKey, len(tx.Signatures)) +func (tx StdTx) GetPubKeys() []cryptotypes.PubKey { + pks := make([]cryptotypes.PubKey, len(tx.Signatures)) for i, stdSig := range tx.Signatures { pks[i] = stdSig.GetPubKey() diff --git a/x/auth/legacy/legacytx/stdtx_test.go b/x/auth/legacy/legacytx/stdtx_test.go index 96460f53820f..a702a82841d0 100644 --- a/x/auth/legacy/legacytx/stdtx_test.go +++ b/x/auth/legacy/legacytx/stdtx_test.go @@ -5,7 +5,6 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" yaml "gopkg.in/yaml.v2" @@ -15,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -39,7 +39,7 @@ func NewTestStdFee() StdFee { } // Deprecated, use TxBuilder. -func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []crypto.PrivKey, accNums []uint64, seqs []uint64, timeout uint64, fee StdFee) sdk.Tx { +func NewTestTx(ctx sdk.Context, msgs []sdk.Msg, privs []cryptotypes.PrivKey, accNums []uint64, seqs []uint64, timeout uint64, fee StdFee) sdk.Tx { sigs := make([]StdSignature, len(privs)) for i, priv := range privs { signBytes := StdSignBytes(ctx.ChainID(), accNums[i], seqs[i], timeout, fee, msgs, "") @@ -126,7 +126,7 @@ func TestTxValidateBasic(t *testing.T) { require.Equal(t, sdkerrors.ErrInsufficientFee.ABCICode(), code) // require to fail validation when no signatures exist - privs, accNums, seqs := []crypto.PrivKey{}, []uint64{}, []uint64{} + privs, accNums, seqs := []cryptotypes.PrivKey{}, []uint64{}, []uint64{} tx = NewTestTx(ctx, msgs, privs, accNums, seqs, 0, fee) err = tx.ValidateBasic() @@ -135,7 +135,7 @@ func TestTxValidateBasic(t *testing.T) { require.Equal(t, sdkerrors.ErrNoSignatures.ABCICode(), code) // require to fail validation when signatures do not match expected signers - privs, accNums, seqs = []crypto.PrivKey{priv1}, []uint64{0, 1}, []uint64{0, 0} + privs, accNums, seqs = []cryptotypes.PrivKey{priv1}, []uint64{0, 1}, []uint64{0, 0} tx = NewTestTx(ctx, msgs, privs, accNums, seqs, 0, fee) err = tx.ValidateBasic() @@ -154,7 +154,7 @@ func TestTxValidateBasic(t *testing.T) { require.Equal(t, sdkerrors.ErrInvalidRequest.ABCICode(), code) // require to pass when above criteria are matched - privs, accNums, seqs = []crypto.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} + privs, accNums, seqs = []cryptotypes.PrivKey{priv1, priv2}, []uint64{0, 1}, []uint64{0, 0} tx = NewTestTx(ctx, msgs, privs, accNums, seqs, 0, fee) err = tx.ValidateBasic() @@ -231,7 +231,7 @@ func TestSignatureV2Conversions(t *testing.T) { // multisigs _, pubKey2, _ := testdata.KeyTestPubAddr() - multiPK := kmultisig.NewLegacyAminoPubKey(1, []crypto.PubKey{ + multiPK := kmultisig.NewLegacyAminoPubKey(1, []cryptotypes.PubKey{ pubKey, pubKey2, }) dummy2 := []byte("dummySig2") diff --git a/x/auth/legacy/v038/types.go b/x/auth/legacy/v038/types.go index aeb554eeeab5..e9977c1d2966 100644 --- a/x/auth/legacy/v038/types.go +++ b/x/auth/legacy/v038/types.go @@ -11,9 +11,11 @@ import ( "sort" "strings" - "github.com/tendermint/tendermint/crypto" + tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/codec" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" v034auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v034" ) @@ -45,11 +47,11 @@ type ( } BaseAccount struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` - PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` - AccountNumber uint64 `json:"account_number" yaml:"account_number"` - Sequence uint64 `json:"sequence" yaml:"sequence"` + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` + PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` } baseAccountPretty struct { @@ -127,7 +129,7 @@ func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount { } func NewBaseAccount( - address sdk.AccAddress, coins sdk.Coins, pk crypto.PubKey, accountNumber, sequence uint64, + address sdk.AccAddress, coins sdk.Coins, pk cryptotypes.PubKey, accountNumber, sequence uint64, ) *BaseAccount { return &BaseAccount{ @@ -259,7 +261,7 @@ func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error { } var ( - pk crypto.PubKey + pk cryptotypes.PubKey err error ) @@ -328,7 +330,7 @@ func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error { } var ( - pk crypto.PubKey + pk cryptotypes.PubKey err error ) @@ -394,7 +396,7 @@ func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error { } var ( - pk crypto.PubKey + pk cryptotypes.PubKey err error ) @@ -417,7 +419,7 @@ func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error { } func NewModuleAddress(name string) sdk.AccAddress { - return sdk.AccAddress(crypto.AddressHash([]byte(name))) + return sdk.AccAddress(tmcrypto.AddressHash([]byte(name))) } func NewModuleAccount(baseAccount *BaseAccount, name string, permissions ...string) *ModuleAccount { @@ -437,7 +439,7 @@ func (ma ModuleAccount) Validate() error { return errors.New("module account name cannot be blank") } - if !ma.Address.Equals(sdk.AccAddress(crypto.AddressHash([]byte(ma.Name)))) { + if !ma.Address.Equals(sdk.AccAddress(tmcrypto.AddressHash([]byte(ma.Name)))) { return fmt.Errorf("address %s cannot be derived from the module name '%s'", ma.Address, ma.Name) } @@ -517,6 +519,7 @@ func ValidateGenAccounts(genAccounts GenesisAccounts) error { } func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cryptocodec.RegisterCrypto(cdc) cdc.RegisterInterface((*GenesisAccount)(nil), nil) cdc.RegisterInterface((*Account)(nil), nil) cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/Account", nil) diff --git a/x/auth/legacy/v039/migrate_test.go b/x/auth/legacy/v039/migrate_test.go new file mode 100644 index 000000000000..6972789c0099 --- /dev/null +++ b/x/auth/legacy/v039/migrate_test.go @@ -0,0 +1,104 @@ +package v039_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + sdk "github.com/cosmos/cosmos-sdk/types" + v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v038" + v039auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v039" +) + +func TestMigrate(t *testing.T) { + aminoCdc := codec.NewLegacyAmino() + v039auth.RegisterLegacyAminoCodec(aminoCdc) + + pub1 := ed25519.GenPrivKeyFromSecret([]byte("acc1")).PubKey() + pub2 := secp256k1.GenPrivKeyFromSecret([]byte("acc2")).PubKey() + + acc1 := v038auth.BaseAccount{ + Address: sdk.AccAddress(pub1.Address()), + Coins: sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)), + Sequence: 1, + AccountNumber: 1, + PubKey: pub1, + } + acc2 := v038auth.BaseAccount{ + Address: sdk.AccAddress(pub2.Address()), + Coins: sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)), + Sequence: 2, + AccountNumber: 2, + PubKey: pub2, + } + + migrated := v039auth.Migrate( + v038auth.GenesisState{ + Accounts: v038auth.GenesisAccounts{&acc1, &acc2}, + }, + ) + + expectedAcc1 := v039auth.NewBaseAccount(acc1.Address, acc1.Coins, acc1.PubKey, acc1.AccountNumber, acc1.Sequence) + expectedAcc2 := v039auth.NewBaseAccount(acc2.Address, acc2.Coins, acc2.PubKey, acc2.AccountNumber, acc2.Sequence) + + require.Equal( + t, migrated, v039auth.GenesisState{ + Accounts: v038auth.GenesisAccounts{expectedAcc1, expectedAcc2}, + }, + ) + + json, err := aminoCdc.MarshalJSONIndent(migrated, "", " ") + require.NoError(t, err) + + expectedJSON := `{ + "params": { + "max_memo_characters": "0", + "tx_sig_limit": "0", + "tx_size_cost_per_byte": "0", + "sig_verify_cost_ed25519": "0", + "sig_verify_cost_secp256k1": "0" + }, + "accounts": [ + { + "type": "cosmos-sdk/Account", + "value": { + "address": "cosmos1j7skdhh9raxdmfhmcy2gxz8hgn0jnhfmujjsfe", + "coins": [ + { + "denom": "stake", + "amount": "400000" + } + ], + "public_key": { + "type": "tendermint/PubKeyEd25519", + "value": "eB0AcLMLKFRNFfh4XAAMstexfAIUQQCDnfjLZ2KJg+A=" + }, + "account_number": "1", + "sequence": "1" + } + }, + { + "type": "cosmos-sdk/Account", + "value": { + "address": "cosmos1v57fx2l2rt6ehujuu99u2fw05779m5e2ux4z2h", + "coins": [ + { + "denom": "stake", + "amount": "400000" + } + ], + "public_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "AruDygh5HprMOpHOEato85dLgAsybMJVyxBGUa3KuWCr" + }, + "account_number": "2", + "sequence": "2" + } + } + ] +}` + require.Equal(t, expectedJSON, string(json)) +} diff --git a/x/auth/legacy/v039/types.go b/x/auth/legacy/v039/types.go index a75bc74a69ea..55c3014eb7f0 100644 --- a/x/auth/legacy/v039/types.go +++ b/x/auth/legacy/v039/types.go @@ -9,10 +9,12 @@ import ( "fmt" "strings" - "github.com/tendermint/tendermint/crypto" + tmcrypto "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/codec/legacy" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" v034auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v034" v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v038" @@ -29,11 +31,11 @@ type ( } BaseAccount struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` - PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` - AccountNumber uint64 `json:"account_number" yaml:"account_number"` - Sequence uint64 `json:"sequence" yaml:"sequence"` + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` + PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` } BaseVestingAccount struct { @@ -47,15 +49,15 @@ type ( } vestingAccountJSON struct { - Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"` - PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` - AccountNumber uint64 `json:"account_number" yaml:"account_number"` - Sequence uint64 `json:"sequence" yaml:"sequence"` - OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"` - DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"` - DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"` - EndTime int64 `json:"end_time" yaml:"end_time"` + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"` + PubKey cryptotypes.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` + OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"` + DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"` + DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"` + EndTime int64 `json:"end_time" yaml:"end_time"` // custom fields based on concrete vesting type which can be omitted StartTime int64 `json:"start_time,omitempty" yaml:"start_time,omitempty"` @@ -117,7 +119,7 @@ func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount { } func NewBaseAccount( - address sdk.AccAddress, coins sdk.Coins, pk crypto.PubKey, accountNumber, sequence uint64, + address sdk.AccAddress, coins sdk.Coins, pk cryptotypes.PubKey, accountNumber, sequence uint64, ) *BaseAccount { return &BaseAccount{ @@ -380,7 +382,7 @@ func (ma ModuleAccount) Validate() error { return errors.New("module account name cannot be blank") } - if x := sdk.AccAddress(crypto.AddressHash([]byte(ma.Name))); !ma.Address.Equals(x) { + if x := sdk.AccAddress(tmcrypto.AddressHash([]byte(ma.Name))); !ma.Address.Equals(x) { return fmt.Errorf("address %s cannot be derived from the module name '%s'; expected: %s", ma.Address, ma.Name, x) } @@ -415,6 +417,7 @@ func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error { } func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cryptocodec.RegisterCrypto(cdc) cdc.RegisterInterface((*v038auth.GenesisAccount)(nil), nil) cdc.RegisterInterface((*v038auth.Account)(nil), nil) cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/Account", nil) diff --git a/x/auth/signing/sig_verifiable_tx.go b/x/auth/signing/sig_verifiable_tx.go index 6621d3fcb085..8381ad491aa3 100644 --- a/x/auth/signing/sig_verifiable_tx.go +++ b/x/auth/signing/sig_verifiable_tx.go @@ -1,8 +1,7 @@ package signing import ( - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) @@ -12,7 +11,7 @@ import ( type SigVerifiableTx interface { types.Tx GetSigners() []types.AccAddress - GetPubKeys() []crypto.PubKey // If signer already has pubkey in context, this list will have nil in its place + GetPubKeys() []cryptotypes.PubKey // If signer already has pubkey in context, this list will have nil in its place GetSignaturesV2() ([]signing.SignatureV2, error) } diff --git a/x/auth/signing/verify.go b/x/auth/signing/verify.go index 0e66f026fa8f..5a5395de69f3 100644 --- a/x/auth/signing/verify.go +++ b/x/auth/signing/verify.go @@ -3,8 +3,7 @@ package signing import ( "fmt" - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -12,7 +11,7 @@ import ( // VerifySignature verifies a transaction signature contained in SignatureData abstracting over different signing modes // and single vs multi-signatures. -func VerifySignature(pubKey crypto.PubKey, signerData SignerData, sigData signing.SignatureData, handler SignModeHandler, tx sdk.Tx) error { +func VerifySignature(pubKey cryptotypes.PubKey, signerData SignerData, sigData signing.SignatureData, handler SignModeHandler, tx sdk.Tx) error { switch data := sigData.(type) { case *signing.SingleSignatureData: signBytes, err := handler.GetSignBytes(data.SignMode, signerData, tx) diff --git a/x/auth/signing/verify_test.go b/x/auth/signing/verify_test.go index f0929c76ccb6..7e842d13537c 100644 --- a/x/auth/signing/verify_test.go +++ b/x/auth/signing/verify_test.go @@ -4,11 +4,11 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil/testdata" @@ -65,7 +65,7 @@ func TestVerifySignature(t *testing.T) { err = signing.VerifySignature(pubKey, signerData, sigV2.Data, handler, stdTx) require.NoError(t, err) - pkSet := []crypto.PubKey{pubKey, pubKey1} + pkSet := []cryptotypes.PubKey{pubKey, pubKey1} multisigKey := kmultisig.NewLegacyAminoPubKey(2, pkSet) multisignature := multisig.NewMultisig(2) msgs = []sdk.Msg{testdata.NewTestMsg(addr, addr1)} diff --git a/x/auth/testutil/suite.go b/x/auth/testutil/suite.go index 518e502de1ca..f8002e68e4e6 100644 --- a/x/auth/testutil/suite.go +++ b/x/auth/testutil/suite.go @@ -4,10 +4,10 @@ import ( "bytes" "github.com/stretchr/testify/suite" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -81,7 +81,7 @@ func (s *TxConfigTestSuite) TestTxBuilderSetMsgs() { func (s *TxConfigTestSuite) TestTxBuilderSetSignatures() { privKey, pubkey, addr := testdata.KeyTestPubAddr() privKey2, pubkey2, _ := testdata.KeyTestPubAddr() - multisigPk := kmultisig.NewLegacyAminoPubKey(2, []crypto.PubKey{pubkey, pubkey2}) + multisigPk := kmultisig.NewLegacyAminoPubKey(2, []cryptotypes.PubKey{pubkey, pubkey2}) txBuilder := s.TxConfig.NewTxBuilder() @@ -268,7 +268,7 @@ func (s *TxConfigTestSuite) TestTxEncodeDecode() { tx3Sigs, err := tx3.GetSignaturesV2() s.Require().NoError(err) s.Require().Equal([]signingtypes.SignatureV2{sig}, tx3Sigs) - s.Require().Equal([]crypto.PubKey{pubkey}, tx3.GetPubKeys()) + s.Require().Equal([]cryptotypes.PubKey{pubkey}, tx3.GetPubKeys()) log("JSON encode transaction") jsonTxBytes, err := s.TxConfig.TxJSONEncoder()(tx) @@ -287,7 +287,7 @@ func (s *TxConfigTestSuite) TestTxEncodeDecode() { tx3Sigs, err = tx3.GetSignaturesV2() s.Require().NoError(err) s.Require().Equal([]signingtypes.SignatureV2{sig}, tx3Sigs) - s.Require().Equal([]crypto.PubKey{pubkey}, tx3.GetPubKeys()) + s.Require().Equal([]cryptotypes.PubKey{pubkey}, tx3.GetPubKeys()) } func (s *TxConfigTestSuite) TestWrapTxBuilder() { diff --git a/x/auth/tx/builder.go b/x/auth/tx/builder.go index b3697e70b262..4c76d529a9de 100644 --- a/x/auth/tx/builder.go +++ b/x/auth/tx/builder.go @@ -1,15 +1,12 @@ package tx import ( - "fmt" - "github.com/gogo/protobuf/proto" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/ante" @@ -103,9 +100,9 @@ func (w *wrapper) GetSigners() []sdk.AccAddress { return w.tx.GetSigners() } -func (w *wrapper) GetPubKeys() []crypto.PubKey { +func (w *wrapper) GetPubKeys() []cryptotypes.PubKey { signerInfos := w.tx.AuthInfo.SignerInfos - pks := make([]crypto.PubKey, len(signerInfos)) + pks := make([]cryptotypes.PubKey, len(signerInfos)) for i, si := range signerInfos { // NOTE: it is okay to leave this nil if there is no PubKey in the SignerInfo. @@ -114,7 +111,7 @@ func (w *wrapper) GetPubKeys() []crypto.PubKey { continue } - pk, ok := si.PublicKey.GetCachedValue().(crypto.PubKey) + pk, ok := si.PublicKey.GetCachedValue().(cryptotypes.PubKey) if ok { pks[i] = pk } @@ -366,11 +363,7 @@ func (w *wrapper) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) { w.bodyBz = nil } -// PubKeyToAny converts a crypto.PubKey to a proto Any. -func PubKeyToAny(key crypto.PubKey) (*codectypes.Any, error) { - protoMsg, ok := key.(proto.Message) - if !ok { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidPubKey, fmt.Sprintf("can't proto encode %T", protoMsg)) - } - return codectypes.NewAnyWithValue(protoMsg) +// PubKeyToAny converts a cryptotypes.PubKey to a proto Any. +func PubKeyToAny(key cryptotypes.PubKey) (*codectypes.Any, error) { + return codectypes.NewAnyWithValue(key) } diff --git a/x/auth/tx/sigs.go b/x/auth/tx/sigs.go index d0e43ede7526..b40935b4b82e 100644 --- a/x/auth/tx/sigs.go +++ b/x/auth/tx/sigs.go @@ -3,10 +3,8 @@ package tx import ( "fmt" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/types/tx" "github.com/cosmos/cosmos-sdk/types/tx/signing" ) @@ -33,7 +31,7 @@ func SignatureDataToModeInfoAndSig(data signing.SignatureData) (*tx.ModeInfo, [] modeInfos[i], sigs[i] = SignatureDataToModeInfoAndSig(d) } - multisig := types.MultiSignature{ + multisig := cryptotypes.MultiSignature{ Signatures: sigs, } sig, err := multisig.Marshal() @@ -92,7 +90,7 @@ func ModeInfoAndSigToSignatureData(modeInfo *tx.ModeInfo, sig []byte) (signing.S // decodeMultisignatures safely decodes the the raw bytes as a MultiSignature protobuf message func decodeMultisignatures(bz []byte) ([][]byte, error) { - multisig := types.MultiSignature{} + multisig := cryptotypes.MultiSignature{} err := multisig.Unmarshal(bz) if err != nil { return nil, err @@ -137,7 +135,7 @@ func (g config) UnmarshalSignatureJSON(bz []byte) ([]signing.SignatureV2, error) sigs := make([]signing.SignatureV2, len(sigDescs.Signatures)) for i, desc := range sigDescs.Signatures { - pubKey, _ := desc.PublicKey.GetCachedValue().(crypto.PubKey) + pubKey, _ := desc.PublicKey.GetCachedValue().(cryptotypes.PubKey) data := signing.SignatureDataFromProto(desc.Data) diff --git a/x/auth/types/account.go b/x/auth/types/account.go index 476e607c421c..532b80d3070d 100644 --- a/x/auth/types/account.go +++ b/x/auth/types/account.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -26,7 +27,7 @@ var ( // NewBaseAccount creates a new BaseAccount object //nolint:interfacer -func NewBaseAccount(address sdk.AccAddress, pubKey crypto.PubKey, accountNumber, sequence uint64) *BaseAccount { +func NewBaseAccount(address sdk.AccAddress, pubKey cryptotypes.PubKey, accountNumber, sequence uint64) *BaseAccount { acc := &BaseAccount{ Address: address.String(), AccountNumber: accountNumber, @@ -70,11 +71,11 @@ func (acc *BaseAccount) SetAddress(addr sdk.AccAddress) error { } // GetPubKey - Implements sdk.AccountI. -func (acc BaseAccount) GetPubKey() (pk crypto.PubKey) { +func (acc BaseAccount) GetPubKey() (pk cryptotypes.PubKey) { if acc.PubKey == nil { return nil } - content, ok := acc.PubKey.GetCachedValue().(crypto.PubKey) + content, ok := acc.PubKey.GetCachedValue().(cryptotypes.PubKey) if !ok { return nil } @@ -82,7 +83,7 @@ func (acc BaseAccount) GetPubKey() (pk crypto.PubKey) { } // SetPubKey - Implements sdk.AccountI. -func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error { +func (acc *BaseAccount) SetPubKey(pubKey cryptotypes.PubKey) error { any, err := codectypes.PackAny(pubKey) if err != nil { return err @@ -150,7 +151,7 @@ func (acc BaseAccount) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { if acc.PubKey == nil { return nil } - var pubKey crypto.PubKey + var pubKey cryptotypes.PubKey return unpacker.UnpackAny(acc.PubKey, &pubKey) } @@ -209,7 +210,7 @@ func (ma ModuleAccount) GetPermissions() []string { } // SetPubKey - Implements AccountI -func (ma ModuleAccount) SetPubKey(pubKey crypto.PubKey) error { +func (ma ModuleAccount) SetPubKey(pubKey cryptotypes.PubKey) error { return fmt.Errorf("not supported for module accounts") } @@ -311,8 +312,8 @@ type AccountI interface { GetAddress() sdk.AccAddress SetAddress(sdk.AccAddress) error // errors if already set. - GetPubKey() crypto.PubKey // can return nil. - SetPubKey(crypto.PubKey) error + GetPubKey() cryptotypes.PubKey // can return nil. + SetPubKey(cryptotypes.PubKey) error GetAccountNumber() uint64 SetAccountNumber(uint64) error diff --git a/x/auth/vesting/types/test_common.go b/x/auth/vesting/types/test_common.go index 347faba046a9..0e22ea2352dd 100644 --- a/x/auth/vesting/types/test_common.go +++ b/x/auth/vesting/types/test_common.go @@ -1,9 +1,8 @@ package types import ( - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -22,7 +21,7 @@ func NewTestCoins() sdk.Coins { } // KeyTestPubAddr generates a test key pair -func KeyTestPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { +func KeyTestPubAddr() (cryptotypes.PrivKey, cryptotypes.PubKey, sdk.AccAddress) { key := secp256k1.GenPrivKey() pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) diff --git a/x/bank/app_test.go b/x/bank/app_test.go index 713aa0999b77..82d898b09088 100644 --- a/x/bank/app_test.go +++ b/x/bank/app_test.go @@ -4,10 +4,10 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -28,7 +28,7 @@ type ( msgs []sdk.Msg accNums []uint64 accSeqs []uint64 - privKeys []crypto.PrivKey + privKeys []cryptotypes.PrivKey expectedBalances []expectedBalance } ) @@ -228,7 +228,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { accSeqs: []uint64{0}, expSimPass: true, expPass: true, - privKeys: []crypto.PrivKey{priv1}, + privKeys: []cryptotypes.PrivKey{priv1}, expectedBalances: []expectedBalance{ {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 57)}}, {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}}, @@ -241,7 +241,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { accSeqs: []uint64{1}, expSimPass: true, // doesn't check signature expPass: false, - privKeys: []crypto.PrivKey{priv1}, + privKeys: []cryptotypes.PrivKey{priv1}, }, { desc: "wrong accSeq should not pass Simulate", @@ -250,7 +250,7 @@ func TestMsgMultiSendWithAccounts(t *testing.T) { accSeqs: []uint64{0}, // wrong account sequence expSimPass: false, expPass: false, - privKeys: []crypto.PrivKey{priv1}, + privKeys: []cryptotypes.PrivKey{priv1}, }, } @@ -297,7 +297,7 @@ func TestMsgMultiSendMultipleOut(t *testing.T) { accSeqs: []uint64{0}, expSimPass: true, expPass: true, - privKeys: []crypto.PrivKey{priv1}, + privKeys: []cryptotypes.PrivKey{priv1}, expectedBalances: []expectedBalance{ {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 47)}}, @@ -351,7 +351,7 @@ func TestMsgMultiSendMultipleInOut(t *testing.T) { accSeqs: []uint64{0, 0}, expSimPass: true, expPass: true, - privKeys: []crypto.PrivKey{priv1, priv4}, + privKeys: []cryptotypes.PrivKey{priv1, priv4}, expectedBalances: []expectedBalance{ {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, {addr4, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, @@ -395,7 +395,7 @@ func TestMsgMultiSendDependent(t *testing.T) { accSeqs: []uint64{0}, expSimPass: true, expPass: true, - privKeys: []crypto.PrivKey{priv1}, + privKeys: []cryptotypes.PrivKey{priv1}, expectedBalances: []expectedBalance{ {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 32)}}, {addr2, sdk.Coins{sdk.NewInt64Coin("foocoin", 10)}}, @@ -407,7 +407,7 @@ func TestMsgMultiSendDependent(t *testing.T) { accSeqs: []uint64{0}, expSimPass: true, expPass: true, - privKeys: []crypto.PrivKey{priv2}, + privKeys: []cryptotypes.PrivKey{priv2}, expectedBalances: []expectedBalance{ {addr1, sdk.Coins{sdk.NewInt64Coin("foocoin", 42)}}, }, diff --git a/x/bank/simulation/operations.go b/x/bank/simulation/operations.go index c1e64d80d58e..9fcc80f0fe45 100644 --- a/x/bank/simulation/operations.go +++ b/x/bank/simulation/operations.go @@ -3,10 +3,9 @@ package simulation import ( "math/rand" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp/helpers" simappparams "github.com/cosmos/cosmos-sdk/simapp/params" sdk "github.com/cosmos/cosmos-sdk/types" @@ -72,7 +71,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio msg := types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins) - err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey}) + err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []cryptotypes.PrivKey{simAccount.PrivKey}) if err != nil { return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "invalid transfers"), nil, err } @@ -85,7 +84,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio // nolint: interfacer func sendMsgSend( r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, - msg *types.MsgSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, + msg *types.MsgSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { var ( @@ -144,7 +143,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope outputs := make([]types.Output, r.Intn(3)+1) // collect signer privKeys - privs := make([]crypto.PrivKey, len(inputs)) + privs := make([]cryptotypes.PrivKey, len(inputs)) // use map to check if address already exists as input usedAddrs := make(map[string]bool) @@ -227,7 +226,7 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope // nolint: interfacer func sendMsgMultiSend( r *rand.Rand, app *baseapp.BaseApp, bk keeper.Keeper, ak types.AccountKeeper, - msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []crypto.PrivKey, + msg *types.MsgMultiSend, ctx sdk.Context, chainID string, privkeys []cryptotypes.PrivKey, ) error { accountNumbers := make([]uint64, len(msg.Inputs)) diff --git a/x/distribution/types/common_test.go b/x/distribution/types/common_test.go index a8301b4e42bd..4e6ef6b01231 100644 --- a/x/distribution/types/common_test.go +++ b/x/distribution/types/common_test.go @@ -1,9 +1,8 @@ package types import ( - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -25,5 +24,5 @@ var ( valAddr3 = sdk.ValAddress(valPk3.Address()) emptyValAddr sdk.ValAddress - emptyPubkey crypto.PubKey + emptyPubkey cryptotypes.PubKey ) diff --git a/x/evidence/keeper/keeper_test.go b/x/evidence/keeper/keeper_test.go index 65e52b30ed1d..9165730466b7 100644 --- a/x/evidence/keeper/keeper_test.go +++ b/x/evidence/keeper/keeper_test.go @@ -6,11 +6,11 @@ import ( "time" "github.com/stretchr/testify/suite" - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" @@ -22,7 +22,7 @@ import ( ) var ( - pubkeys = []crypto.PubKey{ + pubkeys = []cryptotypes.PubKey{ newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB50"), newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB51"), newPubKey("0B485CFC0EECC619440448436F8FC9DF40566F2369E72400281454CB552AFB52"), @@ -38,7 +38,7 @@ var ( initCoins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initAmt)) ) -func newPubKey(pk string) (res crypto.PubKey) { +func newPubKey(pk string) (res cryptotypes.PubKey) { pkBytes, err := hex.DecodeString(pk) if err != nil { panic(err) diff --git a/x/evidence/types/expected_keepers.go b/x/evidence/types/expected_keepers.go index 23c9b40bdc62..0f1d87774c6c 100644 --- a/x/evidence/types/expected_keepers.go +++ b/x/evidence/types/expected_keepers.go @@ -3,8 +3,7 @@ package types import ( "time" - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -19,7 +18,7 @@ type ( // SlashingKeeper defines the slashing module interface contract needed by the // evidence module. SlashingKeeper interface { - GetPubkey(sdk.Context, crypto.Address) (crypto.PubKey, error) + GetPubkey(sdk.Context, cryptotypes.Address) (cryptotypes.PubKey, error) IsTombstoned(sdk.Context, sdk.ConsAddress) bool HasValidatorSigningInfo(sdk.Context, sdk.ConsAddress) bool Tombstone(sdk.Context, sdk.ConsAddress) diff --git a/x/genutil/legacy/v038/migrate.go b/x/genutil/legacy/v038/migrate.go index cd71f57b1129..374092298a7c 100644 --- a/x/genutil/legacy/v038/migrate.go +++ b/x/genutil/legacy/v038/migrate.go @@ -3,7 +3,6 @@ package v038 import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" v036auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v036" v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v038" v036distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v036" @@ -18,12 +17,10 @@ import ( // Migrate migrates exported state from v0.36/v0.37 to a v0.38 genesis state. func Migrate(appState types.AppMap, _ client.Context) types.AppMap { v036Codec := codec.NewLegacyAmino() - cryptocodec.RegisterCrypto(v036Codec) v036gov.RegisterLegacyAminoCodec(v036Codec) v036distr.RegisterLegacyAminoCodec(v036Codec) v038Codec := codec.NewLegacyAmino() - cryptocodec.RegisterCrypto(v038Codec) v038auth.RegisterLegacyAminoCodec(v038Codec) v036gov.RegisterLegacyAminoCodec(v038Codec) v036distr.RegisterLegacyAminoCodec(v038Codec) diff --git a/x/genutil/legacy/v039/migrate.go b/x/genutil/legacy/v039/migrate.go index bf112c1526b9..97442e93809c 100644 --- a/x/genutil/legacy/v039/migrate.go +++ b/x/genutil/legacy/v039/migrate.go @@ -3,7 +3,6 @@ package v039 import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v038" v039auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v039" v036distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v036" @@ -17,13 +16,11 @@ import ( // serialization of accounts do change. func Migrate(appState types.AppMap, _ client.Context) types.AppMap { v038Codec := codec.NewLegacyAmino() - cryptocodec.RegisterCrypto(v038Codec) v038auth.RegisterLegacyAminoCodec(v038Codec) v036gov.RegisterLegacyAminoCodec(v038Codec) v036distr.RegisterLegacyAminoCodec(v038Codec) v039Codec := codec.NewLegacyAmino() - cryptocodec.RegisterCrypto(v039Codec) v039auth.RegisterLegacyAminoCodec(v039Codec) v036gov.RegisterLegacyAminoCodec(v039Codec) v036distr.RegisterLegacyAminoCodec(v039Codec) diff --git a/x/genutil/types/types.go b/x/genutil/types/types.go index d902d8ccb3a5..694eebdbe3bb 100644 --- a/x/genutil/types/types.go +++ b/x/genutil/types/types.go @@ -3,9 +3,8 @@ package types import ( "encoding/json" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/client" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) // DONTCOVER @@ -32,11 +31,11 @@ type InitConfig struct { ChainID string GenTxsDir string NodeID string - ValPubKey crypto.PubKey + ValPubKey cryptotypes.PubKey } // NewInitConfig creates a new InitConfig object -func NewInitConfig(chainID, genTxsDir, nodeID string, valPubKey crypto.PubKey) InitConfig { +func NewInitConfig(chainID, genTxsDir, nodeID string, valPubKey cryptotypes.PubKey) InitConfig { return InitConfig{ ChainID: chainID, GenTxsDir: genTxsDir, diff --git a/x/genutil/utils.go b/x/genutil/utils.go index 5eea11718793..14ac11f533ac 100644 --- a/x/genutil/utils.go +++ b/x/genutil/utils.go @@ -6,13 +6,13 @@ import ( "time" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" tmos "github.com/tendermint/tendermint/libs/os" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/privval" tmtypes "github.com/tendermint/tendermint/types" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) // ExportGenesisFile creates and writes the genesis configuration to disk. An @@ -47,7 +47,7 @@ func ExportGenesisFileWithTime( } // InitializeNodeValidatorFiles creates private validator and p2p configuration files. -func InitializeNodeValidatorFiles(config *cfg.Config) (nodeID string, valPubKey crypto.PubKey, err error) { +func InitializeNodeValidatorFiles(config *cfg.Config) (nodeID string, valPubKey cryptotypes.PubKey, err error) { nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile()) if err != nil { return "", nil, err @@ -70,7 +70,7 @@ func InitializeNodeValidatorFiles(config *cfg.Config) (nodeID string, valPubKey return "", nil, err } - valPubKey, err = ed25519.FromTmEd25519(tmValPubKey) + valPubKey, err = cryptocodec.FromTmPubKeyInterface(tmValPubKey) if err != nil { return "", nil, err } diff --git a/x/gov/common_test.go b/x/gov/common_test.go index d8648b478adb..5ef50ea5db03 100644 --- a/x/gov/common_test.go +++ b/x/gov/common_test.go @@ -7,9 +7,9 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/gov/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -71,7 +71,7 @@ func SortByteArrays(src [][]byte) [][]byte { const contextKeyBadProposal = "contextKeyBadProposal" var ( - pubkeys = []crypto.PubKey{ + pubkeys = []cryptotypes.PubKey{ ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey(), ed25519.GenPrivKey().PubKey(), diff --git a/x/gov/keeper/tally_test.go b/x/gov/keeper/tally_test.go index 6c23a510e9b0..77f468cd2c0b 100644 --- a/x/gov/keeper/tally_test.go +++ b/x/gov/keeper/tally_test.go @@ -410,9 +410,9 @@ func TestTallyJailedValidator(t *testing.T) { _ = staking.EndBlocker(ctx, app.StakingKeeper) - consKey, err := val2.TmConsPubKey() + consAddr, err := val2.GetConsAddr() require.NoError(t, err) - app.StakingKeeper.Jail(ctx, sdk.ConsAddress(consKey.Address())) + app.StakingKeeper.Jail(ctx, sdk.ConsAddress(consAddr.Bytes())) tp := TestProposal proposal, err := app.GovKeeper.SubmitProposal(ctx, tp) diff --git a/x/ibc/core/02-client/keeper/client_test.go b/x/ibc/core/02-client/keeper/client_test.go index 31cf5d80fe4d..30528b88ca7a 100644 --- a/x/ibc/core/02-client/keeper/client_test.go +++ b/x/ibc/core/02-client/keeper/client_test.go @@ -6,7 +6,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types" @@ -379,7 +378,7 @@ func (suite *KeeperTestSuite) TestCheckMisbehaviourAndUpdateState() { altPrivVal := ibctestingmock.NewPV() altPubKey, err := altPrivVal.GetPubKey() suite.Require().NoError(err) - altVal := tmtypes.NewValidator(altPubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 4) + altVal := tmtypes.NewValidator(altPubKey, 4) // Set valSet here with suite.valSet so it doesn't get reset on each testcase valSet := suite.valSet diff --git a/x/ibc/core/02-client/keeper/keeper_test.go b/x/ibc/core/02-client/keeper/keeper_test.go index 24675f4e9adc..d5e162b09ec9 100644 --- a/x/ibc/core/02-client/keeper/keeper_test.go +++ b/x/ibc/core/02-client/keeper/keeper_test.go @@ -12,7 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/keeper" @@ -91,7 +91,7 @@ func (suite *KeeperTestSuite) SetupTest() { testClientHeightMinus1 := types.NewHeight(0, height-1) - validator := tmtypes.NewValidator(pubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 1) + validator := tmtypes.NewValidator(pubKey, 1) suite.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) suite.valSetHash = suite.valSet.Hash() suite.header = suite.chainA.CreateTMClientHeader(testChainID, int64(testClientHeight.VersionHeight), testClientHeightMinus1, now2, suite.valSet, suite.valSet, []tmtypes.PrivValidator{suite.privVal}) @@ -100,7 +100,9 @@ func (suite *KeeperTestSuite) SetupTest() { var validators stakingtypes.Validators for i := 1; i < 11; i++ { privVal := ibctestingmock.NewPV() - pk, err := privVal.GetPubKey() + tmPk, err := privVal.GetPubKey() + suite.Require().NoError(err) + pk, err := cryptocodec.FromTmPubKeyInterface(tmPk) suite.Require().NoError(err) val, err := stakingtypes.NewValidator(sdk.ValAddress(pk.Address()), pk, stakingtypes.Description{}) suite.Require().NoError(err) diff --git a/x/ibc/core/02-client/types/genesis_test.go b/x/ibc/core/02-client/types/genesis_test.go index 1de91033549f..41d88edae897 100644 --- a/x/ibc/core/02-client/types/genesis_test.go +++ b/x/ibc/core/02-client/types/genesis_test.go @@ -5,7 +5,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" client "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client" "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types" @@ -49,7 +48,7 @@ func (suite *TypesTestSuite) TestValidateGenesis() { now := time.Now().UTC() - val := tmtypes.NewValidator(pubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 10) + val := tmtypes.NewValidator(pubKey, 10) valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{val}) heightMinus1 := types.NewHeight(0, height-1) diff --git a/x/ibc/light-clients/06-solomachine/types/consensus_state.go b/x/ibc/light-clients/06-solomachine/types/consensus_state.go index f912aa3501fd..2b637a7ad21e 100644 --- a/x/ibc/light-clients/06-solomachine/types/consensus_state.go +++ b/x/ibc/light-clients/06-solomachine/types/consensus_state.go @@ -3,8 +3,7 @@ package types import ( "strings" - tmcrypto "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" @@ -27,11 +26,11 @@ func (cs ConsensusState) GetRoot() exported.Root { return nil } -// GetPubKey unmarshals the public key into a tmcrypto.PubKey type. -func (cs ConsensusState) GetPubKey() tmcrypto.PubKey { - publicKey, ok := cs.PublicKey.GetCachedValue().(tmcrypto.PubKey) +// GetPubKey unmarshals the public key into a cryptotypes.PubKey type. +func (cs ConsensusState) GetPubKey() cryptotypes.PubKey { + publicKey, ok := cs.PublicKey.GetCachedValue().(cryptotypes.PubKey) if !ok { - panic("ConsensusState PublicKey is not crypto.PubKey") + panic("ConsensusState PublicKey is not cryptotypes.PubKey") } return publicKey diff --git a/x/ibc/light-clients/06-solomachine/types/header.go b/x/ibc/light-clients/06-solomachine/types/header.go index a4f757a37349..e833a702027b 100644 --- a/x/ibc/light-clients/06-solomachine/types/header.go +++ b/x/ibc/light-clients/06-solomachine/types/header.go @@ -3,8 +3,7 @@ package types import ( "strings" - tmcrypto "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" @@ -24,11 +23,11 @@ func (h Header) GetHeight() exported.Height { return clienttypes.NewHeight(0, h.Sequence) } -// GetPubKey unmarshals the new public key into a tmcrypto.PubKey type. -func (h Header) GetPubKey() tmcrypto.PubKey { - publicKey, ok := h.NewPublicKey.GetCachedValue().(tmcrypto.PubKey) +// GetPubKey unmarshals the new public key into a cryptotypes.PubKey type. +func (h Header) GetPubKey() cryptotypes.PubKey { + publicKey, ok := h.NewPublicKey.GetCachedValue().(cryptotypes.PubKey) if !ok { - panic("Header NewPublicKey is not crypto.PubKey") + panic("Header NewPublicKey is not cryptotypes.PubKey") } return publicKey diff --git a/x/ibc/light-clients/06-solomachine/types/proof.go b/x/ibc/light-clients/06-solomachine/types/proof.go index 7a5204e7f742..c6f4c8b48f75 100644 --- a/x/ibc/light-clients/06-solomachine/types/proof.go +++ b/x/ibc/light-clients/06-solomachine/types/proof.go @@ -1,9 +1,8 @@ package types import ( - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/cosmos/cosmos-sdk/types/tx/signing" @@ -19,7 +18,7 @@ import ( // The type of the signature data determines how the public key is used to // verify the signature. An error is returned if signature verification fails // or an invalid SignatureData type is provided. -func VerifySignature(pubKey crypto.PubKey, signBytes []byte, sigData signing.SignatureData) error { +func VerifySignature(pubKey cryptotypes.PubKey, signBytes []byte, sigData signing.SignatureData) error { switch data := sigData.(type) { case *signing.SingleSignatureData: if !pubKey.VerifySignature(signBytes, data.Signature) { diff --git a/x/ibc/light-clients/06-solomachine/types/solomachine.go b/x/ibc/light-clients/06-solomachine/types/solomachine.go index 06d8fc05f6af..d3936ef42747 100644 --- a/x/ibc/light-clients/06-solomachine/types/solomachine.go +++ b/x/ibc/light-clients/06-solomachine/types/solomachine.go @@ -1,9 +1,8 @@ package types import ( - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/x/ibc/core/exported" ) @@ -20,17 +19,17 @@ func (cs ClientState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method func (cs ConsensusState) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return unpacker.UnpackAny(cs.PublicKey, new(crypto.PubKey)) + return unpacker.UnpackAny(cs.PublicKey, new(cryptotypes.PubKey)) } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method func (h Header) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return unpacker.UnpackAny(h.NewPublicKey, new(crypto.PubKey)) + return unpacker.UnpackAny(h.NewPublicKey, new(cryptotypes.PubKey)) } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method func (hd HeaderData) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - return unpacker.UnpackAny(hd.NewPubKey, new(crypto.PubKey)) + return unpacker.UnpackAny(hd.NewPubKey, new(cryptotypes.PubKey)) } // UnpackInterfaces implements the UnpackInterfaceMessages.UnpackInterfaces method diff --git a/x/ibc/light-clients/07-tendermint/types/misbehaviour_handle_test.go b/x/ibc/light-clients/07-tendermint/types/misbehaviour_handle_test.go index 21336118603a..e0fc26389c54 100644 --- a/x/ibc/light-clients/07-tendermint/types/misbehaviour_handle_test.go +++ b/x/ibc/light-clients/07-tendermint/types/misbehaviour_handle_test.go @@ -7,7 +7,6 @@ import ( "github.com/tendermint/tendermint/crypto/tmhash" tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types" @@ -22,7 +21,7 @@ func (suite *TendermintTestSuite) TestCheckMisbehaviourAndUpdateState() { altPubKey, err := altPrivVal.GetPubKey() suite.Require().NoError(err) - altVal := tmtypes.NewValidator(altPubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 4) + altVal := tmtypes.NewValidator(altPubKey, 4) // Create bothValSet with both suite validator and altVal bothValSet := tmtypes.NewValidatorSet(append(suite.valSet.Validators, altVal)) diff --git a/x/ibc/light-clients/07-tendermint/types/misbehaviour_test.go b/x/ibc/light-clients/07-tendermint/types/misbehaviour_test.go index 22bd8674fb8e..6f70c4b716eb 100644 --- a/x/ibc/light-clients/07-tendermint/types/misbehaviour_test.go +++ b/x/ibc/light-clients/07-tendermint/types/misbehaviour_test.go @@ -7,7 +7,6 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types" ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" @@ -37,7 +36,7 @@ func (suite *TendermintTestSuite) TestMisbehaviourValidateBasic() { versionHeight := int64(height.VersionHeight) - altVal := tmtypes.NewValidator(altPubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), versionHeight) + altVal := tmtypes.NewValidator(altPubKey, versionHeight) // Create bothValSet with both suite validator and altVal bothValSet := tmtypes.NewValidatorSet(append(suite.valSet.Validators, altVal)) diff --git a/x/ibc/light-clients/07-tendermint/types/tendermint_test.go b/x/ibc/light-clients/07-tendermint/types/tendermint_test.go index b175bfd5a588..171d33f561ef 100644 --- a/x/ibc/light-clients/07-tendermint/types/tendermint_test.go +++ b/x/ibc/light-clients/07-tendermint/types/tendermint_test.go @@ -11,7 +11,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/codec" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" @@ -82,7 +81,7 @@ func (suite *TendermintTestSuite) SetupTest() { heightMinus1 := clienttypes.NewHeight(0, height.VersionHeight-1) - val := tmtypes.NewValidator(pubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 10) + val := tmtypes.NewValidator(pubKey, 10) suite.valSet = tmtypes.NewValidatorSet([]*tmtypes.Validator{val}) suite.valsHash = suite.valSet.Hash() suite.header = suite.chainA.CreateTMClientHeader(chainID, int64(height.VersionHeight), heightMinus1, suite.now, suite.valSet, suite.valSet, []tmtypes.PrivValidator{suite.privVal}) diff --git a/x/ibc/light-clients/07-tendermint/types/update_test.go b/x/ibc/light-clients/07-tendermint/types/update_test.go index 2d075ad0a5cf..0941e632124b 100644 --- a/x/ibc/light-clients/07-tendermint/types/update_test.go +++ b/x/ibc/light-clients/07-tendermint/types/update_test.go @@ -5,7 +5,6 @@ import ( tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types" types "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types" @@ -35,7 +34,7 @@ func (suite *TendermintTestSuite) TestCheckHeaderAndUpdateState() { heightMinus3 := clienttypes.NewHeight(height.VersionNumber, height.VersionHeight-3) heightPlus5 := clienttypes.NewHeight(height.VersionNumber, height.VersionHeight+5) - altVal := tmtypes.NewValidator(altPubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), versionHeight) + altVal := tmtypes.NewValidator(altPubKey, versionHeight) // Create bothValSet with both suite validator and altVal. Would be valid update bothValSet := tmtypes.NewValidatorSet(append(suite.valSet.Validators, altVal)) diff --git a/x/ibc/testing/chain.go b/x/ibc/testing/chain.go index 2c0554c6aa3b..c29c111e8f0a 100644 --- a/x/ibc/testing/chain.go +++ b/x/ibc/testing/chain.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/tmhash" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmprotoversion "github.com/tendermint/tendermint/proto/tendermint/version" @@ -37,6 +36,7 @@ import ( solomachinetypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/06-solomachine/types" ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types" "github.com/cosmos/cosmos-sdk/x/ibc/testing/mock" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -109,7 +109,7 @@ type TestChain struct { Vals *tmtypes.ValidatorSet Signers []tmtypes.PrivValidator - senderPrivKey crypto.PrivKey + senderPrivKey cryptotypes.PrivKey SenderAccount authtypes.AccountI // IBC specific helpers @@ -132,7 +132,7 @@ func NewTestChain(t *testing.T, chainID string) *TestChain { require.NoError(t, err) // create validator set with single validator - validator := tmtypes.NewValidator(pubKey.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 1) + validator := tmtypes.NewValidator(pubKey, 1) valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) signers := []tmtypes.PrivValidator{privVal} @@ -346,7 +346,7 @@ func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bo valSet := stakingtypes.Validators(histInfo.Valset) - tmValidators, err := valSet.ToTmValidators() + tmValidators, err := teststaking.ToTmValidators(valSet) if err != nil { panic(err) } diff --git a/x/ibc/testing/chain_test.go b/x/ibc/testing/chain_test.go index 243eb064479e..bf5af6de6367 100644 --- a/x/ibc/testing/chain_test.go +++ b/x/ibc/testing/chain_test.go @@ -6,7 +6,6 @@ import ( "github.com/stretchr/testify/require" tmtypes "github.com/tendermint/tendermint/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing" "github.com/cosmos/cosmos-sdk/x/ibc/testing/mock" ) @@ -20,8 +19,8 @@ func TestCreateSortedSignerArray(t *testing.T) { pubKey2, err := privVal2.GetPubKey() require.NoError(t, err) - validator1 := tmtypes.NewValidator(pubKey1.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 1) - validator2 := tmtypes.NewValidator(pubKey2.(cryptotypes.IntoTmPubKey).AsTmPubKey(), 2) + validator1 := tmtypes.NewValidator(pubKey1, 1) + validator2 := tmtypes.NewValidator(pubKey2, 2) expected := []tmtypes.PrivValidator{privVal2, privVal1} diff --git a/x/ibc/testing/mock/privval.go b/x/ibc/testing/mock/privval.go index ec40a8aad6ba..fe46659b3df9 100644 --- a/x/ibc/testing/mock/privval.go +++ b/x/ibc/testing/mock/privval.go @@ -5,7 +5,9 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" ) var _ tmtypes.PrivValidator = PV{} @@ -13,7 +15,7 @@ var _ tmtypes.PrivValidator = PV{} // MockPV implements PrivValidator without any safety or persistence. // Only use it for testing. type PV struct { - PrivKey crypto.PrivKey + PrivKey cryptotypes.PrivKey } func NewPV() PV { @@ -22,7 +24,7 @@ func NewPV() PV { // GetPubKey implements PrivValidator interface func (pv PV) GetPubKey() (crypto.PubKey, error) { - return pv.PrivKey.PubKey(), nil + return cryptocodec.ToTmPubKeyInterface(pv.PrivKey.PubKey()) } // SignVote implements PrivValidator interface diff --git a/x/ibc/testing/solomachine.go b/x/ibc/testing/solomachine.go index 21b02516e9e2..6b2508f30e1f 100644 --- a/x/ibc/testing/solomachine.go +++ b/x/ibc/testing/solomachine.go @@ -4,11 +4,11 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/codec" kmultisig "github.com/cosmos/cosmos-sdk/crypto/keys/multisig" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/crypto/types/multisig" "github.com/cosmos/cosmos-sdk/types/tx/signing" "github.com/cosmos/cosmos-sdk/x/auth/tx" @@ -28,9 +28,9 @@ type Solomachine struct { cdc codec.BinaryMarshaler ClientID string - PrivateKeys []crypto.PrivKey // keys used for signing - PublicKeys []crypto.PubKey // keys used for generating solo machine pub key - PublicKey crypto.PubKey // key used for verification + PrivateKeys []cryptotypes.PrivKey // keys used for signing + PublicKeys []cryptotypes.PubKey // keys used for generating solo machine pub key + PublicKey cryptotypes.PubKey // key used for verification Sequence uint64 Time uint64 Diversifier string @@ -63,17 +63,17 @@ func NewSolomachine(t *testing.T, cdc codec.BinaryMarshaler, clientID, diversifi // The key type can be swapped for any key type supported by the PublicKey // interface, if needed. The same is true for the amino based Multisignature // public key. -func GenerateKeys(t *testing.T, n uint64) ([]crypto.PrivKey, []crypto.PubKey, crypto.PubKey) { +func GenerateKeys(t *testing.T, n uint64) ([]cryptotypes.PrivKey, []cryptotypes.PubKey, cryptotypes.PubKey) { require.NotEqual(t, uint64(0), n, "generation of zero keys is not allowed") - privKeys := make([]crypto.PrivKey, n) - pubKeys := make([]crypto.PubKey, n) + privKeys := make([]cryptotypes.PrivKey, n) + pubKeys := make([]cryptotypes.PubKey, n) for i := uint64(0); i < n; i++ { privKeys[i] = secp256k1.GenPrivKey() pubKeys[i] = privKeys[i].PubKey() } - var pk crypto.PubKey + var pk cryptotypes.PubKey if len(privKeys) > 1 { // generate multi sig pk pk = kmultisig.NewLegacyAminoPubKey(int(n), pubKeys) diff --git a/x/slashing/genesis.go b/x/slashing/genesis.go index ae8f3155533a..2c8b6675762b 100644 --- a/x/slashing/genesis.go +++ b/x/slashing/genesis.go @@ -12,7 +12,7 @@ import ( func InitGenesis(ctx sdk.Context, keeper keeper.Keeper, stakingKeeper types.StakingKeeper, data *types.GenesisState) { stakingKeeper.IterateValidators(ctx, func(index int64, validator stakingtypes.ValidatorI) bool { - consPk, err := validator.TmConsPubKey() + consPk, err := validator.ConsPubKey() if err != nil { panic(err) } diff --git a/x/slashing/keeper/hooks.go b/x/slashing/keeper/hooks.go index daf2e051e1d7..d59601425842 100644 --- a/x/slashing/keeper/hooks.go +++ b/x/slashing/keeper/hooks.go @@ -28,11 +28,12 @@ func (k Keeper) AfterValidatorBonded(ctx sdk.Context, address sdk.ConsAddress, _ // AfterValidatorCreated adds the address-pubkey relation when a validator is created. func (k Keeper) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error { validator := k.sk.Validator(ctx, valAddr) - consPk, err := validator.TmConsPubKey() + consPk, err := validator.ConsPubKey() if err != nil { return err } k.AddPubkey(ctx, consPk) + return nil } diff --git a/x/slashing/keeper/infractions.go b/x/slashing/keeper/infractions.go index a8e349b75be8..168b97b235b9 100644 --- a/x/slashing/keeper/infractions.go +++ b/x/slashing/keeper/infractions.go @@ -3,14 +3,13 @@ package keeper import ( "fmt" - "github.com/tendermint/tendermint/crypto" - + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) // HandleValidatorSignature handles a validator signature, must be called once per validator per block. -func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr crypto.Address, power int64, signed bool) { +func (k Keeper) HandleValidatorSignature(ctx sdk.Context, addr cryptotypes.Address, power int64, signed bool) { logger := k.Logger(ctx) height := ctx.BlockHeight() diff --git a/x/slashing/keeper/keeper.go b/x/slashing/keeper/keeper.go index ee46915b745b..999e82404bda 100644 --- a/x/slashing/keeper/keeper.go +++ b/x/slashing/keeper/keeper.go @@ -5,10 +5,10 @@ import ( gogotypes "github.com/gogo/protobuf/types" - "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" "github.com/cosmos/cosmos-sdk/codec" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/slashing/types" ) @@ -42,7 +42,7 @@ 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 cryptotypes.PubKey) { addr := pubkey.Address() pkStr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubkey) @@ -54,7 +54,7 @@ func (k Keeper) AddPubkey(ctx sdk.Context, pubkey crypto.PubKey) { } // GetPubkey returns the pubkey from the adddress-pubkey relation -func (k Keeper) GetPubkey(ctx sdk.Context, address crypto.Address) (crypto.PubKey, error) { +func (k Keeper) GetPubkey(ctx sdk.Context, address cryptotypes.Address) (cryptotypes.PubKey, error) { store := ctx.KVStore(k.storeKey) var pubkey gogotypes.StringValue @@ -99,14 +99,14 @@ 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) { +func (k Keeper) setAddrPubkeyRelation(ctx sdk.Context, addr cryptotypes.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) { +func (k Keeper) deleteAddrPubkeyRelation(ctx sdk.Context, addr cryptotypes.Address) { store := ctx.KVStore(k.storeKey) store.Delete(types.AddrPubkeyRelationKey(addr)) } diff --git a/x/slashing/simulation/operations.go b/x/slashing/simulation/operations.go index d63700727782..20acc9e91a88 100644 --- a/x/slashing/simulation/operations.go +++ b/x/slashing/simulation/operations.go @@ -65,11 +65,10 @@ func SimulateMsgUnjail(ak types.AccountKeeper, bk types.BankKeeper, k keeper.Kee return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "validator is not jailed"), nil, nil } - cons, err := validator.TmConsPubKey() + consAddr, err := validator.GetConsAddr() if err != nil { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "unable to get validator consensus key"), nil, err } - consAddr := sdk.ConsAddress(cons.Address()) info, found := k.GetValidatorSigningInfo(ctx, consAddr) if !found { return simtypes.NoOpMsg(types.ModuleName, types.TypeMsgUnjail, "unable to find validator signing info"), nil, nil // skip diff --git a/x/staking/client/cli/tx.go b/x/staking/client/cli/tx.go index ab486c5a9841..e83e50f27524 100644 --- a/x/staking/client/cli/tx.go +++ b/x/staking/client/cli/tx.go @@ -7,11 +7,11 @@ import ( "github.com/spf13/cobra" flag "github.com/spf13/pflag" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -416,7 +416,7 @@ type TxCreateValidatorConfig struct { Identity string } -func PrepareConfigForTxCreateValidator(flagSet *flag.FlagSet, moniker, nodeID, chainID string, valPubKey crypto.PubKey) (TxCreateValidatorConfig, error) { +func PrepareConfigForTxCreateValidator(flagSet *flag.FlagSet, moniker, nodeID, chainID string, valPubKey cryptotypes.PubKey) (TxCreateValidatorConfig, error) { c := TxCreateValidatorConfig{} ip, err := flagSet.GetString(FlagIP) diff --git a/x/staking/genesis.go b/x/staking/genesis.go index 1b646f236412..02f6bc317473 100644 --- a/x/staking/genesis.go +++ b/x/staking/genesis.go @@ -5,9 +5,9 @@ import ( "log" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" tmtypes "github.com/tendermint/tendermint/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -198,14 +198,18 @@ func ExportGenesis(ctx sdk.Context, keeper keeper.Keeper) *types.GenesisState { // WriteValidators returns a slice of bonded genesis validators. func WriteValidators(ctx sdk.Context, keeper keeper.Keeper) (vals []tmtypes.GenesisValidator, err error) { keeper.IterateLastValidators(ctx, func(_ int64, validator types.ValidatorI) (stop bool) { - var consPk crypto.PubKey - consPk, err = validator.TmConsPubKey() + pk, err := validator.ConsPubKey() if err != nil { return true } + tmPk, err := cryptocodec.ToTmPubKeyInterface(pk) + if err != nil { + return true + } + vals = append(vals, tmtypes.GenesisValidator{ - Address: sdk.ConsAddress(consPk.Address()).Bytes(), - PubKey: consPk, + Address: sdk.ConsAddress(tmPk.Address()).Bytes(), + PubKey: tmPk, Power: validator.GetConsensusPower(), Name: validator.GetMoniker(), }) @@ -231,7 +235,7 @@ func validateGenesisStateValidators(validators []types.Validator) error { for i := 0; i < len(validators); i++ { val := validators[i] - consPk, err := val.TmConsPubKey() + consPk, err := val.ConsPubKey() if err != nil { return err } diff --git a/x/staking/handler_test.go b/x/staking/handler_test.go index 34a8cd78e746..844fc779905b 100644 --- a/x/staking/handler_test.go +++ b/x/staking/handler_test.go @@ -11,8 +11,8 @@ import ( tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtypes "github.com/tendermint/tendermint/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil/testdata" sdk "github.com/cosmos/cosmos-sdk/types" @@ -132,9 +132,11 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { validator := tstaking.CheckValidator(addr1, types.Bonded, false) assert.Equal(t, addr1.String(), validator.OperatorAddress) - consKey, err := validator.TmConsPubKey() + consKey, err := validator.TmConsPublicKey() require.NoError(t, err) - assert.Equal(t, pk1.(cryptotypes.IntoTmPubKey).AsTmPubKey(), consKey) + tmPk1, err := cryptocodec.ToTmProtoPublicKey(pk1) + require.NoError(t, err) + assert.Equal(t, tmPk1, consKey) assert.Equal(t, valTokens, validator.BondedTokens()) assert.Equal(t, valTokens.ToDec(), validator.DelegatorShares) assert.Equal(t, types.Description{}, validator.Description) @@ -155,9 +157,11 @@ func TestDuplicatesMsgCreateValidator(t *testing.T) { validator = tstaking.CheckValidator(addr2, types.Bonded, false) assert.Equal(t, addr2.String(), validator.OperatorAddress) - consPk, err := validator.TmConsPubKey() + consPk, err := validator.TmConsPublicKey() + require.NoError(t, err) + tmPk2, err := cryptocodec.ToTmProtoPublicKey(pk2) require.NoError(t, err) - assert.Equal(t, pk2.(cryptotypes.IntoTmPubKey).AsTmPubKey(), consPk) + assert.Equal(t, tmPk2, consPk) assert.True(sdk.IntEq(t, valTokens, validator.Tokens)) assert.True(sdk.DecEq(t, valTokens.ToDec(), validator.DelegatorShares)) assert.Equal(t, types.Description{}, validator.Description) diff --git a/x/staking/keeper/msg_server.go b/x/staking/keeper/msg_server.go index 472a96c4853f..3f112a0abb36 100644 --- a/x/staking/keeper/msg_server.go +++ b/x/staking/keeper/msg_server.go @@ -41,7 +41,7 @@ func (k msgServer) CreateValidator(goCtx context.Context, msg *types.MsgCreateVa pk, ok := msg.Pubkey.GetCachedValue().(cryptotypes.PubKey) if !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting crypto.PubKey, got %T", pk) + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting cryptotypes.PubKey, got %T", pk) } if _, found := k.GetValidatorByConsAddr(ctx, sdk.GetConsAddress(pk)); found { diff --git a/x/staking/keeper/validator_test.go b/x/staking/keeper/validator_test.go index c28b6db3582a..894a6008509f 100644 --- a/x/staking/keeper/validator_test.go +++ b/x/staking/keeper/validator_test.go @@ -8,9 +8,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -19,7 +19,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/staking/types" ) -func newMonikerValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey, moniker string) types.Validator { +func newMonikerValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey, moniker string) types.Validator { v, err := types.NewValidator(operator, pubKey, types.Description{Moniker: moniker}) require.NoError(t, err) return v diff --git a/x/staking/legacy/v034/types.go b/x/staking/legacy/v034/types.go index 6e93b7986a52..9f8622d4bec2 100644 --- a/x/staking/legacy/v034/types.go +++ b/x/staking/legacy/v034/types.go @@ -5,9 +5,8 @@ package v034 import ( "time" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec/legacy" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -76,17 +75,17 @@ type ( } Validator struct { - OperatorAddress sdk.ValAddress `json:"operator_address"` - ConsPubKey crypto.PubKey `json:"consensus_pubkey"` - Jailed bool `json:"jailed"` - Status BondStatus `json:"status"` - Tokens sdk.Int `json:"tokens"` - DelegatorShares sdk.Dec `json:"delegator_shares"` - Description Description `json:"description"` - UnbondingHeight int64 `json:"unbonding_height"` - UnbondingCompletionTime time.Time `json:"unbonding_time"` - Commission Commission `json:"commission"` - MinSelfDelegation sdk.Int `json:"min_self_delegation"` + OperatorAddress sdk.ValAddress `json:"operator_address"` + ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey"` + Jailed bool `json:"jailed"` + Status BondStatus `json:"status"` + Tokens sdk.Int `json:"tokens"` + DelegatorShares sdk.Dec `json:"delegator_shares"` + Description Description `json:"description"` + UnbondingHeight int64 `json:"unbonding_height"` + UnbondingCompletionTime time.Time `json:"unbonding_time"` + Commission Commission `json:"commission"` + MinSelfDelegation sdk.Int `json:"min_self_delegation"` } Validators []Validator @@ -170,6 +169,7 @@ func (v *Validator) UnmarshalJSON(data []byte) error { if err != nil { return err } + *v = Validator{ OperatorAddress: bv.OperatorAddress, ConsPubKey: consPubKey, diff --git a/x/staking/legacy/v036/migrate_test.go b/x/staking/legacy/v036/migrate_test.go new file mode 100644 index 000000000000..7278774bf77c --- /dev/null +++ b/x/staking/legacy/v036/migrate_test.go @@ -0,0 +1,103 @@ +package v036_test + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + v034staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v034" + v036staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v036" + "github.com/stretchr/testify/require" +) + +func TestMigrate(t *testing.T) { + aminoCdc := codec.NewLegacyAmino() + consPubKeyEd := ed25519.GenPrivKeyFromSecret([]byte("val0")).PubKey() + consPubKeySecp := secp256k1.GenPrivKeyFromSecret([]byte("val1")).PubKey() + stakingGenState := v034staking.GenesisState{ + Validators: v034staking.Validators{ + v034staking.Validator{ + ConsPubKey: consPubKeyEd, + Status: v034staking.Unbonded, + }, v034staking.Validator{ + ConsPubKey: consPubKeySecp, + Status: v034staking.Unbonded, + }, + }, + } + + migrated := v036staking.Migrate(stakingGenState) + + json, err := aminoCdc.MarshalJSONIndent(migrated, "", " ") + require.NoError(t, err) + + expectedJSON := `{ + "params": { + "unbonding_time": "0", + "max_validators": 0, + "max_entries": 0, + "bond_denom": "" + }, + "last_total_power": "0", + "last_validator_powers": null, + "validators": [ + { + "operator_address": "", + "consensus_pubkey": "cosmosvalconspub1zcjduepq9ymett3nlv6fytn7lqxzd3q3ckvd79eqlcf3wkhgamcl4rzghesq83ecpx", + "jailed": false, + "status": 0, + "tokens": "0", + "delegator_shares": "0", + "description": { + "moniker": "", + "identity": "", + "website": "", + "details": "" + }, + "unbonding_height": "0", + "unbonding_time": "0001-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0", + "max_rate": "0", + "max_change_rate": "0" + }, + "update_time": "0001-01-01T00:00:00Z" + }, + "min_self_delegation": "0" + }, + { + "operator_address": "", + "consensus_pubkey": "cosmosvalconspub1addwnpepqwfxk5k5pugwz3quqyzvzupefm3589tw6x9dkzjdkuzn7hgpz33ag84e406", + "jailed": false, + "status": 0, + "tokens": "0", + "delegator_shares": "0", + "description": { + "moniker": "", + "identity": "", + "website": "", + "details": "" + }, + "unbonding_height": "0", + "unbonding_time": "0001-01-01T00:00:00Z", + "commission": { + "commission_rates": { + "rate": "0", + "max_rate": "0", + "max_change_rate": "0" + }, + "update_time": "0001-01-01T00:00:00Z" + }, + "min_self_delegation": "0" + } + ], + "delegations": null, + "unbonding_delegations": null, + "redelegations": null, + "exported": false +}` + + require.Equal(t, expectedJSON, string(json)) +} diff --git a/x/staking/legacy/v036/types.go b/x/staking/legacy/v036/types.go index 6c110bbe57dc..b433b0070100 100644 --- a/x/staking/legacy/v036/types.go +++ b/x/staking/legacy/v036/types.go @@ -5,9 +5,8 @@ package v036 import ( "time" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec/legacy" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" v034staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v034" ) @@ -30,7 +29,7 @@ type ( Validator struct { OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"` - ConsPubKey crypto.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"` + ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"` Jailed bool `json:"jailed" yaml:"jailed"` Status v034staking.BondStatus `json:"status" yaml:"status"` Tokens sdk.Int `json:"tokens" yaml:"tokens"` diff --git a/x/staking/legacy/v038/types.go b/x/staking/legacy/v038/types.go index aff9a559d457..58ffa1351ba5 100644 --- a/x/staking/legacy/v038/types.go +++ b/x/staking/legacy/v038/types.go @@ -5,9 +5,8 @@ package v038 import ( "time" - "github.com/tendermint/tendermint/crypto" - "github.com/cosmos/cosmos-sdk/codec/legacy" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" v034staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v034" v036staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v036" @@ -28,7 +27,7 @@ type ( Validator struct { OperatorAddress sdk.ValAddress `json:"operator_address" yaml:"operator_address"` - ConsPubKey crypto.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"` + ConsPubKey cryptotypes.PubKey `json:"consensus_pubkey" yaml:"consensus_pubkey"` Jailed bool `json:"jailed" yaml:"jailed"` Status v034staking.BondStatus `json:"status" yaml:"status"` Tokens sdk.Int `json:"tokens" yaml:"tokens"` diff --git a/x/staking/teststaking/helper.go b/x/staking/teststaking/helper.go index c0ba45bb1a98..e63c816abbe1 100644 --- a/x/staking/teststaking/helper.go +++ b/x/staking/teststaking/helper.go @@ -5,8 +5,8 @@ import ( "time" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking" "github.com/cosmos/cosmos-sdk/x/staking/keeper" @@ -32,14 +32,14 @@ func NewHelper(t *testing.T, ctx sdk.Context, k keeper.Keeper) *Helper { } // CreateValidator calls handler to create a new staking validator -func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk crypto.PubKey, stakeAmount int64, ok bool) { +func (sh *Helper) CreateValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount int64, ok bool) { coin := sdk.NewCoin(sh.Denom, sdk.NewInt(stakeAmount)) sh.createValidator(addr, pk, coin, ok) } // CreateValidatorWithValPower calls handler to create a new staking validator with zero // commission -func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk crypto.PubKey, valPower int64, ok bool) sdk.Int { +func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk cryptotypes.PubKey, valPower int64, ok bool) sdk.Int { amount := sdk.TokensFromConsensusPower(valPower) coin := sdk.NewCoin(sh.Denom, amount) sh.createValidator(addr, pk, coin, ok) @@ -47,14 +47,14 @@ func (sh *Helper) CreateValidatorWithValPower(addr sdk.ValAddress, pk crypto.Pub } // CreateValidatorMsg returns a message used to create validator in this service. -func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk crypto.PubKey, stakeAmount int64) *stakingtypes.MsgCreateValidator { +func (sh *Helper) CreateValidatorMsg(addr sdk.ValAddress, pk cryptotypes.PubKey, stakeAmount int64) *stakingtypes.MsgCreateValidator { coin := sdk.NewCoin(sh.Denom, sdk.NewInt(stakeAmount)) msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) require.NoError(sh.t, err) return msg } -func (sh *Helper) createValidator(addr sdk.ValAddress, pk crypto.PubKey, coin sdk.Coin, ok bool) { +func (sh *Helper) createValidator(addr sdk.ValAddress, pk cryptotypes.PubKey, coin sdk.Coin, ok bool) { msg, err := stakingtypes.NewMsgCreateValidator(addr, pk, coin, stakingtypes.Description{}, sh.Commission, sdk.OneInt()) require.NoError(sh.t, err) sh.Handle(msg, ok) diff --git a/x/staking/teststaking/tm.go b/x/staking/teststaking/tm.go new file mode 100644 index 000000000000..9a9c030d061c --- /dev/null +++ b/x/staking/teststaking/tm.go @@ -0,0 +1,43 @@ +package teststaking + +import ( + tmcrypto "github.com/tendermint/tendermint/crypto" + tmtypes "github.com/tendermint/tendermint/types" + + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +// GetTmConsPubKey gets the validator's public key as a tmcrypto.PubKey. +func GetTmConsPubKey(v types.Validator) (tmcrypto.PubKey, error) { + pk, err := v.ConsPubKey() + if err != nil { + return nil, err + } + + return cryptocodec.ToTmPubKeyInterface(pk) +} + +// ToTmValidator casts an SDK validator to a tendermint type Validator. +func ToTmValidator(v types.Validator) (*tmtypes.Validator, error) { + tmPk, err := GetTmConsPubKey(v) + if err != nil { + return nil, err + } + + return tmtypes.NewValidator(tmPk, v.ConsensusPower()), nil +} + +// ToTmValidators casts all validators to the corresponding tendermint type. +func ToTmValidators(v types.Validators) ([]*tmtypes.Validator, error) { + validators := make([]*tmtypes.Validator, len(v)) + var err error + for i, val := range v { + validators[i], err = ToTmValidator(val) + if err != nil { + return nil, err + } + } + + return validators, nil +} diff --git a/x/staking/teststaking/validator.go b/x/staking/teststaking/validator.go index 90dd485999fd..901395d76e92 100644 --- a/x/staking/teststaking/validator.go +++ b/x/staking/teststaking/validator.go @@ -4,14 +4,14 @@ import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) // NewValidator is a testing helper method to create validators in tests -func NewValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey) types.Validator { +func NewValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { v, err := types.NewValidator(operator, pubKey, types.Description{}) require.NoError(t, err) return v diff --git a/x/staking/types/commission_test.go b/x/staking/types/commission_test.go index ec6186122a7e..3ca95cf4b47f 100644 --- a/x/staking/types/commission_test.go +++ b/x/staking/types/commission_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "testing" @@ -7,27 +7,28 @@ import ( "github.com/stretchr/testify/require" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestCommissionValidate(t *testing.T) { testCases := []struct { - input Commission + input types.Commission expectErr bool }{ // invalid commission; max rate < 0% - {NewCommission(sdk.ZeroDec(), sdk.MustNewDecFromStr("-1.00"), sdk.ZeroDec()), true}, + {types.NewCommission(sdk.ZeroDec(), sdk.MustNewDecFromStr("-1.00"), sdk.ZeroDec()), true}, // invalid commission; max rate > 100% - {NewCommission(sdk.ZeroDec(), sdk.MustNewDecFromStr("2.00"), sdk.ZeroDec()), true}, + {types.NewCommission(sdk.ZeroDec(), sdk.MustNewDecFromStr("2.00"), sdk.ZeroDec()), true}, // invalid commission; rate < 0% - {NewCommission(sdk.MustNewDecFromStr("-1.00"), sdk.ZeroDec(), sdk.ZeroDec()), true}, + {types.NewCommission(sdk.MustNewDecFromStr("-1.00"), sdk.ZeroDec(), sdk.ZeroDec()), true}, // invalid commission; rate > max rate - {NewCommission(sdk.MustNewDecFromStr("0.75"), sdk.MustNewDecFromStr("0.50"), sdk.ZeroDec()), true}, + {types.NewCommission(sdk.MustNewDecFromStr("0.75"), sdk.MustNewDecFromStr("0.50"), sdk.ZeroDec()), true}, // invalid commission; max change rate < 0% - {NewCommission(sdk.OneDec(), sdk.OneDec(), sdk.MustNewDecFromStr("-1.00")), true}, + {types.NewCommission(sdk.OneDec(), sdk.OneDec(), sdk.MustNewDecFromStr("-1.00")), true}, // invalid commission; max change rate > max rate - {NewCommission(sdk.OneDec(), sdk.MustNewDecFromStr("0.75"), sdk.MustNewDecFromStr("0.90")), true}, + {types.NewCommission(sdk.OneDec(), sdk.MustNewDecFromStr("0.75"), sdk.MustNewDecFromStr("0.90")), true}, // valid commission - {NewCommission(sdk.MustNewDecFromStr("0.20"), sdk.OneDec(), sdk.MustNewDecFromStr("0.10")), false}, + {types.NewCommission(sdk.MustNewDecFromStr("0.20"), sdk.OneDec(), sdk.MustNewDecFromStr("0.10")), false}, } for i, tc := range testCases { @@ -38,11 +39,11 @@ func TestCommissionValidate(t *testing.T) { func TestCommissionValidateNewRate(t *testing.T) { now := time.Now().UTC() - c1 := NewCommission(sdk.MustNewDecFromStr("0.40"), sdk.MustNewDecFromStr("0.80"), sdk.MustNewDecFromStr("0.10")) + c1 := types.NewCommission(sdk.MustNewDecFromStr("0.40"), sdk.MustNewDecFromStr("0.80"), sdk.MustNewDecFromStr("0.10")) c1.UpdateTime = now testCases := []struct { - input Commission + input types.Commission newRate sdk.Dec blockTime time.Time expectErr bool diff --git a/x/staking/types/data_test.go b/x/staking/types/data_test.go index 5505b9d5ce5e..3f8b290f9415 100644 --- a/x/staking/types/data_test.go +++ b/x/staking/types/data_test.go @@ -1,12 +1,11 @@ -package types +package types_test import ( "fmt" - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,7 +22,7 @@ var ( valAddr3 = sdk.ValAddress(pk3.Address()) emptyAddr sdk.ValAddress - emptyPubkey crypto.PubKey + emptyPubkey cryptotypes.PubKey ) func init() { diff --git a/x/staking/types/delegation_test.go b/x/staking/types/delegation_test.go index 7723570ff0ef..7ca5e8132eb4 100644 --- a/x/staking/types/delegation_test.go +++ b/x/staking/types/delegation_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "encoding/json" @@ -9,10 +9,11 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestDelegationEqual(t *testing.T) { - d1 := NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100)) + d1 := types.NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100)) d2 := d1 ok := d1.String() == d2.String() @@ -26,12 +27,12 @@ func TestDelegationEqual(t *testing.T) { } func TestDelegationString(t *testing.T) { - d := NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100)) + d := types.NewDelegation(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(100)) require.NotEmpty(t, d.String()) } func TestUnbondingDelegationEqual(t *testing.T) { - ubd1 := NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0, + ubd1 := types.NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0, time.Unix(0, 0), sdk.NewInt(0)) ubd2 := ubd1 @@ -46,17 +47,17 @@ func TestUnbondingDelegationEqual(t *testing.T) { } func TestUnbondingDelegationString(t *testing.T) { - ubd := NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0, + ubd := types.NewUnbondingDelegation(sdk.AccAddress(valAddr1), valAddr2, 0, time.Unix(0, 0), sdk.NewInt(0)) require.NotEmpty(t, ubd.String()) } func TestRedelegationEqual(t *testing.T) { - r1 := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, + r1 := types.NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, time.Unix(0, 0), sdk.NewInt(0), sdk.NewDec(0)) - r2 := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, + r2 := types.NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, time.Unix(0, 0), sdk.NewInt(0), sdk.NewDec(0)) @@ -71,7 +72,7 @@ func TestRedelegationEqual(t *testing.T) { } func TestRedelegationString(t *testing.T) { - r := NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, + r := types.NewRedelegation(sdk.AccAddress(valAddr1), valAddr2, valAddr3, 0, time.Unix(0, 0), sdk.NewInt(0), sdk.NewDec(10)) @@ -80,11 +81,11 @@ func TestRedelegationString(t *testing.T) { func TestDelegationResponses(t *testing.T) { cdc := codec.NewLegacyAmino() - dr1 := NewDelegationResp(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(5), + dr1 := types.NewDelegationResp(sdk.AccAddress(valAddr1), valAddr2, sdk.NewDec(5), sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(5))) - dr2 := NewDelegationResp(sdk.AccAddress(valAddr1), valAddr3, sdk.NewDec(5), + dr2 := types.NewDelegationResp(sdk.AccAddress(valAddr1), valAddr3, sdk.NewDec(5), sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(5))) - drs := DelegationResponses{dr1, dr2} + drs := types.DelegationResponses{dr1, dr2} bz1, err := json.Marshal(dr1) require.NoError(t, err) @@ -102,20 +103,20 @@ func TestDelegationResponses(t *testing.T) { require.Equal(t, bz1, bz2) - var drs2 DelegationResponses + var drs2 types.DelegationResponses require.NoError(t, cdc.UnmarshalJSON(bz2, &drs2)) require.Equal(t, drs, drs2) } func TestRedelegationResponses(t *testing.T) { cdc := codec.NewLegacyAmino() - entries := []RedelegationEntryResponse{ - NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), - NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), + entries := []types.RedelegationEntryResponse{ + types.NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), + types.NewRedelegationEntryResponse(0, time.Unix(0, 0), sdk.NewDec(5), sdk.NewInt(5), sdk.NewInt(5)), } - rdr1 := NewRedelegationResponse(sdk.AccAddress(valAddr1), valAddr2, valAddr3, entries) - rdr2 := NewRedelegationResponse(sdk.AccAddress(valAddr2), valAddr1, valAddr3, entries) - rdrs := RedelegationResponses{rdr1, rdr2} + rdr1 := types.NewRedelegationResponse(sdk.AccAddress(valAddr1), valAddr2, valAddr3, entries) + rdr2 := types.NewRedelegationResponse(sdk.AccAddress(valAddr2), valAddr1, valAddr3, entries) + rdrs := types.RedelegationResponses{rdr1, rdr2} bz1, err := json.Marshal(rdr1) require.NoError(t, err) @@ -133,7 +134,7 @@ func TestRedelegationResponses(t *testing.T) { require.Equal(t, bz1, bz2) - var rdrs2 RedelegationResponses + var rdrs2 types.RedelegationResponses require.NoError(t, cdc.UnmarshalJSON(bz2, &rdrs2)) bz3, err := cdc.MarshalJSON(rdrs2) diff --git a/x/staking/types/exported.go b/x/staking/types/exported.go index f8cf8be99ef9..a02adc34bade 100644 --- a/x/staking/types/exported.go +++ b/x/staking/types/exported.go @@ -1,8 +1,10 @@ package types import ( + tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/crypto" ) // DelegationI delegation bond for a delegated proof of stake system @@ -21,7 +23,8 @@ type ValidatorI interface { IsUnbonded() bool // check if has status unbonded IsUnbonding() bool // check if has status unbonding GetOperator() sdk.ValAddress // operator address to receive/return validators coins - TmConsPubKey() (crypto.PubKey, error) // validation consensus pubkey + ConsPubKey() (cryptotypes.PubKey, error) // validation consensus pubkey (cryptotypes.PubKey) + TmConsPublicKey() (tmprotocrypto.PublicKey, error) // validation consensus pubkey (Tendermint) GetConsAddr() (sdk.ConsAddress, error) // validation consensus address GetTokens() sdk.Int // validation tokens GetBondedTokens() sdk.Int // validator bonded tokens diff --git a/x/staking/types/historical_info_test.go b/x/staking/types/historical_info_test.go index f7f6f2a86925..ca3e48951e73 100644 --- a/x/staking/types/historical_info_test.go +++ b/x/staking/types/historical_info_test.go @@ -1,10 +1,11 @@ -package types +package types_test import ( "math/rand" "sort" "testing" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) @@ -14,8 +15,8 @@ var header = tmproto.Header{ Height: 5, } -func createValidators(t *testing.T) []Validator { - return []Validator{ +func createValidators(t *testing.T) []types.Validator { + return []types.Validator{ newValidator(t, valAddr1, pk1), newValidator(t, valAddr2, pk2), newValidator(t, valAddr3, pk3), @@ -24,48 +25,48 @@ func createValidators(t *testing.T) []Validator { func TestHistoricalInfo(t *testing.T) { validators := createValidators(t) - hi := NewHistoricalInfo(header, validators) - require.True(t, sort.IsSorted(Validators(hi.Valset)), "Validators are not sorted") + hi := types.NewHistoricalInfo(header, validators) + require.True(t, sort.IsSorted(types.Validators(hi.Valset)), "Validators are not sorted") var value []byte require.NotPanics(t, func() { - value = ModuleCdc.MustMarshalBinaryBare(&hi) + value = types.ModuleCdc.MustMarshalBinaryBare(&hi) }) require.NotNil(t, value, "Marshalled HistoricalInfo is nil") - recv, err := UnmarshalHistoricalInfo(ModuleCdc, value) + recv, err := types.UnmarshalHistoricalInfo(types.ModuleCdc, value) require.Nil(t, err, "Unmarshalling HistoricalInfo failed") require.Equal(t, hi.Header, recv.Header) for i := range hi.Valset { require.True(t, hi.Valset[i].Equal(&recv.Valset[i])) } - require.True(t, sort.IsSorted(Validators(hi.Valset)), "Validators are not sorted") + require.True(t, sort.IsSorted(types.Validators(hi.Valset)), "Validators are not sorted") } func TestValidateBasic(t *testing.T) { validators := createValidators(t) - hi := HistoricalInfo{ + hi := types.HistoricalInfo{ Header: header, } - err := ValidateBasic(hi) + err := types.ValidateBasic(hi) require.Error(t, err, "ValidateBasic passed on nil ValSet") // Ensure validators are not sorted - for sort.IsSorted(Validators(validators)) { + for sort.IsSorted(types.Validators(validators)) { rand.Shuffle(len(validators), func(i, j int) { it := validators[i] validators[i] = validators[j] validators[j] = it }) } - hi = HistoricalInfo{ + hi = types.HistoricalInfo{ Header: header, Valset: validators, } - err = ValidateBasic(hi) + err = types.ValidateBasic(hi) require.Error(t, err, "ValidateBasic passed on unsorted ValSet") - hi = NewHistoricalInfo(header, validators) - err = ValidateBasic(hi) + hi = types.NewHistoricalInfo(header, validators) + err = types.ValidateBasic(hi) require.NoError(t, err, "ValidateBasic failed on valid HistoricalInfo") } diff --git a/x/staking/types/keys.go b/x/staking/types/keys.go index 71aa5875061d..40d62244a041 100644 --- a/x/staking/types/keys.go +++ b/x/staking/types/keys.go @@ -71,17 +71,8 @@ func AddressFromLastValidatorPowerKey(key []byte) []byte { // VALUE: validator operator address ([]byte) func GetValidatorsByPowerIndexKey(validator Validator) []byte { // NOTE the address doesn't need to be stored because counter bytes must always be different - return getValidatorPowerRank(validator) -} - -// get the bonded validator index key for an operator address -func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte { - return append(LastValidatorPowerKey, operator...) -} + // NOTE the larger values are of higher value -// get the power ranking of a validator -// NOTE the larger values are of higher value -func getValidatorPowerRank(validator Validator) []byte { consensusPower := sdk.TokensToConsensusPower(validator.Tokens) consensusPowerBytes := make([]byte, 8) binary.BigEndian.PutUint64(consensusPowerBytes, uint64(consensusPower)) @@ -109,6 +100,11 @@ func getValidatorPowerRank(validator Validator) []byte { return key } +// get the bonded validator index key for an operator address +func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte { + return append(LastValidatorPowerKey, operator...) +} + // parse the validators operator address from power rank key func ParseValidatorPowerRankKey(key []byte) (operAddr []byte) { powerBytesLen := 8 diff --git a/x/staking/types/keys_test.go b/x/staking/types/keys_test.go index 3569b126c1ad..0f63617f26b3 100644 --- a/x/staking/types/keys_test.go +++ b/x/staking/types/keys_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "bytes" @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -33,7 +34,7 @@ func TestGetValidatorPowerRank(t *testing.T) { val4.Tokens = sdk.TokensFromConsensusPower(x.Int64()) tests := []struct { - validator Validator + validator types.Validator wantHex string }{ {val1, "2300000000000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, @@ -42,7 +43,7 @@ func TestGetValidatorPowerRank(t *testing.T) { {val4, "2300000100000000009c288ede7df62742fc3b7d0962045a8cef0f79f6"}, } for i, tt := range tests { - got := hex.EncodeToString(getValidatorPowerRank(tt.validator)) + got := hex.EncodeToString(types.GetValidatorsByPowerIndexKey(tt.validator)) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } @@ -63,7 +64,7 @@ func TestGetREDByValDstIndexKey(t *testing.T) { "363ab62f0d93849be495e21e3e9013a517038f45bd5ef3b5f25c54946d4a89fc0d09d2f126614540f263d771218209d8bd03c482f69dfba57310f08609"}, } for i, tt := range tests { - got := hex.EncodeToString(GetREDByValDstIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) + got := hex.EncodeToString(types.GetREDByValDstIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } @@ -84,7 +85,7 @@ func TestGetREDByValSrcIndexKey(t *testing.T) { "3563d771218209d8bd03c482f69dfba57310f086095ef3b5f25c54946d4a89fc0d09d2f126614540f23ab62f0d93849be495e21e3e9013a517038f45bd"}, } for i, tt := range tests { - got := hex.EncodeToString(GetREDByValSrcIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) + got := hex.EncodeToString(types.GetREDByValSrcIndexKey(tt.delAddr, tt.valSrcAddr, tt.valDstAddr)) require.Equal(t, tt.wantHex, got, "Keys did not match on test case %d", i) } @@ -94,8 +95,8 @@ func TestGetValidatorQueueKey(t *testing.T) { ts := time.Now() height := int64(1024) - bz := GetValidatorQueueKey(ts, height) - rTs, rHeight, err := ParseValidatorQueueKey(bz) + bz := types.GetValidatorQueueKey(ts, height) + rTs, rHeight, err := types.ParseValidatorQueueKey(bz) require.NoError(t, err) require.Equal(t, ts.UTC(), rTs.UTC()) require.Equal(t, rHeight, height) @@ -105,11 +106,11 @@ func TestTestGetValidatorQueueKeyOrder(t *testing.T) { ts := time.Now().UTC() height := int64(1000) - endKey := GetValidatorQueueKey(ts, height) + endKey := types.GetValidatorQueueKey(ts, height) - keyA := GetValidatorQueueKey(ts.Add(-10*time.Minute), height-10) - keyB := GetValidatorQueueKey(ts.Add(-5*time.Minute), height+50) - keyC := GetValidatorQueueKey(ts.Add(10*time.Minute), height+100) + keyA := types.GetValidatorQueueKey(ts.Add(-10*time.Minute), height-10) + keyB := types.GetValidatorQueueKey(ts.Add(-5*time.Minute), height+50) + keyC := types.GetValidatorQueueKey(ts.Add(10*time.Minute), height+100) require.Equal(t, -1, bytes.Compare(keyA, endKey)) // keyA <= endKey require.Equal(t, -1, bytes.Compare(keyB, endKey)) // keyB <= endKey diff --git a/x/staking/types/msg.go b/x/staking/types/msg.go index 51e19ac263f9..85d0c1d3c23b 100644 --- a/x/staking/types/msg.go +++ b/x/staking/types/msg.go @@ -3,9 +3,8 @@ package types import ( "bytes" - "github.com/tendermint/tendermint/crypto" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) @@ -32,7 +31,7 @@ var ( // NewMsgCreateValidator creates a new MsgCreateValidator instance. // Delegator address and validator address are the same. func NewMsgCreateValidator( - valAddr sdk.ValAddress, pubKey crypto.PubKey, selfDelegation sdk.Coin, + valAddr sdk.ValAddress, pubKey cryptotypes.PubKey, selfDelegation sdk.Coin, description Description, commission CommissionRates, minSelfDelegation sdk.Int, ) (*MsgCreateValidator, error) { pkAny, err := codectypes.PackAny(pubKey) @@ -140,7 +139,7 @@ func (msg MsgCreateValidator) ValidateBasic() error { // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (msg MsgCreateValidator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var pubKey crypto.PubKey + var pubKey cryptotypes.PubKey return unpacker.UnpackAny(msg.Pubkey, &pubKey) } diff --git a/x/staking/types/msg_test.go b/x/staking/types/msg_test.go index eb83b33162ce..3b858a64ddc3 100644 --- a/x/staking/types/msg_test.go +++ b/x/staking/types/msg_test.go @@ -1,10 +1,9 @@ -package types +package types_test import ( "testing" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -12,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -22,7 +22,7 @@ var ( func TestMsgDecode(t *testing.T) { registry := codectypes.NewInterfaceRegistry() cryptocodec.RegisterInterfaces(registry) - RegisterInterfaces(registry) + types.RegisterInterfaces(registry) cdc := codec.NewProtoCodec(registry) // firstly we start testing the pubkey serialization @@ -36,8 +36,8 @@ func TestMsgDecode(t *testing.T) { // now let's try to serialize the whole message - commission1 := NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - msg, err := NewMsgCreateValidator(valAddr1, pk1, coinPos, Description{}, commission1, sdk.OneInt()) + commission1 := types.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + msg, err := types.NewMsgCreateValidator(valAddr1, pk1, coinPos, types.Description{}, commission1, sdk.OneInt()) require.NoError(t, err) msgSerialized, err := codec.MarshalAny(cdc, msg) require.NoError(t, err) @@ -45,7 +45,7 @@ func TestMsgDecode(t *testing.T) { var msgUnmarshaled sdk.Msg err = codec.UnmarshalAny(cdc, &msgUnmarshaled, msgSerialized) require.NoError(t, err) - msg2, ok := msgUnmarshaled.(*MsgCreateValidator) + msg2, ok := msgUnmarshaled.(*types.MsgCreateValidator) require.True(t, ok) require.True(t, msg.Value.IsEqual(msg2.Value)) require.True(t, msg.Pubkey.Equal(msg2.Pubkey)) @@ -53,15 +53,15 @@ func TestMsgDecode(t *testing.T) { // test ValidateBasic for MsgCreateValidator func TestMsgCreateValidator(t *testing.T) { - commission1 := NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) - commission2 := NewCommissionRates(sdk.NewDec(5), sdk.NewDec(5), sdk.NewDec(5)) + commission1 := types.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()) + commission2 := types.NewCommissionRates(sdk.NewDec(5), sdk.NewDec(5), sdk.NewDec(5)) tests := []struct { name, moniker, identity, website, securityContact, details string - CommissionRates CommissionRates + CommissionRates types.CommissionRates minSelfDelegation sdk.Int validatorAddr sdk.ValAddress - pubkey crypto.PubKey + pubkey cryptotypes.PubKey bond sdk.Coin expectPass bool }{ @@ -79,8 +79,8 @@ func TestMsgCreateValidator(t *testing.T) { for _, tc := range tests { t.Logf("Test: %s, pk=%t", tc.name, tc.pubkey) - description := NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) - msg, err := NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description, tc.CommissionRates, tc.minSelfDelegation) + description := types.NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) + msg, err := types.NewMsgCreateValidator(tc.validatorAddr, tc.pubkey, tc.bond, description, tc.CommissionRates, tc.minSelfDelegation) require.NoError(t, err) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) @@ -106,10 +106,10 @@ func TestMsgEditValidator(t *testing.T) { } for _, tc := range tests { - description := NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) + description := types.NewDescription(tc.moniker, tc.identity, tc.website, tc.securityContact, tc.details) newRate := sdk.ZeroDec() - msg := NewMsgEditValidator(tc.validatorAddr, description, &newRate, &tc.minSelfDelegation) + msg := types.NewMsgEditValidator(tc.validatorAddr, description, &newRate, &tc.minSelfDelegation) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { @@ -136,7 +136,7 @@ func TestMsgDelegate(t *testing.T) { } for _, tc := range tests { - msg := NewMsgDelegate(tc.delegatorAddr, tc.validatorAddr, tc.bond) + msg := types.NewMsgDelegate(tc.delegatorAddr, tc.validatorAddr, tc.bond) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { @@ -164,7 +164,7 @@ func TestMsgBeginRedelegate(t *testing.T) { } for _, tc := range tests { - msg := NewMsgBeginRedelegate(tc.delegatorAddr, tc.validatorSrcAddr, tc.validatorDstAddr, tc.amount) + msg := types.NewMsgBeginRedelegate(tc.delegatorAddr, tc.validatorSrcAddr, tc.validatorDstAddr, tc.amount) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { @@ -190,7 +190,7 @@ func TestMsgUndelegate(t *testing.T) { } for _, tc := range tests { - msg := NewMsgUndelegate(tc.delegatorAddr, tc.validatorAddr, tc.amount) + msg := types.NewMsgUndelegate(tc.delegatorAddr, tc.validatorAddr, tc.amount) if tc.expectPass { require.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { diff --git a/x/staking/types/params_test.go b/x/staking/types/params_test.go index c18700ef43d5..05a7ea956f6e 100644 --- a/x/staking/types/params_test.go +++ b/x/staking/types/params_test.go @@ -1,14 +1,15 @@ -package types +package types_test import ( "testing" + "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/require" ) func TestParamsEqual(t *testing.T) { - p1 := DefaultParams() - p2 := DefaultParams() + p1 := types.DefaultParams() + p2 := types.DefaultParams() ok := p1.Equal(p2) require.True(t, ok) diff --git a/x/staking/types/validator.go b/x/staking/types/validator.go index 19e032dbabac..c99aafd4c352 100644 --- a/x/staking/types/validator.go +++ b/x/staking/types/validator.go @@ -8,13 +8,12 @@ import ( "time" abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" - tmtypes "github.com/tendermint/tendermint/types" + tmprotocrypto "github.com/tendermint/tendermint/proto/tendermint/crypto" "gopkg.in/yaml.v2" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" @@ -40,7 +39,7 @@ var _ ValidatorI = Validator{} // NewValidator constructs a new Validator //nolint:interfacer -func NewValidator(operator sdk.ValAddress, pubKey crypto.PubKey, description Description) (Validator, error) { +func NewValidator(operator sdk.ValAddress, pubKey cryptotypes.PubKey, description Description) (Validator, error) { pkAny, err := codectypes.PackAny(pubKey) if err != nil { return Validator{}, err @@ -78,7 +77,7 @@ func (v Validators) String() (out string) { return strings.TrimSpace(out) } -// ToSDKValidators - convenience function convert []Validators to []sdk.Validators +// ToSDKValidators - convenience function convert []Validator to []sdk.ValidatorI func (v Validators) ToSDKValidators() (validators []ValidatorI) { for _, val := range v { validators = append(validators, val) @@ -87,20 +86,6 @@ func (v Validators) ToSDKValidators() (validators []ValidatorI) { return validators } -// ToTmValidators casts all validators to the corresponding tendermint type. -func (v Validators) ToTmValidators() ([]*tmtypes.Validator, error) { - validators := make([]*tmtypes.Validator, len(v)) - var err error - for i, val := range v { - validators[i], err = val.ToTmValidator() - if err != nil { - return nil, err - } - } - - return validators, nil -} - // Sort Validators sorts validator array in ascending operator address order func (v Validators) Sort() { sort.Sort(v) @@ -273,17 +258,13 @@ func (d Description) EnsureLength() (Description, error) { // ABCIValidatorUpdate returns an abci.ValidatorUpdate from a staking validator type // with the full validator power func (v Validator) ABCIValidatorUpdate() abci.ValidatorUpdate { - consPk, err := v.TmConsPubKey() - if err != nil { - panic(err) - } - pk, err := encoding.PubKeyToProto(consPk) + tmProtoPk, err := v.TmConsPublicKey() if err != nil { panic(err) } return abci.ValidatorUpdate{ - PubKey: pk, + PubKey: tmProtoPk, Power: v.ConsensusPower(), } } @@ -291,30 +272,17 @@ func (v Validator) ABCIValidatorUpdate() abci.ValidatorUpdate { // ABCIValidatorUpdateZero returns an abci.ValidatorUpdate from a staking validator type // with zero power used for validator updates. func (v Validator) ABCIValidatorUpdateZero() abci.ValidatorUpdate { - consPk, err := v.TmConsPubKey() - if err != nil { - panic(err) - } - pk, err := encoding.PubKeyToProto(consPk) + tmProtoPk, err := v.TmConsPublicKey() if err != nil { panic(err) } return abci.ValidatorUpdate{ - PubKey: pk, + PubKey: tmProtoPk, Power: 0, } } -// ToTmValidator casts an SDK validator to a tendermint type Validator. -func (v Validator) ToTmValidator() (*tmtypes.Validator, error) { - consPk, err := v.TmConsPubKey() - if err != nil { - return nil, err - } - return tmtypes.NewValidator(consPk, v.ConsensusPower()), nil -} - // SetInitialCommission attempts to set a validator's initial commission. An // error is returned if the commission is invalid. func (v Validator) SetInitialCommission(commission Commission) (Validator, error) { @@ -379,8 +347,8 @@ func (v Validator) BondedTokens() sdk.Int { return sdk.ZeroInt() } -// get the consensus-engine power -// a reduction of 10^6 from validator tokens is applied +// ConsensusPower gets the consensus-engine power. Aa reduction of 10^6 from +// validator tokens is applied func (v Validator) ConsensusPower() int64 { if v.IsBonded() { return v.PotentialConsensusPower() @@ -389,7 +357,7 @@ func (v Validator) ConsensusPower() int64 { return 0 } -// potential consensus-engine power +// PotentialConsensusPower returns the potential consensus-engine power. func (v Validator) PotentialConsensusPower() int64 { return sdk.TokensToConsensusPower(v.Tokens) } @@ -501,30 +469,39 @@ func (v Validator) GetOperator() sdk.ValAddress { return addr } -// TmConsPubKey casts Validator.ConsensusPubkey to crypto.PubKey -func (v Validator) TmConsPubKey() (crypto.PubKey, error) { +// ConsPubKey returns the validator PubKey as a cryptotypes.PubKey. +func (v Validator) ConsPubKey() (cryptotypes.PubKey, error) { pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey) if !ok { - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting crypto.PubKey, got %T", pk) + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) + } + + return pk, nil + +} + +// TmConsPublicKey casts Validator.ConsensusPubkey to tmprotocrypto.PubKey. +func (v Validator) TmConsPublicKey() (tmprotocrypto.PublicKey, error) { + pk, err := v.ConsPubKey() + if err != nil { + return tmprotocrypto.PublicKey{}, err } - // The way things are refactored now, v.ConsensusPubkey is sometimes a TM - // ed25519 pubkey, sometimes our own ed25519 pubkey. This is very ugly and - // inconsistent. - // Luckily, here we coerce it into a TM ed25519 pubkey always, as this - // pubkey will be passed into TM (eg calling encoding.PubKeyToProto). - if intoTmPk, ok := pk.(cryptotypes.IntoTmPubKey); ok { - return intoTmPk.AsTmPubKey(), nil + tmPk, err := cryptocodec.ToTmProtoPublicKey(pk) + if err != nil { + return tmprotocrypto.PublicKey{}, err } - return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidPubKey, "Logic error: ConsensusPubkey must be an SDK key and SDK PubKey types must be convertible to tendermint PubKey; got: %T", pk) + + return tmPk, nil } // GetConsAddr extracts Consensus key address func (v Validator) GetConsAddr() (sdk.ConsAddress, error) { - pk, err := v.TmConsPubKey() - if err != nil { - return sdk.ConsAddress{}, err + pk, ok := v.ConsensusPubkey.GetCachedValue().(cryptotypes.PubKey) + if !ok { + return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "expecting cryptotypes.PubKey, got %T", pk) } + return sdk.ConsAddress(pk.Address()), nil } @@ -537,6 +514,6 @@ func (v Validator) GetDelegatorShares() sdk.Dec { return v.DelegatorShares } // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces func (v Validator) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error { - var pk crypto.PubKey + var pk cryptotypes.PubKey return unpacker.UnpackAny(v.ConsensusPubkey, &pk) } diff --git a/x/staking/types/validator_test.go b/x/staking/types/validator_test.go index 64afc97681bd..08204215d595 100644 --- a/x/staking/types/validator_test.go +++ b/x/staking/types/validator_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "math/rand" @@ -7,14 +7,15 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/encoding" tmtypes "github.com/tendermint/tendermint/types" "github.com/cosmos/cosmos-sdk/codec/legacy" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" + "github.com/cosmos/cosmos-sdk/x/staking/types" ) func TestValidatorTestEquivalent(t *testing.T) { @@ -27,19 +28,19 @@ func TestValidatorTestEquivalent(t *testing.T) { } func TestUpdateDescription(t *testing.T) { - d1 := Description{ + d1 := types.Description{ Website: "https://validator.cosmos", Details: "Test validator", } - d2 := Description{ - Moniker: DoNotModifyDesc, - Identity: DoNotModifyDesc, - Website: DoNotModifyDesc, - Details: DoNotModifyDesc, + d2 := types.Description{ + Moniker: types.DoNotModifyDesc, + Identity: types.DoNotModifyDesc, + Website: types.DoNotModifyDesc, + Details: types.DoNotModifyDesc, } - d3 := Description{ + d3 := types.Description{ Moniker: "", Identity: "", Website: "", @@ -58,9 +59,7 @@ func TestUpdateDescription(t *testing.T) { func TestABCIValidatorUpdate(t *testing.T) { validator := newValidator(t, valAddr1, pk1) abciVal := validator.ABCIValidatorUpdate() - consPk, err := validator.TmConsPubKey() - require.NoError(t, err) - pk, err := encoding.PubKeyToProto(consPk) + pk, err := validator.TmConsPublicKey() require.NoError(t, err) require.Equal(t, pk, abciVal.PubKey) require.Equal(t, validator.BondedTokens().Int64(), abciVal.Power) @@ -69,9 +68,7 @@ func TestABCIValidatorUpdate(t *testing.T) { func TestABCIValidatorUpdateZero(t *testing.T) { validator := newValidator(t, valAddr1, pk1) abciVal := validator.ABCIValidatorUpdateZero() - consPk, err := validator.TmConsPubKey() - require.NoError(t, err) - pk, err := encoding.PubKeyToProto(consPk) + pk, err := validator.TmConsPublicKey() require.NoError(t, err) require.Equal(t, pk, abciVal.PubKey) require.Equal(t, int64(0), abciVal.Power) @@ -94,8 +91,8 @@ func TestRemoveTokens(t *testing.T) { require.Equal(t, int64(90), validator.Tokens.Int64()) // update validator to from bonded -> unbonded - validator = validator.UpdateStatus(Unbonded) - require.Equal(t, Unbonded, validator.Status) + validator = validator.UpdateStatus(types.Unbonded) + require.Equal(t, types.Unbonded, validator.Status) validator = validator.RemoveTokens(sdk.NewInt(10)) require.Panics(t, func() { validator.RemoveTokens(sdk.NewInt(-1)) }) @@ -104,7 +101,7 @@ func TestRemoveTokens(t *testing.T) { func TestAddTokensValidatorBonded(t *testing.T) { validator := newValidator(t, valAddr1, pk1) - validator = validator.UpdateStatus(Bonded) + validator = validator.UpdateStatus(types.Bonded) validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10)) assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) @@ -114,11 +111,11 @@ func TestAddTokensValidatorBonded(t *testing.T) { func TestAddTokensValidatorUnbonding(t *testing.T) { validator := newValidator(t, valAddr1, pk1) - validator = validator.UpdateStatus(Unbonding) + validator = validator.UpdateStatus(types.Unbonding) validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10)) assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) - assert.Equal(t, Unbonding, validator.Status) + assert.Equal(t, types.Unbonding, validator.Status) assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) } @@ -126,21 +123,21 @@ func TestAddTokensValidatorUnbonding(t *testing.T) { func TestAddTokensValidatorUnbonded(t *testing.T) { validator := newValidator(t, valAddr1, pk1) - validator = validator.UpdateStatus(Unbonded) + validator = validator.UpdateStatus(types.Unbonded) validator, delShares := validator.AddTokensFromDel(sdk.NewInt(10)) assert.True(sdk.DecEq(t, sdk.NewDec(10), delShares)) - assert.Equal(t, Unbonded, validator.Status) + assert.Equal(t, types.Unbonded, validator.Status) assert.True(sdk.IntEq(t, sdk.NewInt(10), validator.Tokens)) assert.True(sdk.DecEq(t, sdk.NewDec(10), validator.DelegatorShares)) } // TODO refactor to make simpler like the AddToken tests above func TestRemoveDelShares(t *testing.T) { - valA := Validator{ + valA := types.Validator{ OperatorAddress: valAddr1.String(), ConsensusPubkey: pk1Any, - Status: Bonded, + Status: types.Bonded, Tokens: sdk.NewInt(100), DelegatorShares: sdk.NewDec(100), } @@ -175,20 +172,20 @@ func TestAddTokensFromDel(t *testing.T) { func TestUpdateStatus(t *testing.T) { validator := newValidator(t, valAddr1, pk1) validator, _ = validator.AddTokensFromDel(sdk.NewInt(100)) - require.Equal(t, Unbonded, validator.Status) + require.Equal(t, types.Unbonded, validator.Status) require.Equal(t, int64(100), validator.Tokens.Int64()) // Unbonded to Bonded - validator = validator.UpdateStatus(Bonded) - require.Equal(t, Bonded, validator.Status) + validator = validator.UpdateStatus(types.Bonded) + require.Equal(t, types.Bonded, validator.Status) // Bonded to Unbonding - validator = validator.UpdateStatus(Unbonding) - require.Equal(t, Unbonding, validator.Status) + validator = validator.UpdateStatus(types.Unbonding) + require.Equal(t, types.Unbonding, validator.Status) // Unbonding to Bonded - validator = validator.UpdateStatus(Bonded) - require.Equal(t, Bonded, validator.Status) + validator = validator.UpdateStatus(types.Bonded) + require.Equal(t, types.Bonded, validator.Status) } func TestPossibleOverflow(t *testing.T) { @@ -205,8 +202,8 @@ func TestValidatorMarshalUnmarshalJSON(t *testing.T) { js, err := legacy.Cdc.MarshalJSON(validator) require.NoError(t, err) require.NotEmpty(t, js) - require.Contains(t, string(js), "\"consensus_pubkey\":{\"type\":\"cosmos/PubKeyEd25519\"") - got := &Validator{} + require.Contains(t, string(js), "\"consensus_pubkey\":{\"type\":\"tendermint/PubKeyEd25519\"") + got := &types.Validator{} err = legacy.Cdc.UnmarshalJSON(js, got) assert.NoError(t, err) assert.True(t, validator.Equal(got)) @@ -215,17 +212,17 @@ func TestValidatorMarshalUnmarshalJSON(t *testing.T) { func TestValidatorSetInitialCommission(t *testing.T) { val := newValidator(t, valAddr1, pk1) testCases := []struct { - validator Validator - commission Commission + validator types.Validator + commission types.Commission expectedErr bool }{ - {val, NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), false}, - {val, NewCommission(sdk.ZeroDec(), sdk.NewDecWithPrec(-1, 1), sdk.ZeroDec()), true}, - {val, NewCommission(sdk.ZeroDec(), sdk.NewDec(15000000000), sdk.ZeroDec()), true}, - {val, NewCommission(sdk.NewDecWithPrec(-1, 1), sdk.ZeroDec(), sdk.ZeroDec()), true}, - {val, NewCommission(sdk.NewDecWithPrec(2, 1), sdk.NewDecWithPrec(1, 1), sdk.ZeroDec()), true}, - {val, NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.NewDecWithPrec(-1, 1)), true}, - {val, NewCommission(sdk.ZeroDec(), sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(2, 1)), true}, + {val, types.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), false}, + {val, types.NewCommission(sdk.ZeroDec(), sdk.NewDecWithPrec(-1, 1), sdk.ZeroDec()), true}, + {val, types.NewCommission(sdk.ZeroDec(), sdk.NewDec(15000000000), sdk.ZeroDec()), true}, + {val, types.NewCommission(sdk.NewDecWithPrec(-1, 1), sdk.ZeroDec(), sdk.ZeroDec()), true}, + {val, types.NewCommission(sdk.NewDecWithPrec(2, 1), sdk.NewDecWithPrec(1, 1), sdk.ZeroDec()), true}, + {val, types.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.NewDecWithPrec(-1, 1)), true}, + {val, types.NewCommission(sdk.ZeroDec(), sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(2, 1)), true}, } for i, tc := range testCases { @@ -248,8 +245,8 @@ func TestValidatorSetInitialCommission(t *testing.T) { // Check that sort will create deterministic ordering of validators func TestValidatorsSortDeterminism(t *testing.T) { - vals := make([]Validator, 10) - sortedVals := make([]Validator, 10) + vals := make([]types.Validator, 10) + sortedVals := make([]types.Validator, 10) // Create random validator slice for i := range vals { @@ -258,7 +255,7 @@ func TestValidatorsSortDeterminism(t *testing.T) { } // Save sorted copy - sort.Sort(Validators(vals)) + sort.Sort(types.Validators(vals)) copy(sortedVals, vals) // Randomly shuffle validators, sort, and check it is equal to original sort @@ -269,20 +266,20 @@ func TestValidatorsSortDeterminism(t *testing.T) { vals[j] = it }) - Validators(vals).Sort() + types.Validators(vals).Sort() require.Equal(t, sortedVals, vals, "Validator sort returned different slices") } } // Check SortTendermint sorts the same as tendermint func TestValidatorsSortTendermint(t *testing.T) { - vals := make([]Validator, 100) + vals := make([]types.Validator, 100) for i := range vals { pk := ed25519.GenPrivKey().PubKey() pk2 := ed25519.GenPrivKey().PubKey() vals[i] = newValidator(t, sdk.ValAddress(pk2.Address()), pk) - vals[i].Status = Bonded + vals[i].Status = types.Bonded vals[i].Tokens = sdk.NewInt(rand.Int63()) } // create some validators with the same power @@ -290,62 +287,64 @@ func TestValidatorsSortTendermint(t *testing.T) { vals[i].Tokens = sdk.NewInt(1000000) } - valz := Validators(vals) + valz := types.Validators(vals) // create expected tendermint validators by converting to tendermint then sorting - expectedVals, err := valz.ToTmValidators() + expectedVals, err := teststaking.ToTmValidators(valz) require.NoError(t, err) sort.Sort(tmtypes.ValidatorsByVotingPower(expectedVals)) // sort in SDK and then convert to tendermint - sort.Sort(ValidatorsByVotingPower(valz)) - actualVals, err := valz.ToTmValidators() + sort.Sort(types.ValidatorsByVotingPower(valz)) + actualVals, err := teststaking.ToTmValidators(valz) require.NoError(t, err) require.Equal(t, expectedVals, actualVals, "sorting in SDK is not the same as sorting in Tendermint") } func TestValidatorToTm(t *testing.T) { - vals := make(Validators, 10) + vals := make(types.Validators, 10) expected := make([]*tmtypes.Validator, 10) for i := range vals { pk := ed25519.GenPrivKey().PubKey() val := newValidator(t, sdk.ValAddress(pk.Address()), pk) - val.Status = Bonded + val.Status = types.Bonded val.Tokens = sdk.NewInt(rand.Int63()) vals[i] = val - expected[i] = tmtypes.NewValidator(pk.(cryptotypes.IntoTmPubKey).AsTmPubKey(), val.ConsensusPower()) + tmPk, err := cryptocodec.ToTmPubKeyInterface(pk) + require.NoError(t, err) + expected[i] = tmtypes.NewValidator(tmPk, val.ConsensusPower()) } - vs, err := vals.ToTmValidators() + vs, err := teststaking.ToTmValidators(vals) require.NoError(t, err) require.Equal(t, expected, vs) } func TestBondStatus(t *testing.T) { - require.False(t, Unbonded == Bonded) - require.False(t, Unbonded == Unbonding) - require.False(t, Bonded == Unbonding) - require.Equal(t, BondStatus(4).String(), "4") - require.Equal(t, BondStatusUnspecified, Unspecified.String()) - require.Equal(t, BondStatusUnbonded, Unbonded.String()) - require.Equal(t, BondStatusBonded, Bonded.String()) - require.Equal(t, BondStatusUnbonding, Unbonding.String()) + require.False(t, types.Unbonded == types.Bonded) + require.False(t, types.Unbonded == types.Unbonding) + require.False(t, types.Bonded == types.Unbonding) + require.Equal(t, types.BondStatus(4).String(), "4") + require.Equal(t, types.BondStatusUnspecified, types.Unspecified.String()) + require.Equal(t, types.BondStatusUnbonded, types.Unbonded.String()) + require.Equal(t, types.BondStatusBonded, types.Bonded.String()) + require.Equal(t, types.BondStatusUnbonding, types.Unbonding.String()) } -func mkValidator(tokens int64, shares sdk.Dec) Validator { - return Validator{ +func mkValidator(tokens int64, shares sdk.Dec) types.Validator { + return types.Validator{ OperatorAddress: valAddr1.String(), ConsensusPubkey: pk1Any, - Status: Bonded, + Status: types.Bonded, Tokens: sdk.NewInt(tokens), DelegatorShares: shares, } } // Creates a new validators and asserts the error check. -func newValidator(t *testing.T, operator sdk.ValAddress, pubKey crypto.PubKey) Validator { - v, err := NewValidator(operator, pubKey, Description{}) +func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) types.Validator { + v, err := types.NewValidator(operator, pubKey, types.Description{}) require.NoError(t, err) return v }