Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Modular AnteHandler #4583

Closed
wants to merge 12 commits into from
Prev Previous commit
Next Next commit
propogate changes to modules and move feecollectionkeeper to distribu…
…tion
  • Loading branch information
AdityaSripal committed Jun 20, 2019
commit a98d14282993899c7392e371d9b91bf354c97a00
4 changes: 4 additions & 0 deletions server/mock/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ func (tx kvstoreTx) GetMsgs() []sdk.Msg {
return []sdk.Msg{tx}
}

func (tx kvstoreTx) Gas() uint64 {
return 0
}

func (tx kvstoreTx) GetMemo() string {
return ""
}
Expand Down
1 change: 1 addition & 0 deletions types/module/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ needlessly defining many placeholder functions
package module

import (
"fmt"
"encoding/json"

"github.com/gorilla/mux"
Expand Down
6 changes: 3 additions & 3 deletions types/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,12 +130,12 @@ func NewInfiniteGasMeter() GasMeter {
}

// SetGasMeter returns a new context with a gas meter set from a given context.
func SetGasMeter(simulate bool, ctx sdk.Context, gasLimit uint64) sdk.Context {
func SetGasMeter(simulate bool, ctx Context, gasLimit uint64) Context {
// In various cases such as simulation and during the genesis block, we do not
// meter any gas utilization.
if simulate || ctx.BlockHeight() == 0 {
return ctx.WithGasMeter(sdk.NewInfiniteGasMeter())
return ctx.WithGasMeter(NewInfiniteGasMeter())
}

return ctx.WithGasMeter(sdk.NewGasMeter(gasLimit))
return ctx.WithGasMeter(NewGasMeter(gasLimit))
}
1 change: 0 additions & 1 deletion x/auth/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ type (
BaseVestingAccount = types.BaseVestingAccount
ContinuousVestingAccount = types.ContinuousVestingAccount
DelayedVestingAccount = types.DelayedVestingAccount
FeeCollectionKeeper = types.FeeCollectionKeeper
GenesisState = types.GenesisState
Params = types.Params
QueryAccountParams = types.QueryAccountParams
Expand Down
97 changes: 47 additions & 50 deletions x/auth/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"bytes"
"encoding/hex"
"fmt"
"time"

"github.com/tendermint/tendermint/crypto/ed25519"

Expand Down Expand Up @@ -35,72 +34,70 @@ type SignatureVerificationGasConsumer = func(meter sdk.GasMeter, sig []byte, pub
// 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, sigGasConsumer SignatureVerificationGasConsumer) sdk.AnteHandler {
return func(
func AnteHandler(ak AccountKeeper, sigGasConsumer SignatureVerificationGasConsumer,
ctx sdk.Context, tx sdk.Tx, simulate bool,
) (newCtx sdk.Context, res sdk.Result, abort bool) {

// all transactions must be of type auth.StdTx
stdTx, ok := tx.(StdTx)
if !ok {
// Set a gas meter with limit 0 as to prevent an infinite gas meter attack
// during runTx.
newCtx = sdk.SetGasMeter(simulate, ctx, 0)
return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true
}
// all transactions must be of type auth.StdTx
stdTx, ok := tx.(StdTx)
if !ok {
// Set a gas meter with limit 0 as to prevent an infinite gas meter attack
// during runTx.
newCtx = sdk.SetGasMeter(simulate, ctx, 0)
return newCtx, sdk.ErrInternal("tx must be StdTx").Result(), true
}

params := ak.GetParams(ctx)
params := ak.GetParams(ctx)

if res := ValidateTxBasic(ctx, tx, params); res != nil {
return newCtx, res, true
}
if res := ValidateTxBasic(ctx, tx, params); !res.IsOK() {
return newCtx, res, true
}

if res := ValidateSigCount(stdTx, params); !res.IsOK() {
return newCtx, res, true
}
if res := ValidateSigCount(stdTx, params); !res.IsOK() {
return newCtx, res, true
}

if res := ValidateMemo(stdTx, params); !res.IsOK() {
return newCtx, res, true
}
if res := ValidateMemo(stdTx, params); !res.IsOK() {
return newCtx, res, true
}

// 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))
isGenesis := ctx.BlockHeight() == 0
// 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))
isGenesis := ctx.BlockHeight() == 0

// fetch first signer, who's going to pay the fees
signerAccs[0], res = GetSignerAcc(newCtx, ak, signerAddrs[0])
if !res.IsOK() {
return newCtx, res, true
}
// fetch first signer, who's going to pay the fees
signerAccs[0], res = GetSignerAcc(newCtx, ak, signerAddrs[0])
if !res.IsOK() {
return newCtx, res, true
}

// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
stdSigs := stdTx.GetSignatures()

for i := 0; i < len(stdSigs); i++ {
// skip the fee payer, account is cached and fees were deducted already
if i != 0 {
signerAccs[i], res = GetSignerAcc(newCtx, ak, signerAddrs[i])
if !res.IsOK() {
return newCtx, res, true
}
}
// stdSigs contains the sequence number, account number, and signatures.
// When simulating, this would just be a 0-length slice.
stdSigs := stdTx.GetSignatures()

// check signature, return account with incremented nonce
signBytes := GetSignBytes(newCtx.ChainID(), stdTx, signerAccs[i], isGenesis)
signerAccs[i], res = processSig(newCtx, signerAccs[i], stdSigs[i], signBytes, simulate, params, sigGasConsumer)
for i := 0; i < len(stdSigs); i++ {
// skip the fee payer, account is cached and fees were deducted already
if i != 0 {
signerAccs[i], res = GetSignerAcc(newCtx, ak, signerAddrs[i])
if !res.IsOK() {
return newCtx, res, true
}
}

ak.SetAccount(newCtx, signerAccs[i])
// check signature, return account with incremented nonce
signBytes := GetSignBytes(newCtx.ChainID(), stdTx, signerAccs[i], isGenesis)
signerAccs[i], res = processSig(newCtx, signerAccs[i], stdSigs[i], signBytes, simulate, params, sigGasConsumer)
if !res.IsOK() {
return newCtx, res, true
}

// TODO: tx tags (?)
return newCtx, sdk.Result{GasWanted: stdTx.Fee.Gas}, false // continue...
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
Expand Down Expand Up @@ -136,7 +133,7 @@ func ValidateTxBasic(ctx sdk.Context, tx sdk.Tx, params Params) sdk.Result {
return err.Result()
}

ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*sdk.Gas(len(newCtx.TxBytes())), "txSize")
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*sdk.Gas(len(ctx.TxBytes())), "txSize")
return sdk.Result{}
}

Expand Down
6 changes: 2 additions & 4 deletions x/auth/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import (
)

// InitGenesis - Init store state from genesis data
func InitGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper, data types.GenesisState) {
func InitGenesis(ctx sdk.Context, ak AccountKeeper, data types.GenesisState) {
ak.SetParams(ctx, data.Params)
fck.AddCollectedFees(ctx, data.CollectedFees)
}

// ExportGenesis returns a GenesisState for a given context and keeper
func ExportGenesis(ctx sdk.Context, ak AccountKeeper, fck types.FeeCollectionKeeper) types.GenesisState {
collectedFees := fck.GetCollectedFees(ctx)
params := ak.GetParams(ctx)

return types.NewGenesisState(collectedFees, params)
return types.NewGenesisState(params)
}
3 changes: 1 addition & 2 deletions x/auth/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {

// module ante-handle
func (am AppModule) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, res sdk.Result, abort bool) {
antehandler := NewAnteHandler(am.accountKeeper, sigGasConsumer)
return antehandler(ctx, tx, simulate)
return AnteHandler(am.accountKeeper, am.sigGasConsumer, ctx, tx, simulate)
}

// module begin-block
Expand Down
8 changes: 2 additions & 6 deletions x/auth/types/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,23 @@ package types

import (
"fmt"

sdk "github.com/cosmos/cosmos-sdk/types"
)

// GenesisState - all auth state that must be provided at genesis
type GenesisState struct {
CollectedFees sdk.Coins `json:"collected_fees"`
Params Params `json:"params"`
}

// NewGenesisState - Create a new genesis state
func NewGenesisState(collectedFees sdk.Coins, params Params) GenesisState {
func NewGenesisState(params Params) GenesisState {
return GenesisState{
CollectedFees: collectedFees,
Params: params,
}
}

// DefaultGenesisState - Return a default genesis state
func DefaultGenesisState() GenesisState {
return NewGenesisState(sdk.NewCoins(), DefaultParams())
return NewGenesisState(DefaultParams())
}

// ValidateGenesis performs basic validation of auth genesis data returning an
Expand Down
5 changes: 5 additions & 0 deletions x/auth/types/stdtx.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ func (tx StdTx) ValidateBasic() sdk.Error {
return nil
}

// Returns the Gas this tx is allowed to consume
func (tx StdTx) Gas() uint64 {
return tx.Fee.Gas
}

// CountSubKeys counts the total number of keys for a multi-sig public key.
func CountSubKeys(pub crypto.PubKey) int {
v, ok := pub.(multisig.PubKeyMultisigThreshold)
Expand Down
6 changes: 1 addition & 5 deletions x/auth/types/test_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import (
type testInput struct {
cdc *codec.Codec
ctx sdk.Context
fck FeeCollectionKeeper
}

func setupTestInput() testInput {
Expand All @@ -28,21 +27,18 @@ func setupTestInput() testInput {
RegisterBaseAccount(cdc)

authCapKey := sdk.NewKVStoreKey("authCapKey")
fckCapKey := sdk.NewKVStoreKey("fckCapKey")
keyParams := sdk.NewKVStoreKey("subspace")
tkeyParams := sdk.NewTransientStoreKey("transient_subspace")

ms := store.NewCommitMultiStore(db)
ms.MountStoreWithDB(authCapKey, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(fckCapKey, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db)
ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db)
ms.LoadLatestVersion()

fck := NewFeeCollectionKeeper(cdc, fckCapKey)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "test-chain-id"}, false, log.NewNopLogger())

return testInput{cdc: cdc, ctx: ctx, fck: fck}
return testInput{cdc: cdc, ctx: ctx}
}

func NewTestMsg(addrs ...sdk.AccAddress) *sdk.TestMsg {
Expand Down
5 changes: 5 additions & 0 deletions x/bank/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
return ModuleCdc.MustMarshalJSON(gs)
}

// module ante-handle
func (am AppModule) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, res sdk.Result, abort bool) {
return ctx, sdk.Result{}. false
}

// module begin-block
func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags {
return sdk.EmptyTags()
Expand Down
5 changes: 5 additions & 0 deletions x/crisis/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
return ModuleCdc.MustMarshalJSON(gs)
}

// module ante-handle
func (am AppModule) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, res sdk.Result, abort bool) {
return ctx, sdk.Result{}. false
}

// module begin-block
func (AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) sdk.Tags {
return sdk.EmptyTags()
Expand Down
6 changes: 2 additions & 4 deletions x/distribution/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth"
)

func NewAnteHandler(fck auth.FeeCollectionKeeper) sdk.AnteHandler {
return func(
ctx sdk.Context, tx sdk.Tx, simulate bool,
) (newCtx sdk.Context, res sdk.Result, abort bool) {
func NewAnteHandler(fck auth.FeeCollectionKeeper, ctx sdk.Context, tx sdk.Tx, simulate bool)
(newCtx sdk.Context, res sdk.Result, abort bool) {

// all transactions must be of type auth.StdTx
stdTx, ok := tx.(auth.StdTx)
Expand Down
8 changes: 5 additions & 3 deletions x/distribution/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import (
)

// InitGenesis sets distribution information for genesis
func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) {
func InitGenesis(ctx sdk.Context, keeper Keeper, fck types.FeeCollectionKeeper, data types.GenesisState) {
fck.AddCollectedFees(ctx, data.CollectedFees)
keeper.SetFeePool(ctx, data.FeePool)
keeper.SetCommunityTax(ctx, data.CommunityTax)
keeper.SetBaseProposerReward(ctx, data.BaseProposerReward)
Expand Down Expand Up @@ -37,7 +38,8 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) {
}

// ExportGenesis returns a GenesisState for a given context and keeper.
func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState {
func ExportGenesis(ctx sdk.Context, keeper Keeper, fck types.FeeCollectionKeeper) types.GenesisState {
collectedFees := fck.GetCollectedFees(ctx)
feePool := keeper.GetFeePool(ctx)
communityTax := keeper.GetCommunityTax(ctx)
baseProposerRewards := keeper.GetBaseProposerReward(ctx)
Expand Down Expand Up @@ -115,6 +117,6 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState {
return false
},
)
return types.NewGenesisState(feePool, communityTax, baseProposerRewards, bonusProposerRewards, withdrawAddrEnabled,
return types.NewGenesisState(feePool, collectedFees, communityTax, baseProposerRewards, bonusProposerRewards, withdrawAddrEnabled,
dwi, pp, outstanding, acc, his, cur, dels, slashes)
}
3 changes: 1 addition & 2 deletions x/distribution/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {

// module ante-handle
func (am AppModule) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool) (newCtx sdk.Context, res sdk.Result, abort bool) {
antehandler := NewAnteHandler(am.fck)
return antehandler(ctx, tx, simulate)
return AnteHandler(am.fck, ctx, tx, simulate)
}

// module begin-block
Expand Down
6 changes: 0 additions & 6 deletions x/distribution/types/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,3 @@ type StakingHooks interface {
type BankKeeper interface {
AddCoins(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coins) (sdk.Coins, sdk.Error)
}

// expected fee collection keeper
type FeeCollectionKeeper interface {
GetCollectedFees(ctx sdk.Context) sdk.Coins
ClearCollectedFees(ctx sdk.Context)
}
File renamed without changes.
File renamed without changes.
5 changes: 4 additions & 1 deletion x/distribution/types/genesis.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ type ValidatorSlashEventRecord struct {
// GenesisState - all distribution state that must be provided at genesis
type GenesisState struct {
FeePool FeePool `json:"fee_pool"`
CollectedFees sdk.Coins `json:"collected_fees"`
CommunityTax sdk.Dec `json:"community_tax"`
BaseProposerReward sdk.Dec `json:"base_proposer_reward"`
BonusProposerReward sdk.Dec `json:"bonus_proposer_reward"`
Expand All @@ -69,14 +70,15 @@ type GenesisState struct {
ValidatorSlashEvents []ValidatorSlashEventRecord `json:"validator_slash_events"`
}

func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusProposerReward sdk.Dec,
func NewGenesisState(feePool FeePool, collectedFees sdk.Coins, communityTax, baseProposerReward, bonusProposerReward sdk.Dec,
withdrawAddrEnabled bool, dwis []DelegatorWithdrawInfo, pp sdk.ConsAddress, r []ValidatorOutstandingRewardsRecord,
acc []ValidatorAccumulatedCommissionRecord, historical []ValidatorHistoricalRewardsRecord,
cur []ValidatorCurrentRewardsRecord, dels []DelegatorStartingInfoRecord,
slashes []ValidatorSlashEventRecord) GenesisState {

return GenesisState{
FeePool: feePool,
CollectedFees: collectedFees,
CommunityTax: communityTax,
BaseProposerReward: baseProposerReward,
BonusProposerReward: bonusProposerReward,
Expand All @@ -96,6 +98,7 @@ func NewGenesisState(feePool FeePool, communityTax, baseProposerReward, bonusPro
func DefaultGenesisState() GenesisState {
return GenesisState{
FeePool: InitialFeePool(),
CollectedFees: sdk.NewCoins(),
CommunityTax: sdk.NewDecWithPrec(2, 2), // 2%
BaseProposerReward: sdk.NewDecWithPrec(1, 2), // 1%
BonusProposerReward: sdk.NewDecWithPrec(4, 2), // 4%
Expand Down
Loading