From fb3e0af0b6320838c1da8531deba6c6a542c376a Mon Sep 17 00:00:00 2001 From: Federico Kunze <31522760+fedekunze@users.noreply.github.com> Date: Mon, 29 Jul 2019 17:27:01 +0200 Subject: [PATCH] Merge PR #4760: update x/auth to match module spec --- .../improvements/modules/_4760-update-auth | 1 + client/cmd_test.go | 1 + x/auth/alias.go | 105 +++++--- x/auth/{ => ante}/ante.go | 47 ++-- x/auth/{ => ante}/ante_test.go | 240 +++++++++--------- x/auth/keeper.go | 195 -------------- x/auth/keeper/account.go | 80 ++++++ x/auth/keeper/keeper.go | 100 ++++++++ x/auth/{ => keeper}/keeper_bench_test.go | 30 +-- x/auth/keeper/keeper_test.go | 91 +++++++ x/auth/keeper/params.go | 17 ++ x/auth/{ => keeper}/querier.go | 4 +- x/auth/keeper/querier_test.go | 60 +++++ x/auth/{ => keeper}/test_common.go | 18 +- x/auth/keeper_test.go | 90 ------- x/auth/querier_test.go | 44 ---- x/mock/app.go | 9 +- x/slashing/internal/types/expected_keepers.go | 14 +- x/staking/types/expected_keepers.go | 4 +- x/supply/genesis.go | 4 +- x/supply/internal/keeper/common_test.go | 3 +- 21 files changed, 603 insertions(+), 554 deletions(-) create mode 100644 .pending/improvements/modules/_4760-update-auth rename x/auth/{ => ante}/ante.go (88%) rename x/auth/{ => ante}/ante_test.go (76%) delete mode 100644 x/auth/keeper.go create mode 100644 x/auth/keeper/account.go create mode 100644 x/auth/keeper/keeper.go rename x/auth/{ => keeper}/keeper_bench_test.go (72%) create mode 100644 x/auth/keeper/keeper_test.go create mode 100644 x/auth/keeper/params.go rename x/auth/{ => keeper}/querier.go (94%) create mode 100644 x/auth/keeper/querier_test.go rename x/auth/{ => keeper}/test_common.go (93%) delete mode 100644 x/auth/keeper_test.go delete mode 100644 x/auth/querier_test.go diff --git a/.pending/improvements/modules/_4760-update-auth b/.pending/improvements/modules/_4760-update-auth new file mode 100644 index 000000000..f200d78a6 --- /dev/null +++ b/.pending/improvements/modules/_4760-update-auth @@ -0,0 +1 @@ +#4760 update `x/auth` to match module spec diff --git a/client/cmd_test.go b/client/cmd_test.go index 3ca286f64..ea71399a6 100644 --- a/client/cmd_test.go +++ b/client/cmd_test.go @@ -1,3 +1,4 @@ +// nolint: misspell package client_test import ( diff --git a/x/auth/alias.go b/x/auth/alias.go index 2f129ea30..e4ba5e68f 100644 --- a/x/auth/alias.go +++ b/x/auth/alias.go @@ -1,11 +1,15 @@ // nolint // autogenerated code using github.com/rigelrozanski/multitool // aliases generated for the following subdirectories: +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/ante +// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/keeper // ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/types package auth import ( + "github.com/cosmos/cosmos-sdk/x/auth/ante" "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -25,33 +29,46 @@ const ( var ( // functions aliases - NewBaseAccount = types.NewBaseAccount - ProtoBaseAccount = types.ProtoBaseAccount - NewBaseAccountWithAddress = types.NewBaseAccountWithAddress - NewBaseVestingAccount = types.NewBaseVestingAccount - NewContinuousVestingAccountRaw = types.NewContinuousVestingAccountRaw - NewContinuousVestingAccount = types.NewContinuousVestingAccount - NewDelayedVestingAccountRaw = types.NewDelayedVestingAccountRaw - NewDelayedVestingAccount = types.NewDelayedVestingAccount - RegisterCodec = types.RegisterCodec - NewGenesisState = types.NewGenesisState - DefaultGenesisState = types.DefaultGenesisState - ValidateGenesis = types.ValidateGenesis - AddressStoreKey = types.AddressStoreKey - NewParams = types.NewParams - ParamKeyTable = types.ParamKeyTable - DefaultParams = types.DefaultParams - NewQueryAccountParams = types.NewQueryAccountParams - NewStdTx = types.NewStdTx - CountSubKeys = types.CountSubKeys - NewStdFee = types.NewStdFee - StdSignBytes = types.StdSignBytes - DefaultTxDecoder = types.DefaultTxDecoder - DefaultTxEncoder = types.DefaultTxEncoder - NewTxBuilder = types.NewTxBuilder - NewTxBuilderFromCLI = types.NewTxBuilderFromCLI - MakeSignature = types.MakeSignature - NewAccountRetriever = types.NewAccountRetriever + NewAnteHandler = ante.NewAnteHandler + GetSignerAcc = ante.GetSignerAcc + ValidateSigCount = ante.ValidateSigCount + ValidateMemo = ante.ValidateMemo + ProcessPubKey = ante.ProcessPubKey + DefaultSigVerificationGasConsumer = ante.DefaultSigVerificationGasConsumer + DeductFees = ante.DeductFees + EnsureSufficientMempoolFees = ante.EnsureSufficientMempoolFees + SetGasMeter = ante.SetGasMeter + GetSignBytes = ante.GetSignBytes + NewAccountKeeper = keeper.NewAccountKeeper + NewDummySupplyKeeper = keeper.NewDummySupplyKeeper + NewQuerier = keeper.NewQuerier + NewBaseAccount = types.NewBaseAccount + ProtoBaseAccount = types.ProtoBaseAccount + NewBaseAccountWithAddress = types.NewBaseAccountWithAddress + NewBaseVestingAccount = types.NewBaseVestingAccount + NewContinuousVestingAccountRaw = types.NewContinuousVestingAccountRaw + NewContinuousVestingAccount = types.NewContinuousVestingAccount + NewDelayedVestingAccountRaw = types.NewDelayedVestingAccountRaw + NewDelayedVestingAccount = types.NewDelayedVestingAccount + NewAccountRetriever = types.NewAccountRetriever + RegisterCodec = types.RegisterCodec + NewGenesisState = types.NewGenesisState + DefaultGenesisState = types.DefaultGenesisState + ValidateGenesis = types.ValidateGenesis + AddressStoreKey = types.AddressStoreKey + NewParams = types.NewParams + ParamKeyTable = types.ParamKeyTable + DefaultParams = types.DefaultParams + NewQueryAccountParams = types.NewQueryAccountParams + NewStdTx = types.NewStdTx + CountSubKeys = types.CountSubKeys + NewStdFee = types.NewStdFee + StdSignBytes = types.StdSignBytes + DefaultTxDecoder = types.DefaultTxDecoder + DefaultTxEncoder = types.DefaultTxEncoder + NewTxBuilder = types.NewTxBuilder + NewTxBuilderFromCLI = types.NewTxBuilderFromCLI + MakeSignature = types.MakeSignature // variable aliases ModuleCdc = types.ModuleCdc @@ -65,19 +82,23 @@ var ( ) type ( - Account = exported.Account - VestingAccount = exported.VestingAccount - BaseAccount = types.BaseAccount - BaseVestingAccount = types.BaseVestingAccount - ContinuousVestingAccount = types.ContinuousVestingAccount - DelayedVestingAccount = types.DelayedVestingAccount - GenesisState = types.GenesisState - Params = types.Params - QueryAccountParams = types.QueryAccountParams - StdSignMsg = types.StdSignMsg - StdTx = types.StdTx - StdFee = types.StdFee - StdSignDoc = types.StdSignDoc - StdSignature = types.StdSignature - TxBuilder = types.TxBuilder + SignatureVerificationGasConsumer = ante.SignatureVerificationGasConsumer + Account = exported.Account + VestingAccount = exported.VestingAccount + AccountKeeper = keeper.AccountKeeper + BaseAccount = types.BaseAccount + BaseVestingAccount = types.BaseVestingAccount + ContinuousVestingAccount = types.ContinuousVestingAccount + DelayedVestingAccount = types.DelayedVestingAccount + NodeQuerier = types.NodeQuerier + AccountRetriever = types.AccountRetriever + GenesisState = types.GenesisState + Params = types.Params + QueryAccountParams = types.QueryAccountParams + StdSignMsg = types.StdSignMsg + StdTx = types.StdTx + StdFee = types.StdFee + StdSignDoc = types.StdSignDoc + StdSignature = types.StdSignature + TxBuilder = types.TxBuilder ) diff --git a/x/auth/ante.go b/x/auth/ante/ante.go similarity index 88% rename from x/auth/ante.go rename to x/auth/ante/ante.go index 9387b07ec..457dba893 100644 --- a/x/auth/ante.go +++ b/x/auth/ante/ante.go @@ -1,4 +1,4 @@ -package auth +package ante import ( "bytes" @@ -13,6 +13,8 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -30,12 +32,12 @@ func init() { // SignatureVerificationGasConsumer is the type of function that is used to both consume gas when verifying signatures // and also to accept or reject different types of PubKey's. This is where apps can define their own PubKey -type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result +type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) sdk.Result // NewAnteHandler returns an AnteHandler that checks and increments sequence // numbers, checks signatures & account numbers, and deducts fees from the first // signer. -func NewAnteHandler(ak AccountKeeper, supplyKeeper types.SupplyKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { +func NewAnteHandler(ak keeper.AccountKeeper, supplyKeeper types.SupplyKeeper, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler { return func( ctx sdk.Context, tx sdk.Tx, simulate bool, ) (newCtx sdk.Context, res sdk.Result, abort bool) { @@ -45,7 +47,7 @@ func NewAnteHandler(ak AccountKeeper, supplyKeeper types.SupplyKeeper, sigGasCon } // all transactions must be of type auth.StdTx - stdTx, ok := tx.(StdTx) + stdTx, ok := tx.(types.StdTx) if !ok { // Set a gas meter with limit 0 as to prevent an infinite gas meter attack // during runTx. @@ -107,7 +109,7 @@ func NewAnteHandler(ak AccountKeeper, supplyKeeper types.SupplyKeeper, sigGasCon // stdSigs contains the sequence number, account number, and signatures. // When simulating, this would just be a 0-length slice. signerAddrs := stdTx.GetSigners() - signerAccs := make([]Account, len(signerAddrs)) + signerAccs := make([]exported.Account, len(signerAddrs)) isGenesis := ctx.BlockHeight() == 0 // fetch first signer, who's going to pay the fees @@ -150,14 +152,13 @@ func NewAnteHandler(ak AccountKeeper, supplyKeeper types.SupplyKeeper, sigGasCon ak.SetAccount(newCtx, signerAccs[i]) } - // TODO: tx tags (?) return newCtx, sdk.Result{GasWanted: stdTx.Fee.Gas}, false // continue... } } // GetSignerAcc returns an account for a given address that is expected to sign // a transaction. -func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (Account, sdk.Result) { +func GetSignerAcc(ctx sdk.Context, ak keeper.AccountKeeper, addr sdk.AccAddress) (exported.Account, sdk.Result) { if acc := ak.GetAccount(ctx, addr); acc != nil { return acc, sdk.Result{} } @@ -166,12 +167,12 @@ func GetSignerAcc(ctx sdk.Context, ak AccountKeeper, addr sdk.AccAddress) (Accou // ValidateSigCount validates that the transaction has a valid cumulative total // amount of signatures. -func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { +func ValidateSigCount(stdTx types.StdTx, params types.Params) sdk.Result { stdSigs := stdTx.GetSignatures() sigCount := 0 for i := 0; i < len(stdSigs); i++ { - sigCount += CountSubKeys(stdSigs[i].PubKey) + sigCount += types.CountSubKeys(stdSigs[i].PubKey) if uint64(sigCount) > params.TxSigLimit { return sdk.ErrTooManySignatures( fmt.Sprintf("signatures: %d, limit: %d", sigCount, params.TxSigLimit), @@ -183,7 +184,7 @@ func ValidateSigCount(stdTx StdTx, params Params) sdk.Result { } // ValidateMemo validates the memo size. -func ValidateMemo(stdTx StdTx, params Params) sdk.Result { +func ValidateMemo(stdTx types.StdTx, params types.Params) sdk.Result { memoLength := len(stdTx.GetMemo()) if uint64(memoLength) > params.MaxMemoCharacters { return sdk.ErrMemoTooLarge( @@ -200,9 +201,9 @@ func ValidateMemo(stdTx StdTx, params Params) sdk.Result { // verify the signature and increment the sequence. If the account doesn't have // a pubkey, set it. func processSig( - ctx sdk.Context, acc Account, sig StdSignature, signBytes []byte, simulate bool, params Params, + ctx sdk.Context, acc exported.Account, sig types.StdSignature, signBytes []byte, simulate bool, params types.Params, sigGasConsumer SignatureVerificationGasConsumer, -) (updatedAcc Account, res sdk.Result) { +) (updatedAcc exported.Account, res sdk.Result) { pubKey, res := ProcessPubKey(acc, sig, simulate) if !res.IsOK() { @@ -237,13 +238,13 @@ func processSig( return acc, res } -func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignature, params Params) { - simSig := StdSignature{PubKey: pubkey} +func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig types.StdSignature, params types.Params) { + simSig := types.StdSignature{PubKey: pubkey} if len(sig.Signature) == 0 { simSig.Signature = simSecp256k1Sig[:] } - sigBz := ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) + sigBz := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig) cost := sdk.Gas(len(sigBz) + 6) // If the pubkey is a multi-signature pubkey, then we estimate for the maximum @@ -258,8 +259,8 @@ func consumeSimSigGas(gasmeter sdk.GasMeter, pubkey crypto.PubKey, sig StdSignat // ProcessPubKey verifies that the given account address matches that of the // StdSignature. In addition, it will set the public key of the account if it // has not been set. -func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { - // If pubkey is not known for account, set it from the StdSignature. +func ProcessPubKey(acc exported.Account, sig types.StdSignature, simulate bool) (crypto.PubKey, sdk.Result) { + // If pubkey is not known for account, set it from the types.StdSignature. pubKey := acc.GetPubKey() if simulate { // In simulate mode the transaction comes with no signatures, thus if the @@ -292,7 +293,7 @@ func ProcessPubKey(acc Account, sig StdSignature, simulate bool) (crypto.PubKey, // for signature verification based upon the public key type. The cost is fetched from the given params and is matched // by the concrete type. func DefaultSigVerificationGasConsumer( - meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params, + meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params, ) sdk.Result { switch pubkey := pubkey.(type) { case ed25519.PubKeyEd25519: @@ -317,7 +318,7 @@ func DefaultSigVerificationGasConsumer( func consumeMultisignatureVerificationGas(meter sdk.GasMeter, sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold, - params Params) { + params types.Params) { size := sig.BitArray.Size() sigIndex := 0 @@ -333,7 +334,7 @@ func consumeMultisignatureVerificationGas(meter sdk.GasMeter, // // NOTE: We could use the CoinKeeper (in addition to the AccountKeeper, because // the CoinKeeper doesn't give us accounts), but it seems easier to do this. -func DeductFees(supplyKeeper types.SupplyKeeper, ctx sdk.Context, acc Account, fees sdk.Coins) sdk.Result { +func DeductFees(supplyKeeper types.SupplyKeeper, ctx sdk.Context, acc exported.Account, fees sdk.Coins) sdk.Result { blockTime := ctx.BlockHeader().Time coins := acc.GetCoins() @@ -372,7 +373,7 @@ func DeductFees(supplyKeeper types.SupplyKeeper, ctx sdk.Context, acc Account, f // // Contract: This should only be called during CheckTx as it cannot be part of // consensus. -func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee StdFee) sdk.Result { +func EnsureSufficientMempoolFees(ctx sdk.Context, stdFee types.StdFee) sdk.Result { minGasPrices := ctx.MinGasPrices() if !minGasPrices.IsZero() { requiredFees := make(sdk.Coins, len(minGasPrices)) @@ -410,13 +411,13 @@ func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context { // GetSignBytes returns a slice of bytes to sign over for a given transaction // and an account. -func GetSignBytes(chainID string, stdTx StdTx, acc Account, genesis bool) []byte { +func GetSignBytes(chainID string, stdTx types.StdTx, acc exported.Account, genesis bool) []byte { var accNum uint64 if !genesis { accNum = acc.GetAccountNumber() } - return StdSignBytes( + return types.StdSignBytes( chainID, accNum, acc.GetSequence(), stdTx.Fee, stdTx.Msgs, stdTx.Memo, ) } diff --git a/x/auth/ante_test.go b/x/auth/ante/ante_test.go similarity index 76% rename from x/auth/ante_test.go rename to x/auth/ante/ante_test.go index 4faae8ea9..218204185 100644 --- a/x/auth/ante_test.go +++ b/x/auth/ante/ante_test.go @@ -1,4 +1,4 @@ -package auth +package ante import ( "fmt" @@ -13,6 +13,8 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/keeper" "github.com/cosmos/cosmos-sdk/x/auth/types" ) @@ -47,9 +49,9 @@ func checkInvalidTx(t *testing.T, anteHandler sdk.AnteHandler, ctx sdk.Context, // Test various error cases in the AnteHandler control flow. func TestAnteHandlerSigErrors(t *testing.T) { // setup - input := setupTestInput() - ctx := input.ctx - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) + input := keeper.SetupTestInput() + ctx := input.Ctx + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() @@ -87,32 +89,32 @@ func TestAnteHandlerSigErrors(t *testing.T) { checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnknownAddress) // save the first account, but second is still unrecognized - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(fee.Amount) - input.ak.SetAccount(ctx, acc1) + input.AccountKeeper.SetAccount(ctx, acc1) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeUnknownAddress) } // Test logic around account number checking with one signer and many signers. func TestAnteHandlerAccountNumbers(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() priv2, _, addr2 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx @@ -153,22 +155,22 @@ func TestAnteHandlerAccountNumbers(t *testing.T) { // Test logic around account number checking with many signers when BlockHeight is 0. func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(0) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(0) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() priv2, _, addr2 := types.KeyTestPubAddr() // set the accounts, we don't need the acc numbers as it is in the genesis block - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) // msg and signatures var tx sdk.Tx @@ -209,9 +211,9 @@ func TestAnteHandlerAccountNumbersAtBlockHeightZero(t *testing.T) { // Test logic around sequence checking with one signer and many signers. func TestAnteHandlerSequences(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() @@ -219,18 +221,18 @@ func TestAnteHandlerSequences(t *testing.T) { priv3, _, addr3 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) - acc3 := input.ak.NewAccountWithAddress(ctx, addr3) + input.AccountKeeper.SetAccount(ctx, acc2) + acc3 := input.AccountKeeper.NewAccountWithAddress(ctx, addr3) acc3.SetCoins(types.NewTestCoins()) require.NoError(t, acc3.SetAccountNumber(2)) - input.ak.SetAccount(ctx, acc3) + input.AccountKeeper.SetAccount(ctx, acc3) // msg and signatures var tx sdk.Tx @@ -286,16 +288,16 @@ func TestAnteHandlerSequences(t *testing.T) { // Test logic around fee deduction. func TestAnteHandlerFees(t *testing.T) { // setup - input := setupTestInput() - ctx := input.ctx - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) + input := keeper.SetupTestInput() + ctx := input.Ctx + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - input.ak.SetAccount(ctx, acc1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) + input.AccountKeeper.SetAccount(ctx, acc1) // msg and signatures var tx sdk.Tx @@ -309,66 +311,66 @@ func TestAnteHandlerFees(t *testing.T) { checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 149))) - input.ak.SetAccount(ctx, acc1) + input.AccountKeeper.SetAccount(ctx, acc1) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInsufficientFunds) - require.True(t, input.sk.GetModuleAccount(ctx, types.FeeCollectorName).GetCoins().Empty()) - require.True(sdk.IntEq(t, input.ak.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), sdk.NewInt(149))) + require.True(t, input.SupplyKeeper.GetModuleAccount(ctx, types.FeeCollectorName).GetCoins().Empty()) + require.True(sdk.IntEq(t, input.AccountKeeper.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), sdk.NewInt(149))) acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) - input.ak.SetAccount(ctx, acc1) + input.AccountKeeper.SetAccount(ctx, acc1) checkValidTx(t, anteHandler, ctx, tx, false) - require.True(sdk.IntEq(t, input.sk.GetModuleAccount(ctx, types.FeeCollectorName).GetCoins().AmountOf("atom"), sdk.NewInt(150))) - require.True(sdk.IntEq(t, input.ak.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), sdk.NewInt(0))) + require.True(sdk.IntEq(t, input.SupplyKeeper.GetModuleAccount(ctx, types.FeeCollectorName).GetCoins().AmountOf("atom"), sdk.NewInt(150))) + require.True(sdk.IntEq(t, input.AccountKeeper.GetAccount(ctx, addr1).GetCoins().AmountOf("atom"), sdk.NewInt(0))) } // Test logic around memo gas consumption. func TestAnteHandlerMemoGas(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) + input.AccountKeeper.SetAccount(ctx, acc1) // msg and signatures var tx sdk.Tx msg := types.NewTestMsg(addr1) privs, accnums, seqs := []crypto.PrivKey{priv1}, []uint64{0}, []uint64{0} - fee := NewStdFee(0, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) + fee := types.NewStdFee(0, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) // tx does not have enough gas tx = types.NewTestTx(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // tx with memo doesn't have enough gas - fee = NewStdFee(801, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) + fee = types.NewStdFee(801, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, "abcininasidniandsinasindiansdiansdinaisndiasndiadninsd") checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeOutOfGas) // memo too large - fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) + fee = types.NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("01234567890", 500)) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeMemoTooLarge) // tx with memo has enough gas - fee = NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) + fee = types.NewStdFee(9000, sdk.NewCoins(sdk.NewInt64Coin("atom", 0))) tx = types.NewTestTxWithMemo(ctx, []sdk.Msg{msg}, privs, accnums, seqs, fee, strings.Repeat("0123456789", 10)) checkValidTx(t, anteHandler, ctx, tx, false) } func TestAnteHandlerMultiSigner(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() @@ -376,18 +378,18 @@ func TestAnteHandlerMultiSigner(t *testing.T) { priv3, _, addr3 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) - acc3 := input.ak.NewAccountWithAddress(ctx, addr3) + input.AccountKeeper.SetAccount(ctx, acc2) + acc3 := input.AccountKeeper.NewAccountWithAddress(ctx, addr3) acc3.SetCoins(types.NewTestCoins()) require.NoError(t, acc3.SetAccountNumber(2)) - input.ak.SetAccount(ctx, acc3) + input.AccountKeeper.SetAccount(ctx, acc3) // set up msgs and fee var tx sdk.Tx @@ -416,23 +418,23 @@ func TestAnteHandlerMultiSigner(t *testing.T) { func TestAnteHandlerBadSignBytes(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() priv2, _, addr2 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) var tx sdk.Tx msg := types.NewTestMsg(addr1) @@ -456,7 +458,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { chainID string accnum uint64 seq uint64 - fee StdFee + fee types.StdFee msgs []sdk.Msg code sdk.CodeType }{ @@ -472,7 +474,7 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { for _, cs := range cases { tx := types.NewTestTxWithSignBytes( msgs, privs, accnums, seqs, fee, - StdSignBytes(cs.chainID, cs.accnum, cs.seq, cs.fee, cs.msgs, ""), + types.StdSignBytes(cs.chainID, cs.accnum, cs.seq, cs.fee, cs.msgs, ""), "", ) checkInvalidTx(t, anteHandler, ctx, tx, false, cs.code) @@ -493,23 +495,23 @@ func TestAnteHandlerBadSignBytes(t *testing.T) { func TestAnteHandlerSetPubKey(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() _, _, addr2 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) require.NoError(t, acc1.SetAccountNumber(0)) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) var tx sdk.Tx @@ -521,7 +523,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) { tx = types.NewTestTx(ctx, msgs, privs, accnums, seqs, fee) checkValidTx(t, anteHandler, ctx, tx, false) - acc1 = input.ak.GetAccount(ctx, addr1) + acc1 = input.AccountKeeper.GetAccount(ctx, addr1) require.Equal(t, acc1.GetPubKey(), priv1.PubKey()) // test public key not found @@ -532,32 +534,32 @@ func TestAnteHandlerSetPubKey(t *testing.T) { sigs[0].PubKey = nil checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) - acc2 = input.ak.GetAccount(ctx, addr2) + acc2 = input.AccountKeeper.GetAccount(ctx, addr2) require.Nil(t, acc2.GetPubKey()) // test invalid signature and public key tx = types.NewTestTx(ctx, msgs, privs, []uint64{1}, seqs, fee) checkInvalidTx(t, anteHandler, ctx, tx, false, sdk.CodeInvalidPubKey) - acc2 = input.ak.GetAccount(ctx, addr2) + acc2 = input.AccountKeeper.GetAccount(ctx, addr2) require.Nil(t, acc2.GetPubKey()) } func TestProcessPubKey(t *testing.T) { - input := setupTestInput() - ctx := input.ctx + input := keeper.SetupTestInput() + ctx := input.Ctx // keys _, _, addr1 := types.KeyTestPubAddr() priv2, _, addr2 := types.KeyTestPubAddr() - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetPubKey(priv2.PubKey()) type args struct { - acc Account - sig StdSignature + acc exported.Account + sig types.StdSignature simulate bool } tests := []struct { @@ -565,11 +567,11 @@ func TestProcessPubKey(t *testing.T) { args args wantErr bool }{ - {"no sigs, simulate off", args{acc1, StdSignature{}, false}, true}, - {"no sigs, simulate on", args{acc1, StdSignature{}, true}, false}, - {"no sigs, account with pub, simulate on", args{acc2, StdSignature{}, true}, false}, - {"pubkey doesn't match addr, simulate off", args{acc1, StdSignature{PubKey: priv2.PubKey()}, false}, true}, - {"pubkey doesn't match addr, simulate on", args{acc1, StdSignature{PubKey: priv2.PubKey()}, true}, false}, + {"no sigs, simulate off", args{acc1, types.StdSignature{}, false}, true}, + {"no sigs, simulate on", args{acc1, types.StdSignature{}, true}, false}, + {"no sigs, account with pub, simulate on", args{acc2, types.StdSignature{}, true}, false}, + {"pubkey doesn't match addr, simulate off", args{acc1, types.StdSignature{PubKey: priv2.PubKey()}, false}, true}, + {"pubkey doesn't match addr, simulate on", args{acc1, types.StdSignature{PubKey: priv2.PubKey()}, true}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -580,7 +582,7 @@ func TestProcessPubKey(t *testing.T) { } func TestConsumeSignatureVerificationGas(t *testing.T) { - params := DefaultParams() + params := types.DefaultParams() msg := []byte{1, 2, 3, 4} pkSet1, sigSet1 := generatePubKeysAndSignatures(5, msg, false) @@ -595,7 +597,7 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { meter sdk.GasMeter sig []byte pubkey crypto.PubKey - params Params + params types.Params } tests := []struct { name string @@ -603,8 +605,8 @@ func TestConsumeSignatureVerificationGas(t *testing.T) { gasConsumed uint64 shouldErr bool }{ - {"PubKeyEd25519", args{sdk.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, DefaultSigVerifyCostED25519, true}, - {"PubKeySecp256k1", args{sdk.NewInfiniteGasMeter(), nil, secp256k1.GenPrivKey().PubKey(), params}, DefaultSigVerifyCostSecp256k1, false}, + {"PubKeyEd25519", args{sdk.NewInfiniteGasMeter(), nil, ed25519.GenPrivKey().PubKey(), params}, types.DefaultSigVerifyCostED25519, true}, + {"PubKeySecp256k1", args{sdk.NewInfiniteGasMeter(), nil, secp256k1.GenPrivKey().PubKey(), params}, types.DefaultSigVerifyCostSecp256k1, false}, {"Multisig", args{sdk.NewInfiniteGasMeter(), multisignature1.Marshal(), multisigKey1, params}, expectedCost1, false}, {"unknown key", args{sdk.NewInfiniteGasMeter(), nil, nil, params}, 0, true}, } @@ -644,9 +646,9 @@ func expectedGasCostByKeys(pubkeys []crypto.PubKey) uint64 { pubkeyType := strings.ToLower(fmt.Sprintf("%T", pubkey)) switch { case strings.Contains(pubkeyType, "ed25519"): - cost += DefaultParams().SigVerifyCostED25519 + cost += types.DefaultParams().SigVerifyCostED25519 case strings.Contains(pubkeyType, "secp256k1"): - cost += DefaultParams().SigVerifyCostSecp256k1 + cost += types.DefaultParams().SigVerifyCostSecp256k1 default: panic("unexpected key type") } @@ -682,16 +684,16 @@ func TestCountSubkeys(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(T *testing.T) { - require.Equal(t, tt.want, CountSubKeys(tt.args.pub)) + require.Equal(t, tt.want, types.CountSubKeys(tt.args.pub)) }) } } func TestAnteHandlerSigLimitExceeded(t *testing.T) { // setup - input := setupTestInput() - anteHandler := NewAnteHandler(input.ak, input.sk, DefaultSigVerificationGasConsumer) - ctx := input.ctx.WithBlockHeight(1) + input := keeper.SetupTestInput() + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, DefaultSigVerificationGasConsumer) + ctx := input.Ctx.WithBlockHeight(1) // keys and addresses priv1, _, addr1 := types.KeyTestPubAddr() @@ -704,13 +706,13 @@ func TestAnteHandlerSigLimitExceeded(t *testing.T) { priv8, _, addr8 := types.KeyTestPubAddr() // set the accounts - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) acc1.SetCoins(types.NewTestCoins()) - input.ak.SetAccount(ctx, acc1) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + input.AccountKeeper.SetAccount(ctx, acc1) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) acc2.SetCoins(types.NewTestCoins()) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) var tx sdk.Tx msg := types.NewTestMsg(addr1, addr2, addr3, addr4, addr5, addr6, addr7, addr8) @@ -726,8 +728,8 @@ func TestAnteHandlerSigLimitExceeded(t *testing.T) { func TestEnsureSufficientMempoolFees(t *testing.T) { // setup - input := setupTestInput() - ctx := input.ctx.WithMinGasPrices( + input := keeper.SetupTestInput() + ctx := input.Ctx.WithMinGasPrices( sdk.DecCoins{ sdk.NewDecCoinFromDec("photino", sdk.NewDecWithPrec(50000000000000, sdk.Precision)), // 0.0001photino sdk.NewDecCoinFromDec("stake", sdk.NewDecWithPrec(10000000000000, sdk.Precision)), // 0.000001stake @@ -735,16 +737,16 @@ func TestEnsureSufficientMempoolFees(t *testing.T) { ) testCases := []struct { - input StdFee + input types.StdFee expectedOK bool }{ - {NewStdFee(200000, sdk.Coins{}), false}, - {NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("photino", 5))), false}, - {NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("stake", 1))), false}, - {NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("stake", 2))), true}, - {NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("photino", 10))), true}, + {types.NewStdFee(200000, sdk.Coins{}), false}, + {types.NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("photino", 5))), false}, + {types.NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("stake", 1))), false}, + {types.NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("stake", 2))), true}, + {types.NewStdFee(200000, sdk.NewCoins(sdk.NewInt64Coin("photino", 10))), true}, { - NewStdFee( + types.NewStdFee( 200000, sdk.NewCoins( sdk.NewInt64Coin("photino", 10), @@ -754,7 +756,7 @@ func TestEnsureSufficientMempoolFees(t *testing.T) { true, }, { - NewStdFee( + types.NewStdFee( 200000, sdk.NewCoins( sdk.NewInt64Coin("atom", 5), @@ -778,9 +780,9 @@ func TestEnsureSufficientMempoolFees(t *testing.T) { // Test custom SignatureVerificationGasConsumer func TestCustomSignatureVerificationGasConsumer(t *testing.T) { // setup - input := setupTestInput() + input := keeper.SetupTestInput() // setup an ante handler that only accepts PubKeyEd25519 - anteHandler := NewAnteHandler(input.ak, input.sk, func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params) sdk.Result { + anteHandler := NewAnteHandler(input.AccountKeeper, input.SupplyKeeper, func(meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params) sdk.Result { switch pubkey := pubkey.(type) { case ed25519.PubKeyEd25519: meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519") @@ -789,13 +791,13 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { return sdk.ErrInvalidPubKey(fmt.Sprintf("unrecognized public key type: %T", pubkey)).Result() } }) - ctx := input.ctx.WithBlockHeight(1) + ctx := input.Ctx.WithBlockHeight(1) // verify that an secp256k1 account gets rejected priv1, _, addr1 := types.KeyTestPubAddr() - acc1 := input.ak.NewAccountWithAddress(ctx, addr1) + acc1 := input.AccountKeeper.NewAccountWithAddress(ctx, addr1) _ = acc1.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150))) - input.ak.SetAccount(ctx, acc1) + input.AccountKeeper.SetAccount(ctx, acc1) var tx sdk.Tx msg := types.NewTestMsg(addr1) @@ -809,10 +811,10 @@ func TestCustomSignatureVerificationGasConsumer(t *testing.T) { priv2 := ed25519.GenPrivKey() pub2 := priv2.PubKey() addr2 := sdk.AccAddress(pub2.Address()) - acc2 := input.ak.NewAccountWithAddress(ctx, addr2) + acc2 := input.AccountKeeper.NewAccountWithAddress(ctx, addr2) require.NoError(t, acc2.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("atom", 150)))) require.NoError(t, acc2.SetAccountNumber(1)) - input.ak.SetAccount(ctx, acc2) + input.AccountKeeper.SetAccount(ctx, acc2) msg = types.NewTestMsg(addr2) privs, accnums, seqs = []crypto.PrivKey{priv2}, []uint64{1}, []uint64{0} fee = types.NewTestStdFee() diff --git a/x/auth/keeper.go b/x/auth/keeper.go deleted file mode 100644 index f70d44305..000000000 --- a/x/auth/keeper.go +++ /dev/null @@ -1,195 +0,0 @@ -package auth - -import ( - "fmt" - - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/params/subspace" -) - -// AccountKeeper encodes/decodes accounts using the go-amino (binary) -// encoding/decoding library. -type AccountKeeper struct { - // The (unexposed) key used to access the store from the Context. - key sdk.StoreKey - - // The prototypical Account constructor. - proto func() exported.Account - - // The codec codec for binary encoding/decoding of accounts. - cdc *codec.Codec - - paramSubspace subspace.Subspace -} - -// NewAccountKeeper returns a new sdk.AccountKeeper that uses go-amino to -// (binary) encode and decode concrete sdk.Accounts. -// nolint -func NewAccountKeeper( - cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() exported.Account, -) AccountKeeper { - - return AccountKeeper{ - key: key, - proto: proto, - cdc: cdc, - paramSubspace: paramstore.WithKeyTable(types.ParamKeyTable()), - } -} - -// Logger returns a module-specific logger. -func (ak AccountKeeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) -} - -// NewAccountWithAddress implements sdk.AccountKeeper. -func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) exported.Account { - acc := ak.proto() - err := acc.SetAddress(addr) - if err != nil { - // Handle w/ #870 - panic(err) - } - err = acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)) - if err != nil { - // Handle w/ #870 - panic(err) - } - return acc -} - -// NewAccount creates a new account -func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account { - if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil { - panic(err) - } - return acc -} - -// GetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) exported.Account { - store := ctx.KVStore(ak.key) - bz := store.Get(types.AddressStoreKey(addr)) - if bz == nil { - return nil - } - acc := ak.decodeAccount(bz) - return acc -} - -// GetAllAccounts returns all accounts in the accountKeeper. -func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) []exported.Account { - accounts := []exported.Account{} - appendAccount := func(acc exported.Account) (stop bool) { - accounts = append(accounts, acc) - return false - } - ak.IterateAccounts(ctx, appendAccount) - return accounts -} - -// SetAccount implements sdk.AccountKeeper. -func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc exported.Account) { - addr := acc.GetAddress() - store := ctx.KVStore(ak.key) - bz, err := ak.cdc.MarshalBinaryBare(acc) - if err != nil { - panic(err) - } - store.Set(types.AddressStoreKey(addr), bz) -} - -// RemoveAccount removes an account for the account mapper store. -// NOTE: this will cause supply invariant violation if called -func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc exported.Account) { - addr := acc.GetAddress() - store := ctx.KVStore(ak.key) - store.Delete(types.AddressStoreKey(addr)) -} - -// IterateAccounts implements sdk.AccountKeeper. -func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, process func(exported.Account) (stop bool)) { - store := ctx.KVStore(ak.key) - iter := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) - defer iter.Close() - for { - if !iter.Valid() { - return - } - val := iter.Value() - acc := ak.decodeAccount(val) - if process(acc) { - return - } - iter.Next() - } -} - -// GetPubKey Returns the PubKey of the account at address -func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) { - acc := ak.GetAccount(ctx, addr) - if acc == nil { - return nil, sdk.ErrUnknownAddress(fmt.Sprintf("account %s does not exist", addr)) - } - return acc.GetPubKey(), nil -} - -// GetSequence Returns the Sequence of the account at address -func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint64, sdk.Error) { - acc := ak.GetAccount(ctx, addr) - if acc == nil { - return 0, sdk.ErrUnknownAddress(fmt.Sprintf("account %s does not exist", addr)) - } - return acc.GetSequence(), nil -} - -// GetNextAccountNumber Returns and increments the global account number counter -func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { - var accNumber uint64 - store := ctx.KVStore(ak.key) - bz := store.Get(types.GlobalAccountNumberKey) - if bz == nil { - accNumber = 0 - } else { - err := ak.cdc.UnmarshalBinaryLengthPrefixed(bz, &accNumber) - if err != nil { - panic(err) - } - } - - bz = ak.cdc.MustMarshalBinaryLengthPrefixed(accNumber + 1) - store.Set(types.GlobalAccountNumberKey, bz) - - return accNumber -} - -// ----------------------------------------------------------------------------- -// Params - -// SetParams sets the auth module's parameters. -func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) { - ak.paramSubspace.SetParamSet(ctx, ¶ms) -} - -// GetParams gets the auth module's parameters. -func (ak AccountKeeper) GetParams(ctx sdk.Context) (params types.Params) { - ak.paramSubspace.GetParamSet(ctx, ¶ms) - return -} - -// ----------------------------------------------------------------------------- -// Misc. - -func (ak AccountKeeper) decodeAccount(bz []byte) (acc exported.Account) { - err := ak.cdc.UnmarshalBinaryBare(bz, &acc) - if err != nil { - panic(err) - } - return -} diff --git a/x/auth/keeper/account.go b/x/auth/keeper/account.go new file mode 100644 index 000000000..8417a4a34 --- /dev/null +++ b/x/auth/keeper/account.go @@ -0,0 +1,80 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// NewAccountWithAddress implements sdk.AccountKeeper. +func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) exported.Account { + acc := ak.proto() + err := acc.SetAddress(addr) + if err != nil { + panic(err) + } + return ak.NewAccount(ctx, acc) +} + +// NewAccount sets the next account number to a given account interface +func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) exported.Account { + if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil { + panic(err) + } + return acc +} + +// GetAccount implements sdk.AccountKeeper. +func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) exported.Account { + store := ctx.KVStore(ak.key) + bz := store.Get(types.AddressStoreKey(addr)) + if bz == nil { + return nil + } + acc := ak.decodeAccount(bz) + return acc +} + +// GetAllAccounts returns all accounts in the accountKeeper. +func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) (accounts []exported.Account) { + ak.IterateAccounts(ctx, + func(acc exported.Account) (stop bool) { + accounts = append(accounts, acc) + return false + }) + return accounts +} + +// SetAccount implements sdk.AccountKeeper. +func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc exported.Account) { + addr := acc.GetAddress() + store := ctx.KVStore(ak.key) + bz, err := ak.cdc.MarshalBinaryBare(acc) + if err != nil { + panic(err) + } + store.Set(types.AddressStoreKey(addr), bz) +} + +// RemoveAccount removes an account for the account mapper store. +// NOTE: this will cause supply invariant violation if called +func (ak AccountKeeper) RemoveAccount(ctx sdk.Context, acc exported.Account) { + addr := acc.GetAddress() + store := ctx.KVStore(ak.key) + store.Delete(types.AddressStoreKey(addr)) +} + +// IterateAccounts iterates over all the stored accounts and performs a callback function +func (ak AccountKeeper) IterateAccounts(ctx sdk.Context, cb func(account exported.Account) (stop bool)) { + store := ctx.KVStore(ak.key) + iterator := sdk.KVStorePrefixIterator(store, types.AddressStoreKeyPrefix) + + defer iterator.Close() + for ; iterator.Valid(); iterator.Next() { + account := ak.decodeAccount(iterator.Value()) + + if cb(account) { + break + } + } +} diff --git a/x/auth/keeper/keeper.go b/x/auth/keeper/keeper.go new file mode 100644 index 000000000..d60a396d3 --- /dev/null +++ b/x/auth/keeper/keeper.go @@ -0,0 +1,100 @@ +package keeper + +import ( + "fmt" + + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/params/subspace" +) + +// AccountKeeper encodes/decodes accounts using the go-amino (binary) +// encoding/decoding library. +type AccountKeeper struct { + // The (unexposed) key used to access the store from the Context. + key sdk.StoreKey + + // The prototypical Account constructor. + proto func() exported.Account + + // The codec codec for binary encoding/decoding of accounts. + cdc *codec.Codec + + paramSubspace subspace.Subspace +} + +// NewAccountKeeper returns a new sdk.AccountKeeper that uses go-amino to +// (binary) encode and decode concrete sdk.Accounts. +// nolint +func NewAccountKeeper( + cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() exported.Account, +) AccountKeeper { + + return AccountKeeper{ + key: key, + proto: proto, + cdc: cdc, + paramSubspace: paramstore.WithKeyTable(types.ParamKeyTable()), + } +} + +// Logger returns a module-specific logger. +func (ak AccountKeeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +} + +// GetPubKey Returns the PubKey of the account at address +func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.PubKey, sdk.Error) { + acc := ak.GetAccount(ctx, addr) + if acc == nil { + return nil, sdk.ErrUnknownAddress(fmt.Sprintf("account %s does not exist", addr)) + } + return acc.GetPubKey(), nil +} + +// GetSequence Returns the Sequence of the account at address +func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint64, sdk.Error) { + acc := ak.GetAccount(ctx, addr) + if acc == nil { + return 0, sdk.ErrUnknownAddress(fmt.Sprintf("account %s does not exist", addr)) + } + return acc.GetSequence(), nil +} + +// GetNextAccountNumber returns and increments the global account number counter. +// If the global account number is not set, it initializes it with value 0. +func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 { + var accNumber uint64 + store := ctx.KVStore(ak.key) + bz := store.Get(types.GlobalAccountNumberKey) + if bz == nil { + // initialize the account numbers + accNumber = 0 + } else { + err := ak.cdc.UnmarshalBinaryLengthPrefixed(bz, &accNumber) + if err != nil { + panic(err) + } + } + + bz = ak.cdc.MustMarshalBinaryLengthPrefixed(accNumber + 1) + store.Set(types.GlobalAccountNumberKey, bz) + + return accNumber +} + +// ----------------------------------------------------------------------------- +// Misc. + +func (ak AccountKeeper) decodeAccount(bz []byte) (acc exported.Account) { + err := ak.cdc.UnmarshalBinaryBare(bz, &acc) + if err != nil { + panic(err) + } + return +} diff --git a/x/auth/keeper_bench_test.go b/x/auth/keeper/keeper_bench_test.go similarity index 72% rename from x/auth/keeper_bench_test.go rename to x/auth/keeper/keeper_bench_test.go index 8a3ae6da5..fc9da6db1 100644 --- a/x/auth/keeper_bench_test.go +++ b/x/auth/keeper/keeper_bench_test.go @@ -1,4 +1,4 @@ -package auth +package keeper import ( "testing" @@ -7,25 +7,25 @@ import ( ) func BenchmarkAccountMapperGetAccountFound(b *testing.B) { - input := setupTestInput() + input := SetupTestInput() // assumes b.N < 2**24 for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} addr := sdk.AccAddress(arr) - acc := input.ak.NewAccountWithAddress(input.ctx, addr) - input.ak.SetAccount(input.ctx, acc) + acc := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr) + input.AccountKeeper.SetAccount(input.Ctx, acc) } b.ResetTimer() for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} - input.ak.GetAccount(input.ctx, sdk.AccAddress(arr)) + input.AccountKeeper.GetAccount(input.Ctx, sdk.AccAddress(arr)) } } func BenchmarkAccountMapperGetAccountFoundWithCoins(b *testing.B) { - input := setupTestInput() + input := SetupTestInput() coins := sdk.Coins{ sdk.NewCoin("LTC", sdk.NewInt(1000)), sdk.NewCoin("BTC", sdk.NewInt(1000)), @@ -39,20 +39,20 @@ func BenchmarkAccountMapperGetAccountFoundWithCoins(b *testing.B) { for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} addr := sdk.AccAddress(arr) - acc := input.ak.NewAccountWithAddress(input.ctx, addr) + acc := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr) acc.SetCoins(coins) - input.ak.SetAccount(input.ctx, acc) + input.AccountKeeper.SetAccount(input.Ctx, acc) } b.ResetTimer() for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} - input.ak.GetAccount(input.ctx, sdk.AccAddress(arr)) + input.AccountKeeper.GetAccount(input.Ctx, sdk.AccAddress(arr)) } } func BenchmarkAccountMapperSetAccount(b *testing.B) { - input := setupTestInput() + input := SetupTestInput() b.ResetTimer() @@ -60,13 +60,13 @@ func BenchmarkAccountMapperSetAccount(b *testing.B) { for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} addr := sdk.AccAddress(arr) - acc := input.ak.NewAccountWithAddress(input.ctx, addr) - input.ak.SetAccount(input.ctx, acc) + acc := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr) + input.AccountKeeper.SetAccount(input.Ctx, acc) } } func BenchmarkAccountMapperSetAccountWithCoins(b *testing.B) { - input := setupTestInput() + input := SetupTestInput() coins := sdk.Coins{ sdk.NewCoin("LTC", sdk.NewInt(1000)), sdk.NewCoin("BTC", sdk.NewInt(1000)), @@ -82,8 +82,8 @@ func BenchmarkAccountMapperSetAccountWithCoins(b *testing.B) { for i := 0; i < b.N; i++ { arr := []byte{byte((i & 0xFF0000) >> 16), byte((i & 0xFF00) >> 8), byte(i & 0xFF)} addr := sdk.AccAddress(arr) - acc := input.ak.NewAccountWithAddress(input.ctx, addr) + acc := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr) acc.SetCoins(coins) - input.ak.SetAccount(input.ctx, acc) + input.AccountKeeper.SetAccount(input.Ctx, acc) } } diff --git a/x/auth/keeper/keeper_test.go b/x/auth/keeper/keeper_test.go new file mode 100644 index 000000000..9e94a8be1 --- /dev/null +++ b/x/auth/keeper/keeper_test.go @@ -0,0 +1,91 @@ +package keeper + +import ( + "testing" + + "github.com/stretchr/testify/require" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestAccountMapperGetSet(t *testing.T) { + input := SetupTestInput() + addr := sdk.AccAddress([]byte("some-address")) + + // no account before its created + acc := input.AccountKeeper.GetAccount(input.Ctx, addr) + require.Nil(t, acc) + + // create account and check default values + acc = input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr) + require.NotNil(t, acc) + require.Equal(t, addr, acc.GetAddress()) + require.EqualValues(t, nil, acc.GetPubKey()) + require.EqualValues(t, 0, acc.GetSequence()) + + // NewAccount doesn't call Set, so it's still nil + require.Nil(t, input.AccountKeeper.GetAccount(input.Ctx, addr)) + + // set some values on the account and save it + newSequence := uint64(20) + acc.SetSequence(newSequence) + input.AccountKeeper.SetAccount(input.Ctx, acc) + + // check the new values + acc = input.AccountKeeper.GetAccount(input.Ctx, addr) + require.NotNil(t, acc) + require.Equal(t, newSequence, acc.GetSequence()) +} + +func TestAccountMapperRemoveAccount(t *testing.T) { + input := SetupTestInput() + addr1 := sdk.AccAddress([]byte("addr1")) + addr2 := sdk.AccAddress([]byte("addr2")) + + // create accounts + acc1 := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr1) + acc2 := input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr2) + + accSeq1 := uint64(20) + accSeq2 := uint64(40) + + acc1.SetSequence(accSeq1) + acc2.SetSequence(accSeq2) + input.AccountKeeper.SetAccount(input.Ctx, acc1) + input.AccountKeeper.SetAccount(input.Ctx, acc2) + + acc1 = input.AccountKeeper.GetAccount(input.Ctx, addr1) + require.NotNil(t, acc1) + require.Equal(t, accSeq1, acc1.GetSequence()) + + // remove one account + input.AccountKeeper.RemoveAccount(input.Ctx, acc1) + acc1 = input.AccountKeeper.GetAccount(input.Ctx, addr1) + require.Nil(t, acc1) + + acc2 = input.AccountKeeper.GetAccount(input.Ctx, addr2) + require.NotNil(t, acc2) + require.Equal(t, accSeq2, acc2.GetSequence()) +} + +func TestSetParams(t *testing.T) { + input := SetupTestInput() + params := types.DefaultParams() + + input.AccountKeeper.SetParams(input.Ctx, params) + + newParams := types.Params{} + input.AccountKeeper.paramSubspace.Get(input.Ctx, types.KeyTxSigLimit, &newParams.TxSigLimit) + require.Equal(t, newParams.TxSigLimit, types.DefaultTxSigLimit) +} + +func TestGetParams(t *testing.T) { + input := SetupTestInput() + params := types.DefaultParams() + + input.AccountKeeper.SetParams(input.Ctx, params) + + newParams := input.AccountKeeper.GetParams(input.Ctx) + require.Equal(t, params, newParams) +} diff --git a/x/auth/keeper/params.go b/x/auth/keeper/params.go new file mode 100644 index 000000000..0236c7ae1 --- /dev/null +++ b/x/auth/keeper/params.go @@ -0,0 +1,17 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +// SetParams sets the auth module's parameters. +func (ak AccountKeeper) SetParams(ctx sdk.Context, params types.Params) { + ak.paramSubspace.SetParamSet(ctx, ¶ms) +} + +// GetParams gets the auth module's parameters. +func (ak AccountKeeper) GetParams(ctx sdk.Context) (params types.Params) { + ak.paramSubspace.GetParamSet(ctx, ¶ms) + return +} diff --git a/x/auth/querier.go b/x/auth/keeper/querier.go similarity index 94% rename from x/auth/querier.go rename to x/auth/keeper/querier.go index ea2fd5c46..b40dc0135 100644 --- a/x/auth/querier.go +++ b/x/auth/keeper/querier.go @@ -1,4 +1,4 @@ -package auth +package keeper import ( "fmt" @@ -10,7 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/auth/types" ) -// creates a querier for auth REST endpoints +// NewQuerier creates a querier for auth REST endpoints func NewQuerier(keeper AccountKeeper) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, sdk.Error) { switch path[0] { diff --git a/x/auth/keeper/querier_test.go b/x/auth/keeper/querier_test.go new file mode 100644 index 000000000..0e5e7ba47 --- /dev/null +++ b/x/auth/keeper/querier_test.go @@ -0,0 +1,60 @@ +package keeper + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/x/auth/types" +) + +func TestQueryAccount(t *testing.T) { + input := SetupTestInput() + + req := abci.RequestQuery{ + Path: "", + Data: []byte{}, + } + + querier := NewQuerier(input.AccountKeeper) + + bz, err := querier(input.Ctx, []string{"other"}, req) + require.Error(t, err) + require.Nil(t, bz) + + req = abci.RequestQuery{ + Path: fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryAccount), + Data: []byte{}, + } + res, err := queryAccount(input.Ctx, req, input.AccountKeeper) + require.Error(t, err) + require.Nil(t, res) + + req.Data = input.cdc.MustMarshalJSON(types.NewQueryAccountParams([]byte(""))) + res, err = queryAccount(input.Ctx, req, input.AccountKeeper) + require.Error(t, err) + require.Nil(t, res) + + _, _, addr := types.KeyTestPubAddr() + req.Data = input.cdc.MustMarshalJSON(types.NewQueryAccountParams(addr)) + res, err = queryAccount(input.Ctx, req, input.AccountKeeper) + require.Error(t, err) + require.Nil(t, res) + + input.AccountKeeper.SetAccount(input.Ctx, input.AccountKeeper.NewAccountWithAddress(input.Ctx, addr)) + res, err = queryAccount(input.Ctx, req, input.AccountKeeper) + require.NoError(t, err) + require.NotNil(t, res) + + res, err = querier(input.Ctx, []string{types.QueryAccount}, req) + require.NoError(t, err) + require.NotNil(t, res) + + var account exported.Account + err2 := input.cdc.UnmarshalJSON(res, &account) + require.Nil(t, err2) +} diff --git a/x/auth/test_common.go b/x/auth/keeper/test_common.go similarity index 93% rename from x/auth/test_common.go rename to x/auth/keeper/test_common.go index 58ac87cf2..ee2a7fb49 100644 --- a/x/auth/test_common.go +++ b/x/auth/keeper/test_common.go @@ -1,5 +1,7 @@ // nolint -package auth +package keeper + +// DONTCOVER import ( abci "github.com/tendermint/tendermint/abci/types" @@ -16,10 +18,10 @@ import ( ) type testInput struct { - cdc *codec.Codec - ctx sdk.Context - ak AccountKeeper - sk types.SupplyKeeper + cdc *codec.Codec + Ctx sdk.Context + AccountKeeper AccountKeeper + SupplyKeeper types.SupplyKeeper } // moduleAccount defines an account for modules that holds coins on a pool @@ -49,7 +51,7 @@ func (ma moduleAccount) GetPermissions() []string { return ma.permissions } -func setupTestInput() testInput { +func SetupTestInput() testInput { db := dbm.NewMemDB() cdc := codec.New() @@ -76,7 +78,7 @@ func setupTestInput() testInput { ak.SetParams(ctx, types.DefaultParams()) - return testInput{cdc: cdc, ctx: ctx, ak: ak, sk: sk} + return testInput{cdc: cdc, Ctx: ctx, AccountKeeper: ak, SupplyKeeper: sk} } // DummySupplyKeeper defines a supply keeper used only for testing to avoid @@ -136,7 +138,7 @@ func (sk DummySupplyKeeper) GetModuleAccount(ctx sdk.Context, moduleName string) macc := &moduleAccount{ BaseAccount: &baseAcc, name: moduleName, - permissions: []string{"basic"}, + permissions: nil, } maccI := (sk.ak.NewAccount(ctx, macc)).(exported.ModuleAccountI) diff --git a/x/auth/keeper_test.go b/x/auth/keeper_test.go deleted file mode 100644 index 4285132cb..000000000 --- a/x/auth/keeper_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package auth - -import ( - "testing" - - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -func TestAccountMapperGetSet(t *testing.T) { - input := setupTestInput() - addr := sdk.AccAddress([]byte("some-address")) - - // no account before its created - acc := input.ak.GetAccount(input.ctx, addr) - require.Nil(t, acc) - - // create account and check default values - acc = input.ak.NewAccountWithAddress(input.ctx, addr) - require.NotNil(t, acc) - require.Equal(t, addr, acc.GetAddress()) - require.EqualValues(t, nil, acc.GetPubKey()) - require.EqualValues(t, 0, acc.GetSequence()) - - // NewAccount doesn't call Set, so it's still nil - require.Nil(t, input.ak.GetAccount(input.ctx, addr)) - - // set some values on the account and save it - newSequence := uint64(20) - acc.SetSequence(newSequence) - input.ak.SetAccount(input.ctx, acc) - - // check the new values - acc = input.ak.GetAccount(input.ctx, addr) - require.NotNil(t, acc) - require.Equal(t, newSequence, acc.GetSequence()) -} - -func TestAccountMapperRemoveAccount(t *testing.T) { - input := setupTestInput() - addr1 := sdk.AccAddress([]byte("addr1")) - addr2 := sdk.AccAddress([]byte("addr2")) - - // create accounts - acc1 := input.ak.NewAccountWithAddress(input.ctx, addr1) - acc2 := input.ak.NewAccountWithAddress(input.ctx, addr2) - - accSeq1 := uint64(20) - accSeq2 := uint64(40) - - acc1.SetSequence(accSeq1) - acc2.SetSequence(accSeq2) - input.ak.SetAccount(input.ctx, acc1) - input.ak.SetAccount(input.ctx, acc2) - - acc1 = input.ak.GetAccount(input.ctx, addr1) - require.NotNil(t, acc1) - require.Equal(t, accSeq1, acc1.GetSequence()) - - // remove one account - input.ak.RemoveAccount(input.ctx, acc1) - acc1 = input.ak.GetAccount(input.ctx, addr1) - require.Nil(t, acc1) - - acc2 = input.ak.GetAccount(input.ctx, addr2) - require.NotNil(t, acc2) - require.Equal(t, accSeq2, acc2.GetSequence()) -} - -func TestSetParams(t *testing.T) { - input := setupTestInput() - params := DefaultParams() - - input.ak.SetParams(input.ctx, params) - - newParams := Params{} - input.ak.paramSubspace.Get(input.ctx, KeyTxSigLimit, &newParams.TxSigLimit) - require.Equal(t, newParams.TxSigLimit, DefaultTxSigLimit) -} - -func TestGetParams(t *testing.T) { - input := setupTestInput() - params := DefaultParams() - - input.ak.SetParams(input.ctx, params) - - newParams := input.ak.GetParams(input.ctx) - require.Equal(t, params, newParams) -} diff --git a/x/auth/querier_test.go b/x/auth/querier_test.go deleted file mode 100644 index a73b12a40..000000000 --- a/x/auth/querier_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package auth - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" - - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/x/auth/types" -) - -func Test_queryAccount(t *testing.T) { - input := setupTestInput() - req := abci.RequestQuery{ - Path: fmt.Sprintf("custom/%s/%s", QuerierRoute, QueryAccount), - Data: []byte{}, - } - - res, err := queryAccount(input.ctx, req, input.ak) - require.NotNil(t, err) - require.Nil(t, res) - - req.Data = input.cdc.MustMarshalJSON(types.NewQueryAccountParams([]byte(""))) - res, err = queryAccount(input.ctx, req, input.ak) - require.NotNil(t, err) - require.Nil(t, res) - - _, _, addr := types.KeyTestPubAddr() - req.Data = input.cdc.MustMarshalJSON(types.NewQueryAccountParams(addr)) - res, err = queryAccount(input.ctx, req, input.ak) - require.NotNil(t, err) - require.Nil(t, res) - - input.ak.SetAccount(input.ctx, input.ak.NewAccountWithAddress(input.ctx, addr)) - res, err = queryAccount(input.ctx, req, input.ak) - require.Nil(t, err) - require.NotNil(t, res) - - var account Account - err2 := input.cdc.UnmarshalJSON(res, &account) - require.Nil(t, err2) -} diff --git a/x/mock/app.go b/x/mock/app.go index 591b3110d..cadde5841 100644 --- a/x/mock/app.go +++ b/x/mock/app.go @@ -18,6 +18,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/params" ) @@ -38,7 +39,7 @@ type App struct { AccountKeeper auth.AccountKeeper ParamsKeeper params.Keeper - GenesisAccounts []auth.Account + GenesisAccounts []authexported.Account TotalCoinsSupply sdk.Coins } @@ -167,7 +168,7 @@ func (b AddrKeysSlice) Swap(i, j int) { // CreateGenAccounts generates genesis accounts loaded with coins, and returns // their addresses, pubkeys, and privkeys. -func CreateGenAccounts(numAccs int, genCoins sdk.Coins) (genAccs []auth.Account, +func CreateGenAccounts(numAccs int, genCoins sdk.Coins) (genAccs []authexported.Account, addrs []sdk.AccAddress, pubKeys []crypto.PubKey, privKeys []crypto.PrivKey) { addrKeysSlice := AddrKeysSlice{} @@ -196,7 +197,7 @@ func CreateGenAccounts(numAccs int, genCoins sdk.Coins) (genAccs []auth.Account, } // SetGenesis sets the mock app genesis accounts. -func SetGenesis(app *App, accs []auth.Account) { +func SetGenesis(app *App, accs []authexported.Account) { // Pass the accounts in via the application (lazy) instead of through // RequestInitChain. app.GenesisAccounts = accs @@ -283,7 +284,7 @@ func GeneratePrivKeyAddressPairsFromRand(rand *rand.Rand, n int) (keys []crypto. // provided addresses and coin denominations. // nolint: errcheck func RandomSetGenesis(r *rand.Rand, app *App, addrs []sdk.AccAddress, denoms []string) { - accts := make([]auth.Account, len(addrs)) + accts := make([]authexported.Account, len(addrs)) randCoinIntervals := []BigInterval{ {sdk.NewIntWithDecimal(1, 0), sdk.NewIntWithDecimal(1, 1)}, {sdk.NewIntWithDecimal(1, 2), sdk.NewIntWithDecimal(1, 3)}, diff --git a/x/slashing/internal/types/expected_keepers.go b/x/slashing/internal/types/expected_keepers.go index c73ab095e..776817416 100644 --- a/x/slashing/internal/types/expected_keepers.go +++ b/x/slashing/internal/types/expected_keepers.go @@ -4,14 +4,14 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/staking/exported" + stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" ) // AccountKeeper expected account keeper type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(auth.Account) (stop bool)) + IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) } // ParamSubspace defines the expected Subspace interfacace @@ -26,10 +26,10 @@ type ParamSubspace interface { type StakingKeeper interface { // iterate through validators by operator address, execute func for each validator IterateValidators(sdk.Context, - func(index int64, validator exported.ValidatorI) (stop bool)) + func(index int64, validator stakingexported.ValidatorI) (stop bool)) - Validator(sdk.Context, sdk.ValAddress) exported.ValidatorI // get a particular validator by operator address - ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) exported.ValidatorI // get a particular validator by consensus address + Validator(sdk.Context, sdk.ValAddress) stakingexported.ValidatorI // get a particular validator by operator address + ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingexported.ValidatorI // get a particular validator by consensus address // slash the validator and delegators of the validator, specifying offence height, offence power, and slash fraction Slash(sdk.Context, sdk.ConsAddress, int64, int64, sdk.Dec) @@ -38,7 +38,7 @@ type StakingKeeper interface { // Delegation allows for getting a particular delegation for a given validator // and delegator outside the scope of the staking module. - Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) exported.DelegationI + Delegation(sdk.Context, sdk.AccAddress, sdk.ValAddress) stakingexported.DelegationI // MaxValidators returns the maximum amount of bonded validators MaxValidators(sdk.Context) uint16 diff --git a/x/staking/types/expected_keepers.go b/x/staking/types/expected_keepers.go index 8e8485791..e172d5a86 100644 --- a/x/staking/types/expected_keepers.go +++ b/x/staking/types/expected_keepers.go @@ -2,7 +2,7 @@ package types import ( sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/exported" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" stakingexported "github.com/cosmos/cosmos-sdk/x/staking/exported" "github.com/cosmos/cosmos-sdk/x/supply" supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported" @@ -16,7 +16,7 @@ type DistributionKeeper interface { // AccountKeeper defines the expected account keeper (noalias) type AccountKeeper interface { - IterateAccounts(ctx sdk.Context, process func(exported.Account) (stop bool)) + IterateAccounts(ctx sdk.Context, process func(authexported.Account) (stop bool)) } // SupplyKeeper defines the expected supply Keeper (noalias) diff --git a/x/supply/genesis.go b/x/supply/genesis.go index 8084f8c02..ddef25116 100644 --- a/x/supply/genesis.go +++ b/x/supply/genesis.go @@ -2,7 +2,7 @@ package supply import ( sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/exported" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" ) @@ -14,7 +14,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, ak types.AccountKeeper, data Ge if data.Supply.Total.Empty() { var totalSupply sdk.Coins ak.IterateAccounts(ctx, - func(acc authtypes.Account) (stop bool) { + func(acc authexported.Account) (stop bool) { totalSupply = totalSupply.Add(acc.GetCoins()) return false }, diff --git a/x/supply/internal/keeper/common_test.go b/x/supply/internal/keeper/common_test.go index b54170982..8e4bf2c60 100644 --- a/x/supply/internal/keeper/common_test.go +++ b/x/supply/internal/keeper/common_test.go @@ -14,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/x/auth" + authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" "github.com/cosmos/cosmos-sdk/x/bank" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/supply/internal/types" @@ -93,7 +94,7 @@ func createTestInput(t *testing.T, isCheckTx bool, initPower int64, nAccs int64) } // nolint: unparam deadcode unused -func createTestAccs(ctx sdk.Context, numAccs int, initialCoins sdk.Coins, ak *auth.AccountKeeper) (accs []auth.Account) { +func createTestAccs(ctx sdk.Context, numAccs int, initialCoins sdk.Coins, ak *auth.AccountKeeper) (accs []authexported.Account) { for i := 0; i < numAccs; i++ { privKey := secp256k1.GenPrivKey() pubKey := privKey.PubKey()