diff --git a/baseapp/abci.go b/baseapp/abci.go index 5495ee0b0..f451e8610 100644 --- a/baseapp/abci.go +++ b/baseapp/abci.go @@ -71,11 +71,6 @@ func (app *BaseApp) InitChain(ctx context.Context, req *abci.RequestInitChain) ( return } - // add block gas meter for any genesis transactions (allow infinite gas) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - app.prepareProposalState.ctx = app.prepareProposalState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - app.processProposalState.ctx = app.processProposalState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - resp := app.initChainer(app.deliverState.ctx, *req) app.initChainer(app.prepareProposalState.ctx, *req) app.initChainer(app.processProposalState.ctx, *req) @@ -1034,16 +1029,9 @@ func (app *BaseApp) ProcessProposal(ctx context.Context, req *abci.RequestProces app.setProcessProposalHeader(header) } - // add block gas meter - var gasMeter sdk.GasMeter - if maxGas := app.getMaximumBlockGas(app.processProposalState.ctx); maxGas > 0 { - gasMeter = sdk.NewGasMeter(maxGas) - } else { - gasMeter = sdk.NewInfiniteGasMeter() - } - // NOTE: header hash is not set in NewContext, so we manually set it here - app.prepareProcessProposalState(gasMeter, req.Hash) + + app.prepareProcessProposalState(req.Hash) defer func() { if err := recover(); err != nil { @@ -1116,22 +1104,14 @@ func (app *BaseApp) FinalizeBlock(ctx context.Context, req *abci.RequestFinalize app.setDeliverStateHeader(header) } - // add block gas meter - var gasMeter sdk.GasMeter - if maxGas := app.getMaximumBlockGas(app.deliverState.ctx); maxGas > 0 { - gasMeter = sdk.NewGasMeter(maxGas) - } else { - gasMeter = sdk.NewInfiniteGasMeter() - } - // NOTE: header hash is not set in NewContext, so we manually set it here - app.prepareDeliverState(gasMeter, req.Hash) + app.prepareDeliverState(req.Hash) // we also set block gas meter to checkState in case the application needs to // verify gas consumption during (Re)CheckTx if app.checkState != nil { - app.checkState.SetContext(app.checkState.ctx.WithBlockGasMeter(gasMeter).WithHeaderHash(req.Hash)) + app.checkState.SetContext(app.checkState.ctx.WithHeaderHash(req.Hash)) } if app.finalizeBlocker != nil { diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index fe53f5fe6..07f577de4 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -613,8 +613,8 @@ func (app *BaseApp) preparePrepareProposalState() { } } -func (app *BaseApp) prepareProcessProposalState(gasMeter sdk.GasMeter, headerHash []byte) { - app.processProposalState.SetContext(app.processProposalState.Context().WithBlockGasMeter(gasMeter). +func (app *BaseApp) prepareProcessProposalState(headerHash []byte) { + app.processProposalState.SetContext(app.processProposalState.Context(). WithHeaderHash(headerHash). WithConsensusParams(app.GetConsensusParams(app.processProposalState.Context()))) @@ -623,9 +623,8 @@ func (app *BaseApp) prepareProcessProposalState(gasMeter sdk.GasMeter, headerHas } } -func (app *BaseApp) prepareDeliverState(gasMeter sdk.GasMeter, headerHash []byte) { +func (app *BaseApp) prepareDeliverState(headerHash []byte) { app.deliverState.SetContext(app.deliverState.Context(). - WithBlockGasMeter(gasMeter). WithHeaderHash(headerHash). WithConsensusParams(app.GetConsensusParams(app.deliverState.Context()))) } @@ -724,27 +723,6 @@ func (app *BaseApp) StoreConsensusParams(ctx sdk.Context, cp *tmproto.ConsensusP app.paramStore.Set(ctx, ParamStoreKeyABCIParams, cp.Abci) } -// getMaximumBlockGas gets the maximum gas from the consensus params. It panics -// if maximum block gas is less than negative one and returns zero if negative -// one. -func (app *BaseApp) getMaximumBlockGas(ctx sdk.Context) uint64 { - cp := app.GetConsensusParams(ctx) - if cp == nil || cp.Block == nil { - return 0 - } - - maxGas := cp.Block.MaxGas - - // TODO::: This is a temporary fix, max gas causes non-deterministic behavior - // with parallel TX - switch { - case maxGas < -1: - panic(fmt.Sprintf("invalid maximum block gas: %d", maxGas)) - default: - return 0 - } -} - func (app *BaseApp) validateHeight(req abci.RequestBeginBlock) error { if req.Header.Height < 1 { return fmt.Errorf("invalid height: %d", req.Header.Height) @@ -879,11 +857,6 @@ func (app *BaseApp) runTx(ctx sdk.Context, mode runTxMode, txBytes []byte) (gInf ms := ctx.MultiStore() - // only run the tx if there is block gas remaining - if mode == runTxModeDeliver && ctx.BlockGasMeter().IsOutOfGas() { - return gInfo, nil, nil, -1, sdkerrors.Wrap(sdkerrors.ErrOutOfGas, "no block gas left to run tx") - } - defer func() { if r := recover(); r != nil { acltypes.SendAllSignalsForTx(ctx.TxCompletionChannels()) @@ -896,27 +869,6 @@ func (app *BaseApp) runTx(ctx sdk.Context, mode runTxMode, txBytes []byte) (gInf gInfo = sdk.GasInfo{GasWanted: gasWanted, GasUsed: ctx.GasMeter().GasConsumed()} }() - blockGasConsumed := false - // consumeBlockGas makes sure block gas is consumed at most once. It must happen after - // tx processing, and must be execute even if tx processing fails. Hence we use trick with `defer` - consumeBlockGas := func() { - if !blockGasConsumed { - blockGasConsumed = true - ctx.BlockGasMeter().ConsumeGas( - ctx.GasMeter().GasConsumedToLimit(), "block gas meter", - ) - } - } - - // If BlockGasMeter() panics it will be caught by the above recover and will - // return an error - in any case BlockGasMeter will consume gas past the limit. - // - // NOTE: This must exist in a separate defer function for the above recovery - // to recover from this one. - if mode == runTxModeDeliver { - defer consumeBlockGas() - } - tx, err := app.txDecoder(txBytes) if err != nil { return sdk.GasInfo{}, nil, nil, 0, err @@ -1004,9 +956,6 @@ func (app *BaseApp) runTx(ctx sdk.Context, mode runTxMode, txBytes []byte) (gInf result, err = app.runMsgs(runMsgCtx, msgs, mode) if err == nil && mode == runTxModeDeliver { - // When block gas exceeds, it'll panic and won't commit the cached store. - consumeBlockGas() - msCache.Write() } // we do this since we will only be looking at result in DeliverTx diff --git a/baseapp/block_gas_test.go b/baseapp/block_gas_test.go deleted file mode 100644 index 2d154709c..000000000 --- a/baseapp/block_gas_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package baseapp_test - -import ( - "context" - "encoding/json" - "fmt" - "math" - "testing" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - dbm "github.com/tendermint/tm-db" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/tx" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - txtypes "github.com/cosmos/cosmos-sdk/types/tx" - "github.com/cosmos/cosmos-sdk/types/tx/signing" - xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" -) - -func TestBaseApp_BlockGas(t *testing.T) { - testcases := []struct { - name string - gasToConsume uint64 // gas to consume in the msg execution - panicTx bool // panic explicitly in tx execution - expErr bool - }{ - {"less than block gas meter", 10, false, false}, - // {"more than block gas meter", blockMaxGas, false, true}, - // {"more than block gas meter", uint64(float64(blockMaxGas) * 1.2), false, true}, - // {"consume MaxUint64", math.MaxUint64, false, true}, - {"consume MaxGasWanted", txtypes.MaxGasWanted, false, true}, - {"consume block gas when paniced", 10, true, true}, - } - for _, tc := range testcases { - t.Run(tc.name, func(t *testing.T) { - var app *simapp.SimApp - routerOpt := func(bapp *baseapp.BaseApp) { - route := (&testdata.TestMsg{}).Route() - bapp.Router().AddRoute(sdk.NewRoute(route, func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { - _, ok := msg.(*testdata.TestMsg) - if !ok { - return &sdk.Result{}, fmt.Errorf("Wrong Msg type, expected %T, got %T", (*testdata.TestMsg)(nil), msg) - } - ctx.KVStore(app.GetKey(banktypes.ModuleName)).Set([]byte("ok"), []byte("ok")) - ctx.GasMeter().ConsumeGas(tc.gasToConsume, "TestMsg") - if tc.panicTx { - panic("panic in tx execution") - } - return &sdk.Result{}, nil - })) - } - encCfg := simapp.MakeTestEncodingConfig() - encCfg.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil) - encCfg.InterfaceRegistry.RegisterImplementations((*sdk.Msg)(nil), - &testdata.TestMsg{}, - ) - app = simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, map[int64]bool{}, "", 0, nil, encCfg, &simapp.EmptyAppOptions{}, routerOpt) - genState := simapp.NewDefaultGenesisState(encCfg.Marshaler) - stateBytes, err := json.MarshalIndent(genState, "", " ") - require.NoError(t, err) - app.InitChain(context.Background(), &abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: simapp.DefaultConsensusParams, - AppStateBytes: stateBytes, - }) - - ctx := app.NewContext(false, tmproto.Header{}) - - // tx fee - feeCoin := sdk.NewCoin("atom", sdk.NewInt(150)) - feeAmount := sdk.NewCoins(feeCoin) - - // test account and fund - priv1, _, addr1 := testdata.KeyTestPubAddr() - err = app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, feeAmount) - require.NoError(t, err) - err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr1, feeAmount) - require.NoError(t, err) - require.Equal(t, feeCoin.Amount, app.BankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount) - seq, _ := app.AccountKeeper.GetSequence(ctx, addr1) - require.Equal(t, uint64(0), seq) - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - - txBuilder := encCfg.TxConfig.NewTxBuilder() - require.NoError(t, txBuilder.SetMsgs(msg)) - txBuilder.SetFeeAmount(feeAmount) - txBuilder.SetGasLimit(txtypes.MaxGasWanted) // tx validation checks that gasLimit can't be bigger than this - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{6}, []uint64{0} - _, txBytes, err := createTestTx(encCfg.TxConfig, txBuilder, privs, accNums, accSeqs, ctx.ChainID()) - require.NoError(t, err) - - rsp, _ := app.FinalizeBlock(context.Background(), &abci.RequestFinalizeBlock{ - Height: 1, - Txs: [][]byte{txBytes}, - }) - - // check result - ctx = app.GetContextForDeliverTx(txBytes) - okValue := ctx.KVStore(app.GetKey(banktypes.ModuleName)).Get([]byte("ok")) - - if tc.expErr { - if tc.panicTx { - require.Equal(t, sdkerrors.ErrPanic.ABCICode(), rsp.TxResults[0].Code) - } else { - require.Equal(t, sdkerrors.ErrOutOfGas.ABCICode(), rsp.TxResults[0].Code) - } - require.Empty(t, okValue) - } else { - require.Equal(t, uint32(0), rsp.TxResults[0].Code) - require.Equal(t, []byte("ok"), okValue) - } - // check block gas is always consumed - this value may change if we update the logic for - // how gas is consumed - baseGas := uint64(62766) // baseGas is the gas consumed before tx msg - expGasConsumed := addUint64Saturating(tc.gasToConsume, baseGas) - if expGasConsumed > txtypes.MaxGasWanted { - // capped by gasLimit - expGasConsumed = txtypes.MaxGasWanted - } - require.Equal(t, int(expGasConsumed), int(ctx.BlockGasMeter().GasConsumed())) - // tx fee is always deducted - require.Equal(t, 0, int(app.BankKeeper.GetBalance(ctx, addr1, feeCoin.Denom).Amount.Int64())) - // sender's sequence is always increased - seq, err = app.AccountKeeper.GetSequence(ctx, addr1) - require.NoError(t, err) - require.Equal(t, uint64(1), seq) - }) - } -} - -func createTestTx(txConfig client.TxConfig, txBuilder client.TxBuilder, privs []cryptotypes.PrivKey, accNums []uint64, accSeqs []uint64, chainID string) (xauthsigning.Tx, []byte, error) { - // First round: we gather all the signer infos. We use the "set empty - // signature" hack to do that. - var sigsV2 []signing.SignatureV2 - for i, priv := range privs { - sigV2 := signing.SignatureV2{ - PubKey: priv.PubKey(), - Data: &signing.SingleSignatureData{ - SignMode: txConfig.SignModeHandler().DefaultMode(), - Signature: nil, - }, - Sequence: accSeqs[i], - } - - sigsV2 = append(sigsV2, sigV2) - } - err := txBuilder.SetSignatures(sigsV2...) - if err != nil { - return nil, nil, err - } - - // Second round: all signer infos are set, so each signer can sign. - sigsV2 = []signing.SignatureV2{} - for i, priv := range privs { - signerData := xauthsigning.SignerData{ - ChainID: chainID, - AccountNumber: accNums[i], - Sequence: accSeqs[i], - } - sigV2, err := tx.SignWithPrivKey( - txConfig.SignModeHandler().DefaultMode(), signerData, - txBuilder, priv, txConfig, accSeqs[i]) - if err != nil { - return nil, nil, err - } - - sigsV2 = append(sigsV2, sigV2) - } - err = txBuilder.SetSignatures(sigsV2...) - if err != nil { - return nil, nil, err - } - - txBytes, err := txConfig.TxEncoder()(txBuilder.GetTx()) - if err != nil { - return nil, nil, err - } - - return txBuilder.GetTx(), txBytes, nil -} - -func addUint64Saturating(a, b uint64) uint64 { - if math.MaxUint64-a < b { - return math.MaxUint64 - } - - return a + b -} diff --git a/baseapp/deliver_tx_batch_test.go b/baseapp/deliver_tx_batch_test.go index c8a29b8b7..c3d92b4bd 100644 --- a/baseapp/deliver_tx_batch_test.go +++ b/baseapp/deliver_tx_batch_test.go @@ -111,7 +111,6 @@ func TestDeliverTxBatch(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) var requests []*sdk.DeliverTxEntry diff --git a/baseapp/deliver_tx_test.go b/baseapp/deliver_tx_test.go index c9fdc767d..0e144e4a7 100644 --- a/baseapp/deliver_tx_test.go +++ b/baseapp/deliver_tx_test.go @@ -219,7 +219,6 @@ func TestWithRouter(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) for i := 0; i < txPerHeight; i++ { @@ -267,7 +266,6 @@ func TestBaseApp_EndBlock(t *testing.T) { app.Seal() app.setDeliverState(tmproto.Header{}) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) res := app.EndBlock(app.deliverState.ctx, abci.RequestEndBlock{}) require.Empty(t, app.deliverState.ctx.MultiStore().GetEvents()) @@ -323,7 +321,6 @@ func TestQuery(t *testing.T) { // query is still empty after a DeliverTx before we commit header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) _, resTx, err = app.Deliver(aminoTxEncoder(), tx) @@ -352,7 +349,6 @@ func TestGRPCQuery(t *testing.T) { app.InitChain(context.Background(), &abci.RequestInitChain{}) header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -434,7 +430,6 @@ func TestMultiMsgDeliverTx(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(0, 0, 1, 2) txBytes, err := codec.Marshal(tx) @@ -517,7 +512,6 @@ func TestSimulateTx(t *testing.T) { count := int64(blockN + 1) header := tmproto.Header{Height: count} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(count, count) @@ -577,7 +571,6 @@ func TestRunInvalidTransaction(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // transaction with no messages @@ -706,7 +699,6 @@ func TestTxGasLimits(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) testCases := []struct { @@ -877,7 +869,6 @@ func TestCustomRunTxPanicHandler(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.AddRunTxRecoveryHandler(func(recoveryObj interface{}) error { @@ -921,7 +912,6 @@ func TestBaseAppAnteHandler(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) // execute a tx that will fail ante handler execution @@ -1035,7 +1025,6 @@ func TestGasConsumptionBadTx(t *testing.T) { header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewGasMeter(app.getMaximumBlockGas(app.deliverState.ctx))) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) tx := newTxCounter(5, 0) @@ -1046,13 +1035,7 @@ func TestGasConsumptionBadTx(t *testing.T) { res := app.DeliverTx(app.deliverState.ctx, abci.RequestDeliverTx{Tx: txBytes}) require.False(t, res.IsOK(), fmt.Sprintf("%v", res)) - // require next tx to fail due to black gas limit - tx = newTxCounter(5, 0) - txBytes, err = cdc.Marshal(tx) - require.NoError(t, err) - - res = app.DeliverTx(app.deliverState.ctx, abci.RequestDeliverTx{Tx: txBytes}) - require.False(t, res.IsOK(), fmt.Sprintf("%v", res)) + // removed the block gas exceeded because of removal of block gas meter, gasWanted < max block gas is still fulfilled by various other checks } func TestInitChainer(t *testing.T) { @@ -1132,7 +1115,6 @@ func TestInitChainer(t *testing.T) { // commit and ensure we can still query header := tmproto.Header{Height: app.LastBlockHeight() + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1172,7 +1154,6 @@ func TestBeginBlock_WithInitialHeight(t *testing.T) { ) app.setDeliverState(tmproto.Header{Height: 4}) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) require.PanicsWithError(t, "invalid height: 4; expected: 3", func() { app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{ Header: tmproto.Header{ @@ -1465,11 +1446,9 @@ func TestCheckTx(t *testing.T) { // If a block is committed, CheckTx state should be reset. header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.checkState.ctx = app.checkState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()).WithHeaderHash([]byte("hash")) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) + app.checkState.ctx = app.checkState.ctx.WithHeaderHash([]byte("hash")) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header, Hash: []byte("hash")}) - require.NotNil(t, app.checkState.ctx.BlockGasMeter(), "block gas meter should have been set to checkState") require.NotEmpty(t, app.checkState.ctx.HeaderHash()) app.EndBlock(app.deliverState.ctx, abci.RequestEndBlock{}) @@ -1510,7 +1489,6 @@ func TestDeliverTx(t *testing.T) { for blockN := 0; blockN < nBlocks; blockN++ { header := tmproto.Header{Height: int64(blockN) + 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) for i := 0; i < txPerHeight; i++ { @@ -1663,7 +1641,6 @@ func TestLoadVersionInvalid(t *testing.T) { header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1715,7 +1692,6 @@ func setupBaseAppWithSnapshots(t *testing.T, blocks uint, blockTxs int, options keyCounter := 0 for height := int64(1); height <= int64(blocks); height++ { app.setDeliverState(tmproto.Header{Height: height}) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: tmproto.Header{Height: height}}) for txNum := 0; txNum < blockTxs; txNum++ { tx := txTest{Msgs: []sdk.Msg{}} @@ -1793,7 +1769,6 @@ func TestLoadVersion(t *testing.T) { // execute a block, collect commit ID header := tmproto.Header{Height: 1} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1801,7 +1776,6 @@ func TestLoadVersion(t *testing.T) { // execute a block, collect commit ID header = tmproto.Header{Height: 2} app.setDeliverState(header) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: header}) app.SetDeliverStateToCommit() app.Commit(context.Background()) @@ -1885,7 +1859,6 @@ func TestSetLoader(t *testing.T) { // "execute" one block app.setDeliverState(tmproto.Header{Height: 2}) - app.deliverState.ctx = app.deliverState.ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) app.BeginBlock(app.deliverState.ctx, abci.RequestBeginBlock{Header: tmproto.Header{Height: 2}}) app.SetDeliverStateToCommit() app.Commit(context.Background()) diff --git a/types/context.go b/types/context.go index e36e88dc8..8ba51ef25 100644 --- a/types/context.go +++ b/types/context.go @@ -24,23 +24,22 @@ but please do not over-use it. We try to keep all data structured and standard additions here would be better just to add to the Context struct */ type Context struct { - ctx context.Context - ms MultiStore - header tmproto.Header - headerHash tmbytes.HexBytes - chainID string - txBytes []byte - logger log.Logger - voteInfo []abci.VoteInfo - gasMeter GasMeter - blockGasMeter GasMeter - occEnabled bool - checkTx bool - recheckTx bool // if recheckTx == true, then checkTx must also be true - minGasPrice DecCoins - consParams *tmproto.ConsensusParams - eventManager *EventManager - priority int64 // The tx priority, only relevant in CheckTx + ctx context.Context + ms MultiStore + header tmproto.Header + headerHash tmbytes.HexBytes + chainID string + txBytes []byte + logger log.Logger + voteInfo []abci.VoteInfo + gasMeter GasMeter + occEnabled bool + checkTx bool + recheckTx bool // if recheckTx == true, then checkTx must also be true + minGasPrice DecCoins + consParams *tmproto.ConsensusParams + eventManager *EventManager + priority int64 // The tx priority, only relevant in CheckTx txBlockingChannels acltypes.MessageAccessOpsChannelMapping txCompletionChannels acltypes.MessageAccessOpsChannelMapping @@ -93,10 +92,6 @@ func (c Context) GasMeter() GasMeter { return c.gasMeter } -func (c Context) BlockGasMeter() GasMeter { - return c.blockGasMeter -} - func (c Context) IsCheckTx() bool { return c.checkTx } @@ -274,12 +269,6 @@ func (c Context) WithGasMeter(meter GasMeter) Context { return c } -// WithBlockGasMeter returns a Context with an updated block GasMeter -func (c Context) WithBlockGasMeter(meter GasMeter) Context { - c.blockGasMeter = meter - return c -} - // WithIsCheckTx enables or disables CheckTx value for verifying transactions and returns an updated Context func (c Context) WithIsCheckTx(isCheckTx bool) Context { c.checkTx = isCheckTx diff --git a/types/context_test.go b/types/context_test.go index e49a82903..12d71b67b 100644 --- a/types/context_test.go +++ b/types/context_test.go @@ -92,7 +92,6 @@ func (s *contextTestSuite) TestContextWithCustom() { logger := mocks.NewMockLogger(ctrl) voteinfos := []abci.VoteInfo{{}} meter := types.NewGasMeter(10000) - blockGasMeter := types.NewGasMeter(20000) minGasPrices := types.DecCoins{types.NewInt64DecCoin("feetoken", 1)} headerHash := []byte("headerHash") @@ -106,7 +105,6 @@ func (s *contextTestSuite) TestContextWithCustom() { WithVoteInfos(voteinfos). WithGasMeter(meter). WithMinGasPrices(minGasPrices). - WithBlockGasMeter(blockGasMeter). WithHeaderHash(headerHash). WithIsOCCEnabled(isOCC) @@ -119,7 +117,6 @@ func (s *contextTestSuite) TestContextWithCustom() { s.Require().Equal(voteinfos, ctx.VoteInfos()) s.Require().Equal(meter, ctx.GasMeter()) s.Require().Equal(minGasPrices, ctx.MinGasPrices()) - s.Require().Equal(blockGasMeter, ctx.BlockGasMeter()) s.Require().Equal(headerHash, ctx.HeaderHash().Bytes()) s.Require().False(ctx.WithIsCheckTx(false).IsCheckTx()) diff --git a/x/capability/capability_test.go b/x/capability/capability_test.go index 45a5f6ea4..8f09d6d73 100644 --- a/x/capability/capability_test.go +++ b/x/capability/capability_test.go @@ -61,14 +61,10 @@ func (suite *CapabilityTestSuite) TestInitializeMemStore() { suite.Require().False(newKeeper.IsInitialized(ctx), "memstore initialized flag set before BeginBlock") // Mock app beginblock and ensure that no gas has been consumed and memstore is initialized - ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}).WithBlockGasMeter(sdk.NewGasMeter(50)) - prevGas := ctx.BlockGasMeter().GasConsumed() + ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) restartedModule := capability.NewAppModule(suite.cdc, *newKeeper) restartedModule.BeginBlock(ctx, abci.RequestBeginBlock{}) suite.Require().True(newKeeper.IsInitialized(ctx), "memstore initialized flag not set") - gasUsed := ctx.BlockGasMeter().GasConsumed() - - suite.Require().Equal(prevGas, gasUsed, "beginblocker consumed gas during execution") // Mock the first transaction getting capability and subsequently failing // by using a cached context and discarding all cached writes. diff --git a/x/capability/genesis_test.go b/x/capability/genesis_test.go index 875ea9793..70aabb729 100644 --- a/x/capability/genesis_test.go +++ b/x/capability/genesis_test.go @@ -6,7 +6,6 @@ import ( dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/simapp" - sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/capability" "github.com/cosmos/cosmos-sdk/x/capability/keeper" @@ -40,7 +39,7 @@ func (suite *CapabilityTestSuite) TestGenesis() { newKeeper := keeper.NewKeeper(suite.cdc, newApp.GetKey(types.StoreKey), newApp.GetMemKey(types.MemStoreKey)) newSk1 := newKeeper.ScopeToModule(banktypes.ModuleName) newSk2 := newKeeper.ScopeToModule(stakingtypes.ModuleName) - deliverCtx, _ := newApp.BaseApp.NewUncachedContext(false, tmproto.Header{}).WithBlockGasMeter(sdk.NewInfiniteGasMeter()).CacheContext() + deliverCtx, _ := newApp.BaseApp.NewUncachedContext(false, tmproto.Header{}).CacheContext() capability.InitGenesis(deliverCtx, *newKeeper, *genState) diff --git a/x/capability/keeper/keeper.go b/x/capability/keeper/keeper.go index 35b8addf4..4ba2579cf 100644 --- a/x/capability/keeper/keeper.go +++ b/x/capability/keeper/keeper.go @@ -111,12 +111,9 @@ func (k *Keeper) InitMemStore(ctx sdk.Context) { panic(fmt.Sprintf("invalid memory store type; got %s, expected: %s", memStoreType, sdk.StoreTypeMemory)) } - // create context with no block gas meter to ensure we do not consume gas during local initialization logic. - noGasCtx := ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) - // check if memory store has not been initialized yet by checking if initialized flag is nil. - if !k.IsInitialized(noGasCtx) { - prefixStore := prefix.NewStore(noGasCtx.KVStore(k.storeKey), types.KeyPrefixIndexCapability) + if !k.IsInitialized(ctx) { + prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefixIndexCapability) iterator := sdk.KVStorePrefixIterator(prefixStore, nil) // initialize the in-memory store for all persisted capabilities @@ -128,11 +125,11 @@ func (k *Keeper) InitMemStore(ctx sdk.Context) { var capOwners types.CapabilityOwners k.cdc.MustUnmarshal(iterator.Value(), &capOwners) - k.InitializeCapability(noGasCtx, index, capOwners) + k.InitializeCapability(ctx, index, capOwners) } // set the initialized flag so we don't rerun initialization logic - memStore := noGasCtx.KVStore(k.memKey) + memStore := ctx.KVStore(k.memKey) memStore.Set(types.KeyMemInitialized, []byte{1}) } } diff --git a/x/upgrade/abci.go b/x/upgrade/abci.go index e0791bc0c..a5e5d7ea8 100644 --- a/x/upgrade/abci.go +++ b/x/upgrade/abci.go @@ -111,7 +111,6 @@ func panicUpgradeNeeded(k keeper.Keeper, ctx sdk.Context, plan types.Plan) { func applyUpgrade(k keeper.Keeper, ctx sdk.Context, plan types.Plan) { ctx.Logger().Info(fmt.Sprintf("applying upgrade \"%s\" at %s", plan.Name, plan.DueAt())) - ctx = ctx.WithBlockGasMeter(sdk.NewInfiniteGasMeter()) k.ApplyUpgrade(ctx, plan) }