Skip to content

Commit

Permalink
refactor(x/auth): use transaction service (#19967)
Browse files Browse the repository at this point in the history
  • Loading branch information
julienrbrt authored Apr 10, 2024
1 parent 76bb0cd commit 17bb4c7
Show file tree
Hide file tree
Showing 20 changed files with 157 additions and 50 deletions.
2 changes: 1 addition & 1 deletion core/transaction/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type ExecMode uint8
// For backwards compatibility and easier casting, the exec mode values must be the same as in cosmos/cosmos-sdk/types package.
const (
ExecModeCheck ExecMode = iota
_
ExecModeReCheck
ExecModeSimulate
_
_
Expand Down
4 changes: 2 additions & 2 deletions simapp/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
circuitante.NewCircuitBreakerDecorator(options.CircuitKeeper),
ante.NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
ante.NewValidateBasicDecorator(),
ante.NewValidateBasicDecorator(options.AccountKeeper.Environment()),
ante.NewTxTimeoutHeightDecorator(),
ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager),
ante.NewUnorderedTxDecorator(unorderedtx.DefaultMaxUnOrderedTTL, options.TxManager, options.AccountKeeper.Environment()),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper, options.TxFeeChecker),
Expand Down
6 changes: 4 additions & 2 deletions simapp/app_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,10 @@ var (
Config: appconfig.WrapAny(&slashingmodulev1.Module{}),
},
{
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{}),
Name: "tx",
Config: appconfig.WrapAny(&txconfigv1.Config{
SkipAnteHandler: true, // SimApp is using non default AnteHandler such as circuit and unorderedtx decorators
}),
},
{
Name: genutiltypes.ModuleName,
Expand Down
28 changes: 28 additions & 0 deletions simapp/app_di.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"cosmossdk.io/log"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/auth"
"cosmossdk.io/x/auth/ante"
"cosmossdk.io/x/auth/ante/unorderedtx"
authkeeper "cosmossdk.io/x/auth/keeper"
authsims "cosmossdk.io/x/auth/simulation"
Expand Down Expand Up @@ -292,13 +293,40 @@ func NewSimApp(
}
}

// set custom ante handlers
app.setCustomAnteHandler()

if err := app.Load(loadLatest); err != nil {
panic(err)
}

return app
}

// overwritte default ante handlers with custom ante handlers
// set SkipAnteHandler to true in app config and set custom ante handler on baseapp
func (app *SimApp) setCustomAnteHandler() {
anteHandler, err := NewAnteHandler(
HandlerOptions{
ante.HandlerOptions{
AccountKeeper: app.AuthKeeper,
BankKeeper: app.BankKeeper,
SignModeHandler: app.txConfig.SignModeHandler(),
FeegrantKeeper: app.FeeGrantKeeper,
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
},
&app.CircuitBreakerKeeper,
app.UnorderedTxManager,
},
)
if err != nil {
panic(err)
}

// Set the AnteHandler for the app
app.SetAnteHandler(anteHandler)
}

// Close implements the Application interface and closes all necessary application
// resources.
func (app *SimApp) Close() error {
Expand Down
6 changes: 3 additions & 3 deletions types/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ func (c Context) Logger() log.Logger { return c.logge
func (c Context) VoteInfos() []abci.VoteInfo { return c.voteInfo }
func (c Context) GasMeter() storetypes.GasMeter { return c.gasMeter }
func (c Context) BlockGasMeter() storetypes.GasMeter { return c.blockGasMeter }
func (c Context) IsCheckTx() bool { return c.checkTx } // Deprecated: use execMode instead
func (c Context) IsReCheckTx() bool { return c.recheckTx } // Deprecated: use execMode instead
func (c Context) IsCheckTx() bool { return c.checkTx } // Deprecated: use core/transaction service instead
func (c Context) IsReCheckTx() bool { return c.recheckTx } // Deprecated: use core/transaction service instead
func (c Context) IsSigverifyTx() bool { return c.sigverifyTx }
func (c Context) ExecMode() ExecMode { return c.execMode }
func (c Context) ExecMode() ExecMode { return c.execMode } // Deprecated: use core/transaction service instead
func (c Context) MinGasPrices() DecCoins { return c.minGasPrice }
func (c Context) EventManager() EventManagerI { return c.eventManager }
func (c Context) Priority() int64 { return c.priority }
Expand Down
1 change: 1 addition & 0 deletions x/auth/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Ref: https://keepachangelog.com/en/1.0.0/

### Improvements

* [#19967](https://github.com/cosmos/cosmos-sdk/pull/19967) Refactor ante handlers to use `transaction.Service` for getting exec mode.
* [#18780](https://github.com/cosmos/cosmos-sdk/pull/18780) Move sig verification out of the for loop, into the authenticate method.
* [#19188](https://github.com/cosmos/cosmos-sdk/pull/19188) Remove creation of `BaseAccount` when sending a message to an account that does not exist.
* When signing a transaction with an account that has not been created accountnumber 0 must be used
Expand Down
2 changes: 1 addition & 1 deletion x/auth/ante/ante.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
anteDecorators := []sdk.AnteDecorator{
NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
NewExtensionOptionsDecorator(options.ExtensionOptionChecker),
NewValidateBasicDecorator(),
NewValidateBasicDecorator(options.AccountKeeper.Environment()),
NewTxTimeoutHeightDecorator(),
NewValidateMemoDecorator(options.AccountKeeper),
NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
Expand Down
26 changes: 17 additions & 9 deletions x/auth/ante/basic.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package ante

import (
"cosmossdk.io/core/appmodule/v2"
"cosmossdk.io/core/transaction"
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/auth/migrations/legacytx"
Expand All @@ -18,15 +20,20 @@ import (
// If ValidateBasic passes, decorator calls next AnteHandler in chain. Note,
// ValidateBasicDecorator decorator will not get executed on ReCheckTx since it
// is not dependent on application state.
type ValidateBasicDecorator struct{}
type ValidateBasicDecorator struct {
env appmodule.Environment
}

func NewValidateBasicDecorator() ValidateBasicDecorator {
return ValidateBasicDecorator{}
func NewValidateBasicDecorator(env appmodule.Environment) ValidateBasicDecorator {
return ValidateBasicDecorator{
env: env,
}
}

func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, next sdk.AnteHandler) (sdk.Context, error) {
// no need to validate basic on recheck tx, call next antehandler
if ctx.ExecMode() == sdk.ExecModeReCheck {
txService := vbd.env.TransactionService
if txService.ExecMode(ctx) == transaction.ExecModeReCheck {
return next(ctx, tx, false)
}

Expand All @@ -36,7 +43,7 @@ func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool,
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// ValidateMemoDecorator will validate memo given the parameters passed in
Expand Down Expand Up @@ -69,7 +76,7 @@ func (vmd ValidateMemoDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool,
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// ConsumeTxSizeGasDecorator will take in parameters and consume gas proportional
Expand Down Expand Up @@ -101,7 +108,8 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*storetypes.Gas(len(ctx.TxBytes())), "txSize")

// simulate gas cost for signatures in simulate mode
if ctx.ExecMode() == sdk.ExecModeSimulate {
txService := cgts.ak.Environment().TransactionService
if txService.ExecMode(ctx) == transaction.ExecModeSimulate {
// in simulate mode, each element should be a nil signature
sigs, err := sigTx.GetSignaturesV2()
if err != nil {
Expand Down Expand Up @@ -143,7 +151,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// isIncompleteSignature tests whether SignatureData is fully filled in for simulation purposes
Expand Down Expand Up @@ -206,5 +214,5 @@ func (txh TxTimeoutHeightDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ boo
)
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}
2 changes: 1 addition & 1 deletion x/auth/ante/basic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func TestValidateBasic(t *testing.T) {
invalidTx, err := suite.CreateTestTx(suite.ctx, privs, accNums, accSeqs, suite.ctx.ChainID(), signing.SignMode_SIGN_MODE_DIRECT)
require.NoError(t, err)

vbd := ante.NewValidateBasicDecorator()
vbd := ante.NewValidateBasicDecorator(suite.accountKeeper.Environment())
antehandler := sdk.ChainAnteDecorators(vbd)
_, err = antehandler(suite.ctx, invalidTx, false)

Expand Down
8 changes: 7 additions & 1 deletion x/auth/ante/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,26 @@ import (
"context"

"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/x/auth/types"

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

type HasEnvironment interface {
Environment() appmodule.Environment
}

// AccountKeeper defines the contract needed for AccountKeeper related APIs.
// Interface provides support to use non-sdk AccountKeeper for AnteHandler's decorators.
type AccountKeeper interface {
GetParams(ctx context.Context) (params types.Params)
GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI
SetAccount(ctx context.Context, acc sdk.AccountI)
GetModuleAddress(moduleName string) sdk.AccAddress
AddressCodec() address.Codec
NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI
AddressCodec() address.Codec
Environment() appmodule.Environment
}

// FeegrantKeeper defines the expected feegrant keeper.
Expand Down
12 changes: 12 additions & 0 deletions x/auth/ante/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ante

import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
)

var SimSecp256k1PubkeyInternal = simSecp256k1Pubkey

func SetSVDPubKey(svd SigVerificationDecorator, ctx sdk.Context, acc sdk.AccountI, txPubKey cryptotypes.PubKey) error {
return svd.setPubKey(ctx, acc, txPubKey)
}
2 changes: 1 addition & 1 deletion x/auth/ante/ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (r RejectExtensionOptionsDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx,
return ctx, err
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

func checkExtOpts(tx sdk.Tx, checker ExtensionOptionChecker) error {
Expand Down
9 changes: 6 additions & 3 deletions x/auth/ante/fee.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"fmt"

"cosmossdk.io/core/transaction"
errorsmod "cosmossdk.io/errors"
"cosmossdk.io/x/auth/types"

Expand Down Expand Up @@ -45,7 +46,9 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, nex
return ctx, errorsmod.Wrap(sdkerrors.ErrTxDecode, "Tx must be a FeeTx")
}

if ctx.ExecMode() != sdk.ExecModeSimulate && ctx.BlockHeight() > 0 && feeTx.GetGas() == 0 {
txService := dfd.accountKeeper.Environment().TransactionService
execMode := txService.ExecMode(ctx)
if execMode != transaction.ExecModeSimulate && ctx.BlockHeight() > 0 && feeTx.GetGas() == 0 {
return ctx, errorsmod.Wrap(sdkerrors.ErrInvalidGasLimit, "must provide positive gas")
}

Expand All @@ -55,7 +58,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, nex
)

fee := feeTx.GetFee()
if ctx.ExecMode() != sdk.ExecModeSimulate {
if execMode != transaction.ExecModeSimulate {
fee, priority, err = dfd.txFeeChecker(ctx, tx)
if err != nil {
return ctx, err
Expand All @@ -67,7 +70,7 @@ func (dfd DeductFeeDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool, nex

newCtx := ctx.WithPriority(priority)

return next(newCtx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(newCtx, tx, false)
}

func (dfd DeductFeeDecorator) checkDeductFee(ctx sdk.Context, sdkTx sdk.Tx, fee sdk.Coins) error {
Expand Down
4 changes: 2 additions & 2 deletions x/auth/ante/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ func (sud SetUpContextDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ bool,
}
}()

return next(newCtx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(newCtx, tx, false)
}

// SetGasMeter returns a new context with a gas meter set from a given context.
func SetGasMeter(ctx sdk.Context, gasLimit uint64) sdk.Context {
// In various cases such as simulation and during the genesis block, we do not
// meter any gas utilization.
if ctx.ExecMode() == sdk.ExecModeSimulate || ctx.BlockHeight() == 0 {
if ctx.ExecMode() == sdk.ExecModeSimulate || ctx.BlockHeight() == 0 { // NOTE: using environment here breaks the API of SetGasMeter, an alternative must be found for server/v2. ref: https://github.com/cosmos/cosmos-sdk/issues/19640
return ctx.WithGasMeter(storetypes.NewInfiniteGasMeter())
}

Expand Down
11 changes: 6 additions & 5 deletions x/auth/ante/sigverify.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
secp256k1dcrd "github.com/decred/dcrd/dcrec/secp256k1/v4"
"google.golang.org/protobuf/types/known/anypb"

"cosmossdk.io/core/transaction"
errorsmod "cosmossdk.io/errors"
storetypes "cosmossdk.io/store/types"
aa_interface_v1 "cosmossdk.io/x/accounts/interfaces/account_abstraction/v1"
Expand Down Expand Up @@ -215,7 +216,7 @@ func (svd SigVerificationDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ boo

ctx.EventManager().EmitEvents(events)

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// authenticate the authentication of the TX for a specific tx signer.
Expand Down Expand Up @@ -280,7 +281,7 @@ func (svd SigVerificationDecorator) consumeSignatureGas(
pubKey cryptotypes.PubKey,
signature signing.SignatureV2,
) error {
if ctx.ExecMode() == sdk.ExecModeSimulate && pubKey == nil {
if svd.ak.Environment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate && pubKey == nil {
pubKey = simSecp256k1Pubkey
}

Expand Down Expand Up @@ -310,7 +311,7 @@ func (svd SigVerificationDecorator) verifySig(ctx sdk.Context, tx sdk.Tx, acc sd
// we're in simulation mode, or in ReCheckTx, or context is not
// on sig verify tx, then we do not need to verify the signatures
// in the tx.
if ctx.ExecMode() == sdk.ExecModeSimulate || ctx.IsReCheckTx() || !ctx.IsSigverifyTx() {
if svd.ak.Environment().TransactionService.ExecMode(ctx) == transaction.ExecModeSimulate || ctx.IsReCheckTx() || !ctx.IsSigverifyTx() {
return nil
}

Expand Down Expand Up @@ -384,7 +385,7 @@ func (svd SigVerificationDecorator) setPubKey(ctx sdk.Context, acc sdk.AccountI,
if txPubKey == nil {
// if we're not in simulation mode, and we do not have a valid pubkey
// for this signer, then we simply error.
if ctx.ExecMode() != sdk.ExecModeSimulate {
if svd.ak.Environment().TransactionService.ExecMode(ctx) != transaction.ExecModeSimulate {
return fmt.Errorf("the account %s is without a pubkey and did not provide a pubkey in the tx to set it", acc.GetAddress().String())
}
// if we're in simulation mode, then we can populate the pubkey with the
Expand Down Expand Up @@ -479,7 +480,7 @@ func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, _ b
}
}

return next(ctx, tx, ctx.ExecMode() == sdk.ExecModeSimulate)
return next(ctx, tx, false)
}

// DefaultSigVerificationGasConsumer is the default implementation of SignatureVerificationGasConsumer. It consumes gas
Expand Down
Loading

0 comments on commit 17bb4c7

Please sign in to comment.